Skip to content

Go ​

Compatibility

Go 1.21+. No third-party dependencies.

Client Implementation ​

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 is the response wrapper of every endpoint
type Envelope struct {
    Code     int             `json:"code"`                // 0 = success
    Message  string          `json:"message"`             // localized, for humans only
    ErrorKey string          `json:"error_key,omitempty"` // present on every error response
    Data     json.RawMessage `json:"data,omitempty"`
}

// APIError is returned for every response whose code != 0
type APIError struct {
    HTTPStatus int
    Code       int    // business code: 40000 / 40100 / 40400 / 40900 / 42900 / 50000 ...
    ErrorKey   string // stable machine key — branch on this, never on Message
    Message    string
    RetryAfter string // Retry-After header in seconds (set on 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 invokes an OpenAPI endpoint and returns `data` when code == 0; otherwise *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 {
        // Not our JSON envelope (e.g. a proxy error page)
        return nil, &APIError{HTTPStatus: resp.StatusCode, Code: -1,
            Message: http.StatusText(resp.StatusCode), RetryAfter: resp.Header.Get("Retry-After")}
    }
    // Most business errors arrive with HTTP 200 — check Code, not 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 verifies a webhook signature
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))
}

Usage ​

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() {
    body := map[string]any{
        "header_id":     "hdr_5",
        "package_id":    "pkg_12",
        "cardholder_id": "chd_1024",
    }
    // Keep this key: if the call fails on the network, retry with the SAME 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("check APP_ID / SECRET / server clock — retrying will not help")
        case apiErr.Code == 42900: // HTTP 429 too_many_requests
            log.Fatalf("rate limited, retry after %s s with the same Idempotency-Key", apiErr.RetryAfter)
        case apiErr.ErrorKey == "insufficient_balance":
            log.Fatal("top up your wallet first")
        default:
            log.Fatalf("apply rejected: %v", apiErr)
        }
    }
    if err != nil {
        log.Fatal(err) // network error
    }

    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)
}

Check code, not the HTTP status

Most business errors (40000, 40001, 50000) come back with HTTP 200. Call therefore treats any code != 0 as an error, whatever the HTTP status, and you branch on ErrorKey (plus Code for 40100 / 42900).

Webhook Receiver (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
    }
    tsInt, err := strconv.ParseInt(ts, 10, 64)
    if err != nil || abs(time.Now().Unix()-tsInt) > 300 {
        http.Error(w, "timestamp expired", http.StatusUnauthorized)
        return
    }
    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 Receiver (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
        }
        // ... handle ...
        c.Status(200)
    })
    return r
}

Released under MIT-equivalent terms.