Skip to content

Go ​

兼容性

Go 1.21+。无第三方依赖。

客户端实现 ​

go
package brand

import (
    "bytes"
    "crypto/hmac"
    "crypto/rand"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

const (
    AppID  = "cp_a1b2c3d4..."
    Secret = "f1e2d3c4..."
    Base   = "https://api.coinepay.net"
)

var httpClient = &http.Client{Timeout: 30 * time.Second}

// Envelope 所有接口的统一响应包络
type Envelope struct {
    Code     int             `json:"code"`                // 0 = 成功
    Message  string          `json:"message"`             // 本地化文案,仅供人阅读
    ErrorKey string          `json:"error_key,omitempty"` // 所有错误响应都带
    Data     json.RawMessage `json:"data,omitempty"`
}

// APIError code != 0 的响应一律返回该错误
type APIError struct {
    HTTPStatus int
    Code       int    // 业务码:40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
    ErrorKey   string // 稳定的机器标识——据此分支,不要用 Message
    Message    string
    RetryAfter string // Retry-After 响应头(秒),429 时设置
}

func (e *APIError) Error() string {
    return fmt.Sprintf("HTTP %d code=%d error_key=%s: %s", e.HTTPStatus, e.Code, e.ErrorKey, e.Message)
}

// Call 通用 OpenAPI 调用:code == 0 时返回 data,否则返回 *APIError
func Call(method, path string, body any, idempotencyKey string) (json.RawMessage, error) {
    var bodyBytes []byte
    if body != nil {
        var err error
        bodyBytes, err = json.Marshal(body)
        if err != nil {
            return nil, err
        }
    } else {
        bodyBytes = []byte("{}")
    }

    nonceBytes := make([]byte, 16)
    if _, err := rand.Read(nonceBytes); err != nil {
        return nil, err
    }
    nonce := hex.EncodeToString(nonceBytes)
    ts := fmt.Sprintf("%d", time.Now().Unix())
    sum := sha256.Sum256(bodyBytes)
    bodyHash := hex.EncodeToString(sum[:])

    signInput := fmt.Sprintf("%s\n%s\n\n%s\n%s\n%s", method, path, ts, nonce, bodyHash)
    mac := hmac.New(sha256.New, []byte(Secret))
    mac.Write([]byte(signInput))
    sig := hex.EncodeToString(mac.Sum(nil))

    req, err := http.NewRequest(method, Base+path, bytes.NewReader(bodyBytes))
    if err != nil {
        return nil, err
    }
    req.Header.Set("X-App-Id", AppID)
    req.Header.Set("X-Timestamp", ts)
    req.Header.Set("X-Nonce", nonce)
    req.Header.Set("X-Signature", sig)
    req.Header.Set("Content-Type", "application/json")
    if idempotencyKey != "" {
        req.Header.Set("Idempotency-Key", idempotencyKey)
    }

    resp, err := httpClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    raw, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    var env Envelope
    if err := json.Unmarshal(raw, &env); err != nil {
        // 不是我们的 JSON 包络(如代理层错误页)
        return nil, &APIError{HTTPStatus: resp.StatusCode, Code: -1,
            Message: http.StatusText(resp.StatusCode), RetryAfter: resp.Header.Get("Retry-After")}
    }
    // 大部分业务错误的 HTTP 状态码是 200——判断 Code,不要看 resp.StatusCode
    if env.Code != 0 {
        return nil, &APIError{HTTPStatus: resp.StatusCode, Code: env.Code, ErrorKey: env.ErrorKey,
            Message: env.Message, RetryAfter: resp.Header.Get("Retry-After")}
    }
    return env.Data, nil
}

// VerifyWebhook Webhook 验签
func VerifyWebhook(sigHeader, tsHeader string, rawBody []byte, webhookSecret string) bool {
    const prefix = "v1,"
    if len(sigHeader) <= len(prefix) || sigHeader[:len(prefix)] != prefix {
        return false
    }
    sig := sigHeader[len(prefix):]
    mac := hmac.New(sha256.New, []byte(webhookSecret))
    mac.Write([]byte(tsHeader))
    mac.Write([]byte("."))
    mac.Write(rawBody)
    expected := hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(sig), []byte(expected))
}

使用示例 ​

go
package main

