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 surface | Entry point | Consumer | 1.0 target |
|---|---|---|---|
| Open API | /v1/open/* | Merchant server | Stable |
| Business webhooks | Merchant callback address (outbound) | Merchant server | Stable |
| Go SDK | github.com/zmoyi/starpay-go | Merchant server | Stable |
| Deployment configuration | Environment variables / image / Compose | Deployer | Stable (see the variables listed in Section 8) |
| Checkout API | /v1/checkout/*, /v1/public/site-config | Checkout frontend in the same repository | Internal |
| Admin API | /v1/admin/* | web-admin in the same repository | Internal |
| Channel callbacks | /v1/channel/notify | Alipay / WeChat / PayPal | Internal (adapted per channel) |
| Test receiver | /v1/test/webhook/* | Development/integration only | Not 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:
{ "code": "ok", "message": "ok", "data": {}, "error": null }On failure:
{
"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 isCodeOK = "OK", and comparisons are case-insensitive. errorisnullon success; on failure,error.codeis identical to the top-levelcode.error.detailsis 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):
| Channel | Supported currencies |
|---|---|
alipay, wechat | CNY |
paypal | USD, 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.
- Take all query parameters (
application/x-www-form-urlencoded/multipartform fields also participate), excludingsign. - Sort keys in ascending lexicographic order, sort multiple values for the same key in ascending order, and join them as
k1=v1&k2=v2to form the string to sign. sign = hex(HMAC-SHA256(app_secret, string to sign)), lowercase hexadecimal.
Constraints:
- Time window: requests whose
timestampdeviates from server time by more than 5 minutes are rejected (Unix seconds or RFC3339 are supported). - Replay:
request_idandnonceare each recorded in Redis withSETNXfor 5 minutes; duplicates returnREPLAYED_REQUEST. - IP whitelist: when
allowed_ipsis 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
| Method | Path | Success status | Description |
|---|---|---|---|
| POST | /v1/open/orders | 201 | Create an order, idempotent |
| GET | /v1/open/orders/:gateway_order_no | 200 | Query by gateway order number |
| GET | /v1/open/orders/by-merchant/:merchant_order_no | 200 | Query by merchant order number (unique within the application) |
| POST | /v1/open/orders/:gateway_order_no/close | 200 | Close an unpaid order |
| POST | /v1/open/refunds | 201 | Create a refund, idempotent |
| GET | /v1/open/refunds/:refund_no | 200 | Query by refund number |
| GET | /v1/open/refunds/by-merchant/:merchant_refund_no | 200 | Query by merchant refund number |
| GET | /v1/open/ping | 200 | Connectivity 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_nois unique. A repeated request returnscreated=falseand the original order, without creating a duplicate order. - Create refund:
app + merchant_refund_nois unique; a repeated request returnscreated=falseand the original refund. - Same key but inconsistent key fields (amount, currency, product, etc.) →
IDEMPOTENCY_CONFLICT. - The
payment.pay_urlin 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 code | Typical HTTP | Meaning |
|---|---|---|
INVALID_REQUEST | 400 | Request body/parameters are invalid |
MISSING_REQUIRED_FIELD | 400 | A required field is missing |
INVALID_AMOUNT / INVALID_CURRENCY / CURRENCY_NOT_SUPPORTED | 400 | Invalid amount or currency, or channel not supported |
INVALID_RETURN_URL / INVALID_METADATA | 400 | Invalid return URL or metadata |
INVALID_SIGNATURE | 401 | Signature is missing or does not match |
TIMESTAMP_EXPIRED | 401 | Timestamp is outside the window |
REPLAYED_REQUEST | 401 | Duplicate request_id / nonce |
APP_NOT_FOUND | 401 | Application does not exist |
APP_DISABLED / IP_NOT_ALLOWED | 403 | Application disabled or source IP not in the whitelist |
ORDER_NOT_FOUND / REFUND_NOT_FOUND | 404 | Resource does not exist or does not belong to the application |
ORDER_ALREADY_PAID / ORDER_EXPIRED / ORDER_STATUS_NOT_ALLOWED | 409 | Order status does not allow the operation |
IDEMPOTENCY_CONFLICT | 409 | Idempotency key reused with inconsistent parameters |
REFUND_AMOUNT_EXCEEDS_PAID / REFUND_STATUS_NOT_ALLOWED | 400/409 | Refund amount or status is invalid |
CHANNEL_UNAVAILABLE / CHANNEL_TIMEOUT | 503 | Channel unavailable or timed out |
CHANNEL_CONFIG_INVALID / CHANNEL_RESPONSE_ERROR | 400/502 | Channel configuration or response is abnormal |
RATE_LIMITED | 429 | Open API rate limit triggered |
INTERNAL_ERROR / SERVICE_UNAVAILABLE | 500/503 | Gateway internal error |
4. Business Webhooks (Stable, outbound)
Request headers:
| Header | Description |
|---|---|
X-Pay-Gateway-Event-Id | Unique event ID, the deduplication key |
X-Pay-Gateway-Event-Type | Event type |
X-Pay-Gateway-Delivery-No | Delivery number, unchanged across retries |
X-Pay-Gateway-Timestamp | Unix seconds |
X-Pay-Gateway-Signature | hex(HMAC-SHA256(app_secret, timestamp + "." + body)) |
Verification requirements:
- A 5-minute time window is recommended (the SDK default is
DefaultWebhookTolerance). - Handle idempotently by
event_idordelivery_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
failedand can be retried manually in the admin console.
Event types:
| Event | Trigger |
|---|---|
payment.succeeded | Payment succeeded |
payment.failed | Payment failed |
order.expired | Order closed due to timeout |
order.closed | Closed manually (includes close_source) |
refund.succeeded | Refund succeeded |
refund.failed | Refund 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.
| Method | Path | Description |
|---|---|---|
| GET | /v1/checkout/orders/:gateway_order_no | Checkout order details {title, order} |
| GET | /v1/checkout/orders/:gateway_order_no/methods | Available payment methods {locked, selected_method, methods[]} |
| POST | /v1/checkout/orders/:gateway_order_no/pay | Initiate payment {payment:{status, channel, pay_method, pay_url, qr_code, form_html}} |
| GET | /v1/checkout/paypal/return | PayPal return capture, then 302 to the result page |
| GET | /v1/public/site-config | Public 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 viaPOST /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 returnssetup_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 theweb-adminin the same repository and are not externally committed.
7. Go SDK (Stable)
Module: github.com/zmoyi/starpay-go (sdk/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, toolchaingo1.26.11). - The SDK is released as a separate repository,
github.com/zmoyi/starpay-go, usingvX.Y.Ztags; main repository tags and SDK tags are independent of each other. sdk/goin 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.
| Variable | Default | Description |
|---|---|---|
APP_NAME | payment-gateway | Application name |
APP_ENV | local | Enables key validation when set to production |
HTTP_ADDR | :8080 | Listen address |
DB_DRIVER | postgres | postgres / mysql (MySQL migration compatibility is not yet verified) |
DATABASE_URL | empty | Takes precedence over the split DB_* settings |
DB_HOST / DB_PORT / DB_NAME / DB_USER / DB_PASSWORD / DB_SSLMODE | localhost / 5432 / payment_gateway / payment / payment / disable | Split connection settings |
REDIS_ADDR | localhost:6379 | Redis address |
REDIS_PASSWORD | empty | Redis password |
JWT_SECRET | development default | Default is rejected in production |
ACCESS_TOKEN_TTL | 12h | Admin access token |
REFRESH_TOKEN_TTL | 168h | Refresh token |
REFRESH_COOKIE_NAME | pg_refresh_token | Refresh Cookie name |
REFRESH_COOKIE_SECURE | false | Should be true in production |
REFRESH_COOKIE_SAME_SITE | lax | Cookie SameSite |
APP_SECRET_ENCRYPTION_KEY | development default | 16/24/32 bytes, must be changed in production |
ORDER_DEFAULT_TTL | 15m | Default order validity period (once first written to gateway configuration, the configuration takes precedence) |
ORDER_EXPIRE_SCAN_INTERVAL | 30s | Expiry scan interval |
ORDER_EXPIRE_SCAN_LIMIT | 100 | Maximum records per scan |
ORDER_EXPIRE_WORKER_CONCURRENCY | 2 | Number of expiry queue consumers (takes effect after restart) |
OPEN_API_RATE_LIMIT_ENABLED | true | Open API rate limiting switch (first written to gateway configuration) |
OPEN_API_RATE_LIMIT | 120 | Quota per window |
OPEN_API_RATE_LIMIT_WINDOW | 1m | Rate 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:
- Test receiver:
/v1/test/webhook/*is registered only in non-productionenvironments (testRoutesEnabled), with unit test coverage. - Raw checkout data:
PaymentResult.Rawis nowjson:"-"; internal reconciliation snapshots are retained, and browsers no longer receive raw channel responses. - 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.
- Rate limit response headers: added
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-ResetandRetry-Afterfor 429 responses. - Webhook retry table: aligned with
maxDeliveryAttempts = 3, keeping only the two delays of 10s and 30s. - SDK Go version:
sdk/go/go.modupgraded togo 1.26.0+toolchain go1.26.11, consistent with the main repository. /v1/open/pingfields:message,app_idandrequest_idare 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/gomust be synchronized when tagging the main repository (currently a manual process; automation requires configuring credentials for that repository). - OpenAPI description file (optional): generating
openapi.yamland 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(usinghttptestor shared JSON samples) to ensure that SDK serialized fields match the backendserializeOrder/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.yamland 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.