8000 GitHub - imokyou/sashop: 企业级 Shoplazza Admin API v2025-06 Go SDK,**零外部依赖**,模块化设计,覆盖全部 API 端点。 · GitHub
[go: up one dir, main page]

Skip to content
imokyouPublic

About

企业级 Shoplazza Admin API v2025-06 Go SDK,**零外部依赖**,模块化设计,覆盖全部 API 端点。

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Shoplazza Admin API Go SDK

企业级 Shoplazza Admin API v2025-06 Go SDK,零外部依赖,模块化设计,覆盖全部 API 端点。

✨ 核心特性

特性 说明
📦 全量覆盖 21 个 API 模块,涵盖商品、订单、客户、库存、物流等
🔌 模块化设计 每个 API 独立子包,按需导入
🔄 Token 自动刷新 401 自动刷新 + 重试,对调用者完全透明
🔒 分布式锁 支持本地锁 / Redis 分布式锁,多实例安全
♻️ 智能重试 429/5xx 自动指数退避重试
🛡️ 类型安全 全量 Go struct,编译期检查
📝 零依赖 仅使用 Go 标准库

📥 安装

go get github.com/imokyou/sashop

要求 Go 1.21+


🚀 快速开始(3分钟上手)

第1步:获取 Access Token

在 Shoplazza 后台 → 应用 → 你的应用 → 复制 Access Token。

第2步:创建客户端

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/imokyou/sashop"
)

func main() {
    // 两个必填参数:店铺域名 + Access Token
    client, err := shoplazza.New(
        "mystore.myshoplaza.com",    // 你的店铺域名
        "shpa_xxxxxxxxxxxxx",         // 你的 Access Token
    )
    if err != nil {
        log.Fatal(err)
    }

    // 搞定!现在可以调用任何 API 了
    shop, _ := client.Shop.Get(context.Background())
    fmt.Printf("🏪 店铺: %s\n", shop.Name)
}

第3步:调用 API

ctx := context.Background()

// 列出最近20个商品
products, _ := client.Product.List(ctx, &product.ListRequest{PageSize: 20})

// 列出最近订单
orders, _ := client.Order.List(ctx, nil)

// 获取客户数量
count, _ := client.Customer.Count(ctx)

就这么简单!🎉


📦 API 模块速查表

所有模块都通过 client.模块名.方法名() 调用:

模块 属性名 常用方法 说明
商品 client.Product List / Get / Create / Update / Delete / Count / ListVariants / ListImages 商品、变体、图片、集合
订单 client.Order List / Get / Create / Cancel / Count / ListTransactions / ListRisks / ListRefunds 订单、交易、退款、风险
客户 client.Customer List / Get / Create / Update / Count / ListAddresses / CreateAddress 客户 + 收货地址
店铺 client.Shop Get / Update / ListLocations / ListMetafields / ListScriptTags 店铺信息、门店、元数据
库存 client.Inventory ListItems / GetItem / ListLevels / SetLevel / ListSuppliers / ListProcurements 库存、供应商、采购
物流 client.Fulfillment Create / Get / Complete / Cancel / List / ListCarrierServices 发货、承运商
折扣 client.Discount ListPriceRules / CreatePriceRule / ListDiscountCodes / ListFlashSales 价格规则、折扣码、秒杀
优惠券 client.Coupon List / Receive 优惠券
礼品卡 client.GiftCard List / Create / Get / Disable / BatchCreate 礼品卡
计费 client.Billing ListOneTimeCharges / CreateRecurringCharge / CreateUsageCharge 应用计费
支付 client.Payment ListPaymentOrders / GetPaymentOrder / ListDisputes / ListSettlements 支付订单、争议
Webhook client.Webhook List / Create / Get / Update / Delete / Count 事件订阅
文章 client.Article List / Create / Get / Update / Delete / Count / ListAuthors 博客文章
博客 client.Blog List / Create / Get / Update / Delete / Count 博客
自定义页面 client.CustomPage List / Create / Get / Update / Delete / Search / BatchDelete 自定义页面
主题 client.Theme List / Get / Delete / Publish / GetDocTree / CreateFile / UpdateFile 主题 + 模板文件
OAuth client.OAuth GetAccessScopes 权限范围
重定向 client.Redirect List / Create / Get / Update / Delete / Search URL 重定向
数据分析 client.Analysis GetAnalysis / GetAnalysisBySPU 流量、销售分析
文件管理 client.File List / Get / Delete / CreateUpload 文件中心
物流追踪 client.Tracking ListCarriers / DetectCarrier / GetAvailableShippingLines 物流信息

🔧 高级配置

自定义所有选项

client, err := shoplazza.New("mystore.myshoplaza.com", "your-token",
    // 自定义 HTTP Client(超时、代理等)
    shoplazza.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}),

    // 最大重试次数(默认 3)
    shoplazza.WithMaxRetries(5),

    // 重试等待范围(默认 1s ~ 30s,指数退避 + 随机抖动)
    shoplazza.WithRetryWait(500*time.Millisecond, 60*time.Second),

    // API 版本(默认 "2025-06")
    shoplazza.WithAPIVersion("2025-06"),

    // 自定义 User-Agent
    shoplazza.WithUserAgent("MyApp/1.0"),

    // 日志输出(调试用)
    shoplazza.WithLogger(log.Default()),
)

MustNew — 用于 init() 或测试

// 创建失败会 panic,仅用于你确定参数正确的场景
client := shoplazza.MustNew("mystore.myshoplaza.com", "your-token")

♻️ Token 自动刷新(无感刷新)