import (
    "encoding/json"
    "errors"
    "fmt"
    "log"

    "github.com/google/uuid"

    "yourapp/brand"
)

type ApplyData struct {
    CardID     string `json:"card_id"`
    Status     int    `json:"status"`
    StatusDesc string `json:"status_desc"`
}

func main() {
    // 1. 申请虚拟卡(带幂等键)
    body := map[string]any{
        "header_id":     "hdr_5",
        "package_id":    "pkg_12",
        "cardholder_id": "chd_1024",
    }
    // 保留这个 key:网络失败重试时必须用同一个 key
    idempotencyKey := uuid.New().String()
    data, err := brand.Call("POST", "/api/v1/openapi/card/apply", body, idempotencyKey)

    var apiErr *brand.APIError
    if errors.As(err, &apiErr) {
        switch {
        case apiErr.Code == 40100: // HTTP 401 openapi_invalid_credentials
            log.Fatal("检查 APP_ID / SECRET / 服务器时钟——重试无效")
        case apiErr.Code == 42900: // HTTP 429 too_many_requests
            log.Fatalf("触发限流,%s 秒后用同一个 Idempotency-Key 重试", apiErr.RetryAfter)
        case apiErr.ErrorKey == "insufficient_balance":
            log.Fatal("请先给钱包充值")
        default:
            log.Fatalf("开卡被拒绝: %v", apiErr)
        }
    }
    if err != nil {
        log.Fatal(err) // 网络错误
    }

    var card ApplyData
    if err := json.Unmarshal(data, &card); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Created card: %s, status=%d (%s)\n", card.CardID, card.Status, card.StatusDesc)
}

判断 code,不要看 HTTP 状态码

大部分业务错误(40000、40001、50000)的 HTTP 状态码是 200。因此 Call 不论 HTTP 状态码如何,只要 code != 0 就视为错误,再按 ErrorKey(40100 / 42900 看 Code)分支处理。

Webhook 接收(net/http) ​

go
package main

import (
    "encoding/json"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"

    "yourapp/brand"
)

var webhookSecret = os.Getenv("BRAND_WEBHOOK_SECRET")

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    raw, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "read error", http.StatusBadRequest)
        return
    }

    sig := r.Header.Get("Webhook-Signature")
    ts  := r.Header.Get("Webhook-Timestamp")
    eventID := r.Header.Get("Webhook-Id")
    eventType := r.Header.Get("Webhook-Type")

    if !brand.VerifyWebhook(sig, ts, raw, webhookSecret) {
        http.Error(w, "invalid signature", http.StatusUnauthorized)
        return
    }

    // 时间戳 ±5 分钟
    tsInt, err := strconv.ParseInt(ts, 10, 64)
    if err != nil || abs(time.Now().Unix()-tsInt) > 300 {
        http.Error(w, "timestamp expired", http.StatusUnauthorized)
        return
    }

    // 基于 event_id 去重
    if alreadyProcessed(eventID) {
        w.WriteHeader(http.StatusOK)
        return
    }

    var payload map[string]any
    if err := json.Unmarshal(raw, &payload); err != nil {
        http.Error(w, "invalid json", http.StatusBadRequest)
        return
    }

    if err := enqueue(eventType, payload); err != nil {
        http.Error(w, "internal error", http.StatusInternalServerError)
        return
    }
    markProcessed(eventID)

    w.WriteHeader(http.StatusOK)
}

func abs(n int64) int64 {
    if n < 0 {
        return -n
    }
    return n
}

func main() {
    http.HandleFunc("/webhook", webhookHandler)
    http.ListenAndServe(":3000", nil)
}

Webhook 接收(Gin) ​

go
import (
    "github.com/gin-gonic/gin"
    "io"
)

func setupRouter() *gin.Engine {
    r := gin.Default()
    r.POST("/webhook", func(c *gin.Context) {
        raw, err := io.ReadAll(c.Request.Body)
        if err != nil {
            c.AbortWithStatus(400)
            return
        }
        sig := c.GetHeader("Webhook-Signature")
        ts  := c.GetHeader("Webhook-Timestamp")
        if !brand.VerifyWebhook(sig, ts, raw, webhookSecret) {
            c.AbortWithStatus(401)
            return
        }
        // ...处理
        c.Status(200)
    })
    return r
}

采用 MIT 等价条款发布