golang实现Shopify API CRUD操作的插件库shopify的使用

Golang实现Shopify API CRUD操作的插件库shopify的使用

安装

go get github.com/rapito/go-shopify

使用说明

这是一个用Go语言编写的简单API,用于向您的Shopify商店发送CRUD请求。

基本GET请求示例

package main

import (
    "fmt"
    "github.com/rapito/go-shopify/shopify"
)

func main() {
    // 初始化Shopify客户端
    // storeDomain: 您的商店域名(如"your-store.myshopify.com")
    // apiKey: 您的API密钥
    // pass: 您的API密码
    shop := shopify.New(storeDomain, apiKey, pass)
    
    // 获取产品列表
    result, err := shop.Get("products")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Println(string(result))
}

完整CRUD操作示例

以下是一个完整的CRUD操作示例,包含创建、读取、更新和删除操作:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/rapito/go-shopify/shopify"
)

type Product struct {
    Title       string `json:"title"`
    BodyHTML    string `json:"body_html"`
    Vendor      string `json:"vendor"`
    ProductType string `json:"product_type"`
    Status      string `json:"status"`
}

func main() {
    // 初始化Shopify客户端
    shop := shopify.New("your-store.myshopify.com", "your-api-key", "your-api-password")

    // 1. 创建产品
    newProduct := Product{
        Title:       "Go Shopify Test Product",
        BodyHTML:    "<p>This is a test product created with go-shopify</p>",
        Vendor:      "Go Shopify",
        ProductType: "Test",
        Status:      "active",
    }
    
    productJSON, _ := json.Marshal(map[string]Product{"product": newProduct})
    createResult, err := shop.Post("products.json", productJSON)
    if err != nil {
        fmt.Println("Create error:", err)
        return
    }
    fmt.Println("Created product:", string(createResult))

    // 解析创建的产品ID
    var createdProduct struct {
        Product struct {
            ID int64 `json:"id"`
        } `json:"product"`
    }
    json.Unmarshal(createResult, &createdProduct)
    productID := createdProduct.Product.ID

    // 2. 获取单个产品
    getResult, err := shop.Get(fmt.Sprintf("products/%d.json", productID))
    if err != nil {
        fmt.Println("Get error:", err)
        return
    }
    fmt.Println("Product details:", string(getResult))

    // 3. 更新产品
    updatedProduct := Product{
        Title:       "Updated Go Shopify Test Product",
        BodyHTML:    "<p>This product has been updated</p>",
        Vendor:      "Go Shopify Updated",
        ProductType: "Test Updated",
        Status:      "active",
    }
    
    updateJSON, _ := json.Marshal(map[string]Product{"product": updatedProduct})
    updateResult, err := shop.Put(fmt.Sprintf("products/%d.json", productID), updateJSON)
    if err != nil {
        fmt.Println("Update error:", err)
        return
    }
    fmt.Println("Updated product:", string(updateResult))

    // 4. 删除产品
    deleteResult, err := shop.Delete(fmt.Sprintf("products/%d.json", productID))
    if err != nil {
        fmt.Println("Delete error:", err)
        return
    }
    fmt.Println("Delete result:", string(deleteResult))
}

其他说明

  1. 您可以在项目的examples文件夹中找到简单的使用示例
  2. 查看shopify_test.go文件中的测试用例可以获取完整的CRUD操作示例

贡献

  1. 您可以fork这个库并根据需要进行修改
  2. 您可以提交pull request,我会很高兴查看并合并它
  3. 如果您发现bug,可以创建issue,我会尽力修复它

原始工作

这个项目是受到hammond-bonesgo-shopify库启发而创建的。


更多关于golang实现Shopify API CRUD操作的插件库shopify的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang实现Shopify API CRUD操作的插件库shopify的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


使用Golang实现Shopify API的CRUD操作

Shopify是一个流行的电子商务平台,提供了丰富的API接口。下面我将介绍如何使用Golang实现Shopify API的基本CRUD(创建、读取、更新、删除)操作。

准备工作

首先,你需要安装Shopify API的Golang客户端库。推荐使用github.com/r0busta/go-shopify-graphqlgithub.com/bold-commerce/go-shopify

go get github.com/bold-commerce/go-shopify

初始化客户端

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/bold-commerce/go-shopify"
)

func main() {
	// 从环境变量获取Shopify凭证
	shopName := os.Getenv("SHOPIFY_SHOP_NAME")
	apiKey := os.Getenv("SHOPIFY_API_KEY")
	password := os.Getenv("SHOPIFY_API_PASSWORD")

	// 创建Shopify客户端
	client := shopify.NewClient(shopName, apiKey, password)

	// 测试连接
	testConnection(client)
}

func testConnection(client *shopify.Client) {
	// 获取商店信息
	shop, err := client.Shop.Get()
	if err != nil {
		log.Fatalf("连接Shopify失败: %v", err)
	}
	fmt.Printf("成功连接到商店: %s\n", shop.Name)
}

产品(Product)的CRUD操作

1. 创建产品(Create)

