Payment Gateway Integration Guide
1. Integration Overview
This payment gateway serves internal business applications. It provides unified order creation, order queries, order closure, channel payments, callback signature verification, business webhooks and expired order notifications.
The flow has two layers:
- The business application calls the gateway to create an order and initiate payment.
- After the gateway completes the channel payment, it notifies the business application through a webhook.
2. Preparation
The business application must first configure the following in the gateway admin console:
app_idapp_secretnotify_url- IP whitelist (optional)
Business-side requests must carry the following authentication parameters. The current implementation reads authentication fields from the URL query and form parameters; the JSON body is not included in the signature.
app_idrequest_idtimestampnoncesign
Signing algorithm:
1. Collect the URL query parameters.
2. If the request is form or multipart, merge the form fields.
3. Exclude sign.
4. Sort by key; sort values of the same key.
5. Join them as key=value&key=value.
6. Compute HMAC-SHA256 with app_secret.
7. Use the lower-case hex string as sign.Example string to sign:
app_id=snsgo&nonce=n_001&request_id=req_20260702_001×tamp=1782921600Pseudocode:
params = query + form
delete params["sign"]
signing_string = sort_by_key_and_value(params).join("&")
sign = hex(hmac_sha256(app_secret, signing_string))Timestamps accept Unix seconds or RFC3339, with an allowed window of 5 minutes. request_id and nonce must not repeat within the window.
Open APIs are rate limited by default per app_id + HTTP method + route. The default is 120 requests per minute per endpoint per application; when the limit is hit, the gateway returns RATE_LIMITED.
Every response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset (Unix seconds, upper bound). On a 429 the gateway additionally returns Retry-After (seconds); back off and retry according to that value.
2.1 Key rotation and compromise handling
app_secret is shown only once, when the application is created or the key is reset in the admin console. Business applications should store it in their own secret management system and must not commit it to a code repository or bundle it into frontend packages.
In V1, resetting a key immediately invalidates the old key. Recommended process:
- A gateway administrator resets the application key during off-peak hours.
- The business application updates its server-side configuration.
- The business application calls
/v1/open/pingto verify signatures with the new key. - After verification passes, normal payment requests resume.
If a key compromise is suspected, disable the application or reset the key first, then investigate the source of the leak.
2.2 Connectivity check
GET /v1/open/ping uses the same signing parameters as other open APIs and verifies the key and network connectivity:
{
"code": "ok",
"message": "ok",
"data": {
"message": "pong",
"app_id": "app_xxx",
"request_id": "req_xxx"
},
"error": null
}data.app_id echoes the application that passed authentication, and data.request_id echoes the request_id of this request, which helps with reconciliation and troubleshooting.
Unified response format:
{
"code": "ok",
"message": "ok",
"data": {},
"error": null
}On failure:
{
"code": "INVALID_SIGNATURE",
"message": "invalid signature",
"data": null,
"error": {
"code": "INVALID_SIGNATURE",
"message": "invalid signature",
"details": {}
}
}Error response conventions:
codeanderror.codeare kept identical.- Error codes use stable upper snake case. Business logic should branch on
error.code, not onmessage. error.detailsis always an object; it is{}when there is no structured information.- Payment channel errors expose only sanitized fields, such as
provider_error_code,provider_error_message,provider_request_idandretryable.
3. Order Lifecycle
Order statuses:
pendingpaidfailedclosed
For orders without expires_at, the gateway automatically generates a default expiry, currently 15 minutes. Unpaid orders that time out are closed automatically, and an order.expired webhook is delivered.
4. Creating a Payment Order
POST /v1/open/orders?app_id={app_id}&request_id={request_id}×tamp={timestamp}&nonce={nonce}&sign={sign}Example request:
{
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"subject": "Pro Membership",
"description": "snsgo Pro membership monthly",
"business_type": "membership",
"channel": "alipay",
"pay_method": "alipay",
"return_url": "https://snsgo.example.com/payment/result",
"metadata": {
"user_id": "123",
"tier": "pro"
}
}Notes:
merchant_order_nomust be unique within the sameapp_id.amountis expressed in the smallest currency unit.- Business applications do not pass
expires_at; the gateway handles it uniformly. return_urlis optional; when omitted, the application's default return address is used.
The response returns:
data.createddata.order.gateway_order_nodata.order.statusdata.order.expires_atdata.order.channeldata.order.pay_methoddata.payment.statusdata.payment.pay_url: the gateway checkout URL. The business application should redirect the user to this address to complete payment.
Example response:
{
"code": "ok",
"message": "ok",
"data": {
"created": true,
"order": {
"gateway_order_no": "pay_20260702_xxx",
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"status": "pending"
},
"payment": {
"status": "pending",
"pay_url": "https://pay.example.com/checkout/pay_20260702_xxx?token=checkout_token"
}
},
"error": null
}5. Querying Orders
Query by gateway order number
GET /v1/open/orders/{gateway_order_no}?app_id={app_id}&request_id={request_id}×tamp={timestamp}&nonce={nonce}&sign={sign}Query by merchant order number
GET /v1/open/orders/by-merchant/{merchant_order_no}?app_id={app_id}&request_id={request_id}×tamp={timestamp}&nonce={nonce}&sign={sign}6. Closing an Order
POST /v1/open/orders/{gateway_order_no}/close?app_id={app_id}&request_id={request_id}×tamp={timestamp}&nonce={nonce}&sign={sign}Only pending and failed orders can be closed.
7. Checkout Payment
Standard business integrations do not need to call the endpoints in this section directly. The business application only needs to redirect the user to the data.payment.pay_url returned when the order was created.
The following endpoints are used internally by the gateway checkout page and must carry a checkout token:
X-Checkout-Token: checkout_tokenReading the checkout order
GET /v1/checkout/orders/{gateway_order_no}Getting payment methods
GET /v1/checkout/orders/{gateway_order_no}/methodsInitiating payment
POST /v1/checkout/orders/{gateway_order_no}/payExample request:
{
"channel": "alipay",
"pay_method": "alipay",
"client_ip": "127.0.0.1",
"return_url": "https://snsgo.example.com/payment/result"
}Notes:
- These endpoints are not business-server endpoints.
- The checkout token comes from the query parameter of
payment.pay_urlreturned when the order was created. - If the order already has a locked channel, the frontend should no longer display channel selection.
- If the order has expired, payment is rejected.
- If
return_urlis omitted, the gateway falls back to the order or application default address. paypaluses the gateway's internal return redirection logic.
8. Channel Callbacks
Payment channel callbacks are received centrally by the gateway:
POST /v1/channel/notifyAlipay may omit channel, in which case it is treated as alipay by default. When a payment is initiated, the gateway writes the actual channel account into the order and appends channel and channel_account_id to the Alipay and WeChat callback addresses.
The PayPal webhook address is configured in the PayPal console. Each PayPal channel account must use a callback address that contains its own account ID:
POST /v1/channel/notify?channel=paypal&channel_account_id={channel_account_id}When a channel has only one enabled account, the old address without channel_account_id remains compatible; when multiple enabled accounts exist, callbacks missing the account ID are rejected.
The gateway will:
- verify the signature
- update the order idempotently
- generate the business webhook
9. Business Webhooks
All new events include resource idempotency fields:
{
"resource_type": "payment_order",
"resource_id": "gw_..."
}Refund events use resource_type=refund and resource_id=refund_no, so multiple refunds for the same payment order are not deduplicated against each other.
The gateway delivers events to the business application's notify_url.
9.1 Payment succeeded
Event type: payment.succeeded
Example:
{
"event_type": "payment.succeeded",
"app_id": "snsgo",
"gateway_order_no": "pay_20260702_xxx",
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"channel": "alipay",
"channel_trade_no": "202607022200...",
"paid_at": "2026-07-02T12:03:21Z",
"metadata": {
"user_id": "123",
"tier": "pro"
}
}9.2 Payment failed
Event type: payment.failed
{
"event_type": "payment.failed",
"app_id": "snsgo",
"gateway_order_no": "pay_20260702_xxx",
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"channel": "wechat",
"pay_method": "wechat",
"failure_reason": "PAYERROR",
"failed_at": "2026-07-02T12:03:21Z",
"metadata": {}
}9.3 Order expired
Event type: order.expired
Example:
{
"event_type": "order.expired",
"app_id": "snsgo",
"gateway_order_no": "pay_20260702_xxx",
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"status": "closed",
"channel": "alipay",
"pay_method": "alipay",
"expires_at": "2026-07-02T12:15:00Z",
"closed_at": "2026-07-02T12:15:30Z",
"metadata": {
"user_id": "123",
"tier": "pro"
}
}9.4 Order closed manually
When an administrator closes an order in the admin console, or the business system closes an order through the open API, the gateway delivers order.closed. close_source is admin or merchant, distinguishing the source of the closure. Automatic timeout closure still delivers order.expired.
{
"event_type": "order.closed",
"app_id": "snsgo",
"gateway_order_no": "pay_20260702_xxx",
"merchant_order_no": "snsgo_membership_123",
"amount": 9900,
"currency": "CNY",
"status": "closed",
"close_source": "merchant",
"channel": "alipay",
"pay_method": "alipay",
"closed_at": "2026-07-02T12:10:00Z",
"metadata": {}
}9.5 Refund events
A successful refund delivers refund.succeeded, and a failed refund delivers refund.failed. Key fields include refund_no, merchant_refund_no, gateway_order_no, the integer smallest-unit amount, the currency, the channel trade number and the channel refund number.
9.6 Request headers
X-Pay-Gateway-Event-Id
X-Pay-Gateway-Timestamp
X-Pay-Gateway-Signature
X-Pay-Gateway-Event-Type
X-Pay-Gateway-Delivery-No9.6 Idempotency requirements
Business applications must handle idempotency by event_id.
Signature verification method:
signature = HMAC-SHA256(app_secret, timestamp + "." + raw_body)Business applications should compute the signature using X-Pay-Gateway-Timestamp and the raw request body, then compare it against X-Pay-Gateway-Signature in constant time.
A business application only needs to return any 2xx status code after successfully processing the event. Non-2xx responses or network errors trigger retries.
10. Refund API
POST /v1/open/refunds
GET /v1/open/refunds/:refund_no
GET /v1/open/refunds/by-merchant/:merchant_refund_noExample creation parameters:
{
"gateway_order_no": "gw_...",
"merchant_refund_no": "merchant_refund_001",
"amount": 9900,
"currency": "CNY",
"reason": "duplicate purchase"
}Only paid orders can be refunded. Both pending and succeeded refunds occupy the refundable quota. If the same merchant_refund_no is submitted with identical parameters, the original refund is returned; conflicting parameters return IDEMPOTENCY_CONFLICT.
11. Proactive Order Query Compensation
After a payment is successfully initiated, the gateway creates a compensation record. When a callback is missing, a worker proactively queries Alipay, WeChat or PayPal and corrects the local paid, failed or closed status. After eight consecutive failed confirmations, the record enters manual_required, and an administrator can retry immediately from the payment compensation page.
12. Supported Channels and Currencies
Built-in validation currently applies:
alipay: supports onlyCNYwechat: supports onlyCNYpaypal: supportsUSD,EUR,HKD,JPY,GBP
If channel or pay_method is specified when the order is created, the gateway validates that the currency matches. If neither is specified, the checkout page only shows available channels that support the currency.
13. Recommended Integration Flow
- The business application creates an order.
- The business application calls checkout to initiate payment.
- The user completes payment.
- The channel calls back to the gateway.
- The gateway updates the order to
paid. - The gateway delivers the
payment.succeededwebhook. - The business application grants the entitlement after confirmation.
14. Expired Orders
After an unpaid order exceeds its validity period:
- the gateway closes the order automatically
- the gateway delivers an
order.expiredwebhook
Business applications can use it for:
- timeout closure
- frontend status refresh
- resource release
15. Common Errors
| Error code | HTTP | Scenario | Suggested handling |
|---|---|---|---|
INVALID_SIGNATURE | 401 | Signature is wrong or signing parameters are missing | Regenerate the request according to the signing rules |
TIMESTAMP_EXPIRED | 401 | Request timestamp exceeds the allowed window | Re-sign using the current time |
REPLAYED_REQUEST | 401 | request_id or nonce is duplicated | Generate new idempotent request parameters |
APP_NOT_FOUND | 401 | Application does not exist or credentials are invalid | Check app_id and the secret |
APP_DISABLED | 403 | Application is disabled | Contact the gateway administrator to enable it |
IP_NOT_ALLOWED | 403 | Request source IP is not in the whitelist | Adjust the application IP whitelist |
INVALID_REQUEST | 400 | Request body is malformed or JSON cannot be parsed | Fix the request body |
MISSING_REQUIRED_FIELD | 400 | A required field is missing | Check error.details.field |
INVALID_AMOUNT | 400 | Amount is invalid | The amount must be a positive integer in the smallest currency unit |
INVALID_CURRENCY | 400 | Currency format is invalid | Use an ISO currency code, such as CNY |
CURRENCY_NOT_SUPPORTED | 400 | The current channel does not support this currency | Change the payment channel or currency |
ORDER_NOT_FOUND | 404 | Payment order does not exist | Check gateway_order_no |
ORDER_EXPIRED | 409 | Order has expired | Create a new order |
ORDER_STATUS_NOT_ALLOWED | 409 | The current order status does not allow the operation | Query the order status first, then retry |
IDEMPOTENCY_CONFLICT | 409 | Parameters differ for a repeated request with the same merchant order number | Keep the parameters of the same merchant_order_no consistent |
CHANNEL_UNAVAILABLE | 503 | No payment channel or mode is available | Retry later or switch channels |
CHANNEL_CONFIG_INVALID | 500 | Channel configuration is missing or invalid | Check the channel account configuration in the admin console |
CHANNEL_RESPONSE_ERROR | 502 | The payment channel returned a failure | Check error.details and decide based on retryable |
CHANNEL_TIMEOUT | 504 | Calling the payment channel timed out | Retry following the idempotency rules |
RATE_LIMITED | 429 | Request rate limit exceeded | Reduce the request rate and retry |
INTERNAL_ERROR | 500 | Gateway internal error | Record the request information and contact the gateway administrator |
When the open API rate limit is hit, the gateway returns:
{
"code": "RATE_LIMITED",
"message": "rate limit exceeded",
"data": null,
"error": {
"code": "RATE_LIMITED",
"message": "rate limit exceeded",
"details": {}
}
}The response headers also carry X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset and Retry-After.
16. Integration Acceptance Checklist
- Orders can be created successfully.
- Repeatedly creating the same merchant order number returns the original order.
- Repeatedly creating the same merchant order number with a different amount fails.
- The channel payment page can be redirected to or opened.
payment.succeededis received after a successful payment.order.expiredis received after a timeout without payment.- Webhooks can be handled idempotently by event ID.
- Requests are rejected when webhook signature verification fails.
17. Testing Recommendations
It is recommended to run the minimal flow first:
- Create an application and configure
notify_url - Create a
CNYorder - Initiate an Alipay payment in the checkout page
- Verify the channel callback
- Verify the business webhook
The test payment page can be used for integration testing; use a real business return page in production.
18. Go SDK
Business services can use the Go SDK directly:
go get github.com/zmoyi/starpay-goSDK documentation:
sdk/go/README.md