Skip to content

Public API and SDK Contract (v1.0 Freeze Checklist) ​

This document describes the contract surface committed to external consumers, the current implementation details, and the differences that must be closed before moving to v1.0.0. For usage and examples, see the integration guide. This document only covers "what is a contract and whether it is stable".

1. Contract Surface and Stability Levels ​

Contract surfaceEntry pointConsumer1.0 target
Open API/v1/open/*Merchant serverStable
Business webhooksMerchant callback address (outbound)Merchant serverStable
Go SDKgithub.com/zmoyi/starpay-goMerchant serverStable
Deployment configurationEnvironment variables / image / ComposeDeployerStable (see the variables listed in Section 8)
Checkout API/v1/checkout/*, /v1/public/site-configCheckout frontend in the same repositoryInternal
Admin API/v1/admin/*web-admin in the same repositoryInternal
Channel callbacks/v1/channel/notifyAlipay / WeChat / PayPalInternal (adapted per channel)
Test receiver/v1/test/webhook/*Development/integration onlyNot a contract (not registered when APP_ENV=production)

Conventions:

  • Stable means semantic versioning applies from 1.0; breaking changes must go through a major version bump and provide a deprecation period.
  • Internal means interfaces used by the frontend in the same repository. They may change in lockstep with the frontend, but documentation and the frontend must still be updated together when they change.
  • Order numbers, error message wording, specific keys in details, and log formats are not part of the stable contract.

2. General Conventions ​

2.1 Response envelope ​

All JSON APIs return:

json
{ "code": "ok", "message": "ok", "data": {}, "error": null }

On failure:

json
{
  "code": "ORDER_NOT_FOUND",
  "message": "payment order not found",
  "data": null,
  "error": {
    "code": "ORDER_NOT_FOUND",
    "message": "payment order not found",
    "details": { "gateway_order_no": "pay_20260101_xxx" }
  }
}
  • The success code on the wire is "ok" (lowercase); the SDK constant is CodeOK = "OK", and comparisons are case-insensitive.
  • error is null on success; on failure, error.code is identical to the top-level code.
  • error.details is always an object and may be an empty object.

2.2 Amounts, currencies and time ​

  • Amount: an integer in the smallest currency unit (fen for CNY, cents for USD, yen for JPY).
  • Currency: uppercase ISO 4217 code. Channel constraints (internal/domain/payments/service):
ChannelSupported currencies
alipay, wechatCNY
paypalUSD, EUR, HKD, JPY, GBP
  • Time: an RFC3339 string in JSON (maps directly to *time.Time).
  • Order numbers: the gateway generates pay_YYYYMMDD_<base32> / rf_YYYYMMDD_<base32>. The format is not guaranteed; callers must treat them as opaque strings and pass them through.

2.3 Pagination (admin only) ​

Query parameters page (default 1) and page_size (default 20); the response data is { "items": [], "total": 0, "page": 1, "page_size": 20 }.

3. Open API (Stable) ​

3.1 Authentication signature ​

All requests must carry app_id, request_id, nonce, timestamp and sign in the query string.

  1. Take all query parameters (application/x-www-form-urlencoded / multipart form fields also participate), excluding sign.
  2. Sort keys in ascending lexicographic order, sort multiple values for the same key in ascending order, and join them as k1=v1&k2=v2 to form the string to sign.
  3. sign = hex(HMAC-SHA256(app_secret, string to sign)), lowercase hexadecimal.

Constraints:

  • Time window: requests whose timestamp deviates from server time by more than 5 minutes are rejected (Unix seconds or RFC3339 are supported).
  • Replay: request_id and nonce are each recorded in Redis with SETNX for 5 minutes; duplicates return REPLAYED_REQUEST.
  • IP whitelist: when allowed_ips is configured for the application, validation is performed by CIDR/IP.
  • Disabled application → 403 APP_DISABLED; key must be reset → 401 INVALID_SIGNATURE.

3.2 Routes ​

MethodPathSuccess statusDescription
POST/v1/open/orders201Create an order, idempotent
GET/v1/open/orders/:gateway_order_no200Query by gateway order number
GET/v1/open/orders/by-merchant/:merchant_order_no200Query by merchant order number (unique within the application)
POST/v1/open/orders/:gateway_order_no/close200Close an unpaid order
POST/v1/open/refunds201Create a refund, idempotent
GET/v1/open/refunds/:refund_no200Query by refund number
GET/v1/open/refunds/by-merchant/:merchant_refund_no200Query by merchant refund number
GET/v1/open/ping200Connectivity check, returns message, app_id, request_id

3.2.1 Rate limit response headers ​

Every open API response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset (Unix seconds, upper bound). On a 429, Retry-After (seconds) is additionally returned. Because the counting window slides forward with each request, Reset is an upper bound rather than an exact value.

3.3 Data model ​

Order fields (kept in sync in sdk/go/types.go): gateway_order_no, merchant_order_no, business_type, subject, description, amount, currency, settlement_amount, settlement_currency, channel, pay_method, provider_order_no, channel_trade_no, return_url, status, expires_at, paid_at, failed_at, failure_reason, closed_at, metadata, created_at, updated_at.

Order status: pending → paid / failed / closed (final states do not change).

Refund fields: refund_no, gateway_order_no, merchant_order_no, merchant_refund_no, channel, channel_trade_no, channel_refund_no, amount, currency, reason, status, failure_reason, metadata, succeeded_at, failed_at, created_at, updated_at.

Refund status: pending → succeeded / failed.

3.4 Idempotency ​

  • Create order: app + merchant_order_no is unique. A repeated request returns created=false and the original order, without creating a duplicate order.
  • Create refund: app + merchant_refund_no is unique; a repeated request returns created=false and the original refund.
  • Same key but inconsistent key fields (amount, currency, product, etc.) → IDEMPOTENCY_CONFLICT.
  • The payment.pay_url in the create order response carries a checkout token and can be used for redirection directly.

3.5 Error codes (public commitment) ​

Defined in internal/platform/httpx/errors.go and mirrored in the SDK in sdk/go/errors.go:

Error codeTypical HTTPMeaning
INVALID_REQUEST400Request body/parameters are invalid
MISSING_REQUIRED_FIELD400A required field is missing
INVALID_AMOUNT / INVALID_CURRENCY / CURRENCY_NOT_SUPPORTED400Invalid amount or currency, or channel not supported
INVALID_RETURN_URL / INVALID_METADATA400Invalid return URL or metadata
INVALID_SIGNATURE401Signature is missing or does not match
TIMESTAMP_EXPIRED401Timestamp is outside the window
REPLAYED_REQUEST401Duplicate request_id / nonce
APP_NOT_FOUND401Application does not exist
APP_DISABLED / IP_NOT_ALLOWED403Application disabled or source IP not in the whitelist
ORDER_NOT_FOUND / REFUND_NOT_FOUND404Resource does not exist or does not belong to the application
ORDER_ALREADY_PAID / ORDER_EXPIRED / ORDER_STATUS_NOT_ALLOWED409Order status does not allow the operation
IDEMPOTENCY_CONFLICT409Idempotency key reused with inconsistent parameters
REFUND_AMOUNT_EXCEEDS_PAID / REFUND_STATUS_NOT_ALLOWED400/409Refund amount or status is invalid
CHANNEL_UNAVAILABLE / CHANNEL_TIMEOUT503Channel unavailable or timed out
CHANNEL_CONFIG_INVALID / CHANNEL_RESPONSE_ERROR400/502Channel configuration or response is abnormal
RATE_LIMITED429Open API rate limit triggered
INTERNAL_ERROR / SERVICE_UNAVAILABLE500/503Gateway internal error

4. Business Webhooks (Stable, outbound) ​

Request headers:

HeaderDescription
X-Pay-Gateway-Event-IdUnique event ID, the deduplication key
X-Pay-Gateway-Event-TypeEvent type
X-Pay-Gateway-Delivery-NoDelivery number, unchanged across retries
X-Pay-Gateway-TimestampUnix seconds
X-Pay-Gateway-Signaturehex(HMAC-SHA256(app_secret, timestamp + "." + body))

Verification requirements:

  • A 5-minute time window is recommended (the SDK default is DefaultWebhookTolerance).
  • Handle idempotently by event_id or delivery_no, and return 2xx on success.
  • Non-2xx responses or network errors trigger retries, with at most 3 delivery attempts at intervals of 10s and 30s. After that, the delivery is marked failed and can be retried manually in the admin console.

Event types:

EventTrigger
payment.succeededPayment succeeded
payment.failedPayment failed
order.expiredOrder closed due to timeout
order.closedClosed manually (includes close_source)
refund.succeededRefund succeeded
refund.failedRefund failed

5. Checkout API (Internal) ​

Authentication: the X-Checkout-Token request header or the ?token= query parameter. The token is generated when an order is created or previewed in the admin console.

MethodPathDescription
GET/v1/checkout/orders/:gateway_order_noCheckout order details {title, order}
GET/v1/checkout/orders/:gateway_order_no/methodsAvailable payment methods {locked, selected_method, methods[]}
POST/v1/checkout/orders/:gateway_order_no/payInitiate payment {payment:{status, channel, pay_method, pay_url, qr_code, form_html}}
GET/v1/checkout/paypal/returnPayPal return capture, then 302 to the result page
GET/v1/public/site-configPublic site configuration (no authentication)

methods[] elements: pay_method, channel, channel_account_id, label, enabled, pay_mode; when a routing rule matches, rule_id and target_id are also included.

The raw channel response (PaymentResult.Raw) is only used for internal reconciliation snapshots and is not serialized externally.

6. Admin API (Internal) ​

  • Authentication: Authorization: Bearer <access_token>; the token is obtained via POST /v1/admin/auth/login, and refresh uses an HttpOnly Cookie (REFRESH_COOKIE_NAME).
  • First-time initialization: POST /v1/admin/setup; calling it again after success returns setup_completed.
  • Resources: apps, channels, routing-rules, config/gateway, orders, refunds, payment-reconciliations, webhook-deliveries, users, roles, monitoring/overview.
  • Error codes are defined centrally in internal/platform/httpx/admin_codes.go and follow the existing lowercase naming (invalid_request, order_not_found, etc.). They only serve the web-admin in the same repository and are not externally committed.

7. Go SDK (Stable) ​

Module: github.com/zmoyi/starpay-go (sdk/go).

go
client, err := paygateway.NewClient(paygateway.Config{
    BaseURL:   "https://pay.example.com",
    AppID:     "app_xxx",
    AppSecret: "secret",
    Timeout:   10 * time.Second,
})

Exported stable API:

  • Client: NewClient, Config, Client
  • Orders: CreateOrder, GetOrder, GetOrderByMerchant, CloseOrder
  • Refunds: CreateRefund, GetRefund, GetRefundByMerchant
  • Types: Response[T], APIError, Order, Refund, CreateOrderRequest/Result, CreateRefundRequest/Result
  • Signing: Sign, CanonicalSignString
  • Webhooks: ParseWebhookRequest, ParseWebhookRequestWithOptions, VerifyWebhookSignature, VerifyWebhookSignatureWithOptions, ParseWebhookEvent, WebhookEvent, WebhookVerificationOptions, DefaultWebhookTolerance
  • Error code constants: Code*

SDK behavior commitments: returns *APIError when the response is non-2xx, error != nil, or code is not ok; returns INVALID_RESPONSE and preserves ResponseBody (truncated to 4KB) when the response cannot be parsed as an envelope.

Version and release:

  • The minimum Go version matches the main repository (go 1.26.0, toolchain go1.26.11).
  • The SDK is released as a separate repository, github.com/zmoyi/starpay-go, using vX.Y.Z tags; main repository tags and SDK tags are independent of each other.
  • sdk/go in the main repository is the single source of truth for the SDK source, and must be synchronized to that repository when releasing.

8. Configuration Contract (Stable) ​

Required (must be explicitly set in production): JWT_SECRET, APP_SECRET_ENCRYPTION_KEY, the database connection (DATABASE_URL or DB_*), REDIS_ADDR.

VariableDefaultDescription
APP_NAMEpayment-gatewayApplication name
APP_ENVlocalEnables key validation when set to production
HTTP_ADDR:8080Listen address
DB_DRIVERpostgrespostgres / mysql (MySQL migration compatibility is not yet verified)
DATABASE_URLemptyTakes precedence over the split DB_* settings
DB_HOST / DB_PORT / DB_NAME / DB_USER / DB_PASSWORD / DB_SSLMODElocalhost / 5432 / payment_gateway / payment / payment / disableSplit connection settings
REDIS_ADDRlocalhost:6379Redis address
REDIS_PASSWORDemptyRedis password
JWT_SECRETdevelopment defaultDefault is rejected in production
ACCESS_TOKEN_TTL12hAdmin access token
REFRESH_TOKEN_TTL168hRefresh token
REFRESH_COOKIE_NAMEpg_refresh_tokenRefresh Cookie name
REFRESH_COOKIE_SECUREfalseShould be true in production
REFRESH_COOKIE_SAME_SITElaxCookie SameSite
APP_SECRET_ENCRYPTION_KEYdevelopment default16/24/32 bytes, must be changed in production
ORDER_DEFAULT_TTL15mDefault order validity period (once first written to gateway configuration, the configuration takes precedence)
ORDER_EXPIRE_SCAN_INTERVAL30sExpiry scan interval
ORDER_EXPIRE_SCAN_LIMIT100Maximum records per scan
ORDER_EXPIRE_WORKER_CONCURRENCY2Number of expiry queue consumers (takes effect after restart)
OPEN_API_RATE_LIMIT_ENABLEDtrueOpen API rate limiting switch (first written to gateway configuration)
OPEN_API_RATE_LIMIT120Quota per window
OPEN_API_RATE_LIMIT_WINDOW1mRate limit window

Production validation (APP_ENV=production): rejects the development default JWT_SECRET, the development default APP_SECRET_ENCRYPTION_KEY, and any value containing CHANGE_ME.

Deployment contract: the container listens on 8080, the health check is GET /healthz, and frontend static assets are embedded in the binary.

9. v1.0 Closure Status ​

Items closed in this round:

  1. Test receiver: /v1/test/webhook/* is registered only in non-production environments (testRoutesEnabled), with unit test coverage.
  2. Raw checkout data: PaymentResult.Raw is now json:"-"; internal reconciliation snapshots are retained, and browsers no longer receive raw channel responses.
  3. Admin error codes: centralized in internal/platform/httpx/admin_codes.go, with 95 call sites switched to constants; the documentation now states that only open API/webhook error codes are externally stable.
  4. Rate limit response headers: added X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and Retry-After for 429 responses.
  5. Webhook retry table: aligned with maxDeliveryAttempts = 3, keeping only the two delays of 10s and 30s.
  6. SDK Go version: sdk/go/go.mod upgraded to go 1.26.0 + toolchain go1.26.11, consistent with the main repository.
  7. /v1/open/ping fields: message, app_id and request_id are now documented in the integration guide and this document.

Still requiring manual follow-up:

  • SDK release synchronization: the SDK is released as the separate repository github.com/zmoyi/starpay-go; sdk/go must be synchronized when tagging the main repository (currently a manual process; automation requires configuring credentials for that repository).
  • OpenAPI description file (optional): generating openapi.yaml and validating it in CI would further formalize the contract.

10. Contract Testing and Change Process Recommendations ​

  • Contract tests: add "routes and models cross-check" tests in sdk/go (using httptest or shared JSON samples) to ensure that SDK serialized fields match the backend serializeOrder / serializeRefund; also cross-check error code constants to prevent drift between the two sides.
  • OpenAPI description file: if a stable 1.0 commitment is desired, generate openapi.yaml and validate in CI that routes and documentation match.
  • Deprecation process: for breaking changes, first add a deprecation warning in a minor release, keep it for at least one minor cycle, then remove it in the next major version.
  • Release: complete the "Still requiring manual follow-up" items in Section 9 before v1.0.0.

Released under the Apache License 2.0