Skip to content

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:

  1. The business application calls the gateway to create an order and initiate payment.
  2. 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_id
  • app_secret
  • notify_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_id
  • request_id
  • timestamp
  • nonce
  • sign

Signing algorithm:

text
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:

text
app_id=snsgo&nonce=n_001&request_id=req_20260702_001&timestamp=1782921600

Pseudocode:

text
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:

  1. A gateway administrator resets the application key during off-peak hours.
  2. The business application updates its server-side configuration.
  3. The business application calls /v1/open/ping to verify signatures with the new key.
  4. 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:

json
{
  "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:

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

On failure:

json
{
  "code": "INVALID_SIGNATURE",
  "message": "invalid signature",
  "data": null,
  "error": {
    "code": "INVALID_SIGNATURE",
    "message": "invalid signature",
    "details": {}
  }
}

Error response conventions:

  • code and error.code are kept identical.
  • Error codes use stable upper snake case. Business logic should branch on error.code, not on message.
  • error.details is 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_id and retryable.

3. Order Lifecycle ​

Order statuses:

  • pending
  • paid
  • failed
  • closed

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 ​

text
POST /v1/open/orders?app_id={app_id}&request_id={request_id}&timestamp={timestamp}&nonce={nonce}&sign={sign}

Example request:

json
{
  "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_no must be unique within the same app_id.
  • amount is expressed in the smallest currency unit.
  • Business applications do not pass expires_at; the gateway handles it uniformly.
  • return_url is optional; when omitted, the application's default return address is used.

The response returns:

  • data.created
  • data.order.gateway_order_no
  • data.order.status
  • data.order.expires_at
  • data.order.channel
  • data.order.pay_method
  • data.payment.status
  • data.payment.pay_url: the gateway checkout URL. The business application should redirect the user to this address to complete payment.

Example response:

json
{
  "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 ​

text
GET /v1/open/orders/{gateway_order_no}?app_id={app_id}&request_id={request_id}&timestamp={timestamp}&nonce={nonce}&sign={sign}

Query by merchant order number ​

text
GET /v1/open/orders/by-merchant/{merchant_order_no}?app_id={app_id}&request_id={request_id}&timestamp={timestamp}&nonce={nonce}&sign={sign}

6. Closing an Order ​

text
POST /v1/open/orders/{gateway_order_no}/close?app_id={app_id}&request_id={request_id}&timestamp={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:

text
X-Checkout-Token: checkout_token

Reading the checkout order ​

text
GET /v1/checkout/orders/{gateway_order_no}

Getting payment methods ​

text
GET /v1/checkout/orders/{gateway_order_no}/methods

Initiating payment ​

text
POST /v1/checkout/orders/{gateway_order_no}/pay

Example request:

json
{
  "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_url returned 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_url is omitted, the gateway falls back to the order or application default address.
  • paypal uses the gateway's internal return redirection logic.

8. Channel Callbacks ​

Payment channel callbacks are received centrally by the gateway:

text
POST /v1/channel/notify

Alipay 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:

text
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:

json
{
  "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:

json
{
  "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

json
{
  "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:

json
{
  "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.

json
{
  "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 ​

text
X-Pay-Gateway-Event-Id
X-Pay-Gateway-Timestamp
X-Pay-Gateway-Signature
X-Pay-Gateway-Event-Type
X-Pay-Gateway-Delivery-No

9.6 Idempotency requirements ​

Business applications must handle idempotency by event_id.

Signature verification method:

text
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 ​

text
POST /v1/open/refunds
GET  /v1/open/refunds/:refund_no
GET  /v1/open/refunds/by-merchant/:merchant_refund_no

Example creation parameters:

json
{
  "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 only CNY
  • wechat: supports only CNY
  • paypal: supports USD, 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.

  1. The business application creates an order.
  2. The business application calls checkout to initiate payment.
  3. The user completes payment.
  4. The channel calls back to the gateway.
  5. The gateway updates the order to paid.
  6. The gateway delivers the payment.succeeded webhook.
  7. 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.expired webhook

Business applications can use it for:

  • timeout closure
  • frontend status refresh
  • resource release

15. Common Errors ​

Error codeHTTPScenarioSuggested handling
INVALID_SIGNATURE401Signature is wrong or signing parameters are missingRegenerate the request according to the signing rules
TIMESTAMP_EXPIRED401Request timestamp exceeds the allowed windowRe-sign using the current time
REPLAYED_REQUEST401request_id or nonce is duplicatedGenerate new idempotent request parameters
APP_NOT_FOUND401Application does not exist or credentials are invalidCheck app_id and the secret
APP_DISABLED403Application is disabledContact the gateway administrator to enable it
IP_NOT_ALLOWED403Request source IP is not in the whitelistAdjust the application IP whitelist
INVALID_REQUEST400Request body is malformed or JSON cannot be parsedFix the request body
MISSING_REQUIRED_FIELD400A required field is missingCheck error.details.field
INVALID_AMOUNT400Amount is invalidThe amount must be a positive integer in the smallest currency unit
INVALID_CURRENCY400Currency format is invalidUse an ISO currency code, such as CNY
CURRENCY_NOT_SUPPORTED400The current channel does not support this currencyChange the payment channel or currency
ORDER_NOT_FOUND404Payment order does not existCheck gateway_order_no
ORDER_EXPIRED409Order has expiredCreate a new order
ORDER_STATUS_NOT_ALLOWED409The current order status does not allow the operationQuery the order status first, then retry
IDEMPOTENCY_CONFLICT409Parameters differ for a repeated request with the same merchant order numberKeep the parameters of the same merchant_order_no consistent
CHANNEL_UNAVAILABLE503No payment channel or mode is availableRetry later or switch channels
CHANNEL_CONFIG_INVALID500Channel configuration is missing or invalidCheck the channel account configuration in the admin console
CHANNEL_RESPONSE_ERROR502The payment channel returned a failureCheck error.details and decide based on retryable
CHANNEL_TIMEOUT504Calling the payment channel timed outRetry following the idempotency rules
RATE_LIMITED429Request rate limit exceededReduce the request rate and retry
INTERNAL_ERROR500Gateway internal errorRecord the request information and contact the gateway administrator

When the open API rate limit is hit, the gateway returns:

json
{
  "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.succeeded is received after a successful payment.
  • order.expired is 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:

  1. Create an application and configure notify_url
  2. Create a CNY order
  3. Initiate an Alipay payment in the checkout page
  4. Verify the channel callback
  5. 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:

bash
go get github.com/zmoyi/starpay-go

SDK documentation:

text
sdk/go/README.md

Released under the Apache License 2.0