当 Access Token 过期(收到 401)时,SDK 自动:

  1. 🔒 加锁(防止并发刷新)
  2. 🔄 用 Refresh Token 获取新的 Access Token
  3. 💾 保存新 Token
  4. 🔄 用新 Token 重试原请求
  5. 🔓 释放锁

对调用者完全透明 — 你的代码不需要任何改动。

单实例部署(最简用法)

provider := shoplazza.NewOAuthTokenProvider(shoplazza.OAuthConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    RefreshToken: "your-refresh-token",
    TokenURL:     "https://mystore.myshoplaza.com/openapi/2025-06/oauth/token",
})

// 如果已有可用 Token,设置初始值避免首次请求触发刷新
provider.SetInitialToken("current-access-token", 2*time.Hour)

client, _ := shoplazza.New("mystore.myshoplaza.com", "",
    shoplazza.WithTokenProvider(provider),
)

多实例/集群部署(Redis 分布式锁)

// import "github.com/redis/go-redis/v9"
// rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})

provider := shoplazza.NewOAuthTokenProvider(shoplazza.OAuthConfig{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    RefreshToken: "your-refresh-token",
    TokenURL:     "https://mystore.myshoplaza.com/openapi/2025-06/oauth/token",

    // Redis 分布式锁(一个实例刷新,其他实例等待)
    Locker:     shoplazza.NewRedisLocker(rdb, "lock:token:mystore", 30*time.Second),
    // Redis Token 存储(所有实例共享最新 Token)
    TokenStore: shoplazza.NewRedisTokenStore(rdb, "token:mystore"),
})

💡 RedisClient 接口: SDK 不依赖任何 Redis 库。go-redis/v9 的 *redis.Client 天然满足接口,直接传入即可。


🛡️ 错误处理

判断错误类型

product, err := client.Product.Get(ctx, "some-id")
if err != nil {
    switch {
    case shoplazza.IsNotFound(err):
        fmt.Println("商品不存在")
    case shoplazza.IsUnauthorized(err):
        fmt.Println("Token 过期或无效")
    case shoplazza.IsRateLimited(err):
        fmt.Println("请求频率太高")
    case shoplazza.IsServerError(err):
        fmt.Println("Shoplazza 服务器错误")
    default:
        fmt.Printf("未知错误: %v\n", err)
    }
}

获取详细错误信息

import "github.com/imokyou/sashop/internal/client"

var respErr *client.ResponseError
if errors.As(err, &respErr) {
    fmt.Printf("状态码: %d\n", respErr.HTTPStatusCode)
    fmt.Printf("错误码: %s\n", respErr.Code)
    fmt.Printf("错误信息: %s\n", respErr.Message)
}

自动重试机制

SDK 会自动重试以下错误(默认3次,指数退避):

  • 429 Too Many Requests — API 频率限制
  • 500/502/503/504 — 服务器临时故障

不会重试:400、401、403、404 等客户端错误。


📄 分页遍历

Shoplazza API 使用游标分页。模式如下:

cursor := ""
for {
    resp, err := client.Product.List(ctx, &product.ListRequest{
        PageSize: 50,
        Cursor:   cursor,
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, p := range resp.Products {
        // 处理每个商品
        fmt.Println(p.Title)
    }

    // 没有下一页了
    if resp.Cursor == "" || len(resp.Products) == 0 {
        break
    }
    cursor = resp.Cursor
}

📁 项目结构

sashop/
├── shoplazza.go              # 📌 主入口,聚合所有模块
├── internal/client/           # 🔧 核心 HTTP 客户端(internal)
│   ├── client.go             #    请求/响应/重试/Token刷新
│   └── client_test.go        #    41 个单元测试
├── examples/                  # 📖 示例代码(9 个完整示例)
│   ├── 01_quickstart/
│   ├── 02_product_crud/
│   ├── 03_order_management/
│   ├── 04_error_handling/
│   ├── 05_pagination/
│   ├── 06_token_refresh/
│   ├── 07_advanced_config/
│   ├── 08_webhook/
│   └── 09_customer_address/
├── product/                   # 商品、变体、图片、集合
├── order/                     # 订单、交易、退款、风险
├── customer/                  # 客户、收货地址
├── shop/                      # 店铺、门店、元数据、脚本标签
├── inventory/                 # 库存、供应商、采购
├── fulfillment/               # 发货、承运商
├── discount/                  # 价格规则、折扣码、弹窗、秒杀
├── coupon/                    # 优惠券
├── giftcard/                  # 礼品卡
├── billing/                   # 应用计费
├── payment/                   # 支付订单、争议、结算
├── webhook/                   # Webhook 事件订阅
├── article/                   # 博客文章
├── blog/                      # 博客
├── custompage/                # 自定义页面
├── theme/                     # 主题、模板文件
├── oauth/                     # OAuth 权限
├── redirect/                  # URL 重定向
├── analysis/                  # 数据分析
├── filecenter/                # 文件管理
└── tracking/                  # 物流追踪、配送

🧪 运行测试

# 运行全部测试
go test ./... -v

# 运行特定模块测试
go test ./product/ -v
go test ./internal/client/ -v

全部 21 个模块均有单元测试,总计 130+ 测试用例。


📖 更多示例

查看 examples/ 目录获取完整的可运行示例:

示例 说明
01_quickstart 3 分钟快速上手
02_product_crud 商品增删改查全流程
03_order_management 订单管理 + 物流发货
04_error_handling 错误处理最佳实践
05_pagination 游标分页遍历
06_token_refresh Token 自动刷新(单实例 / 多实例)
07_advanced_config 高级配置选项
08_webhook Webhook 事件管理
09_customer_address 客户 + 收货地址管理

License

MIT

About

企业级 Shoplazza Admin API v2025-06 Go SDK,**零外部依赖**,模块化设计,覆盖全部 API 端点。

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0