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
}