func createProduct(client *shopify.Client) {
	newProduct := shopify.Product{
		Title:       "Go编程书籍",
		BodyHTML:    "<p>一本关于Go语言的优秀书籍</p>",
		Vendor:      "Go出版社",
		ProductType: "书籍",
		Published:   true,
		Variants: []shopify.Variant{
			{
				Price: "39.99",
				Sku:   "GOBOOK-001",
			},
		},
	}

	product, err := client.Product.Create(newProduct)
	if err != nil {
		log.Fatalf("创建产品失败: %v", err)
	}
	fmt.Printf("创建产品成功! ID: %d, 标题: %s\n", product.ID, product.Title)
}

2. 读取产品(Read)

func getProducts(client *shopify.Client) {
	// 获取产品列表
	products, err := client.Product.List(nil)
	if err != nil {
		log.Fatalf("获取产品列表失败: %v", err)
	}

	fmt.Println("产品列表:")
	for _, p := range products {
		fmt.Printf("ID: %d, 标题: %s, 价格: %s\n", 
			p.ID, p.Title, p.Variants[0].Price)
	}

	// 获取单个产品详情
	if len(products) > 0 {
		productID := products[0].ID
		product, err := client.Product.Get(productID, nil)
		if err != nil {
			log.Fatalf("获取产品详情失败: %v", err)
		}
		fmt.Printf("\n产品详情:\n%+v\n", product)
	}
}

3. 更新产品(Update)

func updateProduct(client *shopify.Client, productID int64) {
	update := shopify.Product{
		ID:    productID,
		Title: "Go编程书籍(第二版)",
		BodyHTML: "<p>更新版的Go语言书籍,包含最新特性</p>",
		Variants: []shopify.Variant{
			{
				Price: "49.99",
			},
		},
	}

	product, err := client.Product.Update(update)
	if err != nil {
		log.Fatalf("更新产品失败: %v", err)
	}
	fmt.Printf("产品更新成功! 新标题: %s, 新价格: %s\n", 
		product.Title, product.Variants[0].Price)
}

4. 删除产品(Delete)

func deleteProduct(client *shopify.Client, productID int64) {
	err := client.Product.Delete(productID)
	if err != nil {
		log.Fatalf("删除产品失败: %v", err)
	}
	fmt.Printf("产品ID %d 已成功删除\n", productID)
}

订单(Order)操作示例

func orderOperations(client *shopify.Client) {
	// 获取订单列表
	orders, err := client.Order.List(nil)
	if err != nil {
		log.Fatalf("获取订单列表失败: %v", err)
	}

	fmt.Println("最近的订单:")
	for _, o := range orders {
		fmt.Printf("订单#%d 总价: %s 状态: %s\n", 
			o.OrderNumber, o.TotalPrice, o.FinancialStatus)
	}

	// 获取单个订单详情
	if len(orders) > 0 {
		order, err := client.Order.Get(orders[0].ID, nil)
		if err != nil {
			log.Fatalf("获取订单详情失败: %v", err)
		}
		fmt.Printf("\n订单详情:\n%+v\n", order)
	}
}

使用GraphQL API

如果需要更复杂的查询,可以使用Shopify的GraphQL API:

import (
	"context"
	"github.com/r0busta/go-shopify-graphql/v5"
	"github.com/r0busta/graphql"
)

func graphqlExample(shopName, accessToken string) {
	// 创建GraphQL客户端
	client := shopifygraphql.NewDefaultClient(shopName, accessToken)

	// 定义GraphQL查询
	query := `
		query {
			products(first: 5) {
				edges {
					node {
						id
						title
						variants(first: 1) {
							edges {
								node {
									price
								}
							}
						}
					}
				}
			}
		}
	`

	// 执行查询
	var result struct {
		Products struct {
			Edges []struct {
				Node struct {
					ID     string `json:"id"`
					Title  string `json:"title"`
					Variants struct {
						Edges []struct {
							Node struct {
								Price string `json:"price"`
							} `json:"node"`
						} `json:"edges"`
					} `json:"variants"`
				} `json:"node"`
			} `json:"edges"`
		} `json:"products"`
	}

	err := client.Query(context.Background(), query, nil, &result)
	if err != nil {
		log.Fatalf("GraphQL查询失败: %v", err)
	}

	fmt.Println("GraphQL查询结果:")
	for _, edge := range result.Products.Edges {
		fmt.Printf("产品: %s, 价格: %s\n", 
			edge.Node.Title, edge.Node.Variants.Edges[0].Node.Price)
	}
}

最佳实践

  1. 错误处理: 始终检查API调用的错误返回
  2. 限流处理: Shopify API有调用限制(通常40请求/秒),需要适当控制
  3. 分页: 对于大量数据,使用分页参数
  4. 认证: 使用OAuth进行更安全的认证
  5. 环境变量: 不要将API密钥硬编码在代码中

总结

通过上述代码示例,你可以实现Shopify的基本CRUD操作。根据你的具体需求,可以扩展这些基础功能,比如处理客户信息、库存管理、折扣代码等。Shopify API非常全面,几乎可以自动化所有商店操作。

记得查看Shopify的官方API文档以获取最新的端点和参数信息。

回到顶部