跳至主要内容

Common Specifications

Common Request Headers

All API requests must include the following headers:

ParameterTypeRequiredDescription
Content-TypestringYesapplication/json
X-BAPI-API-KEYstringYesAPI key
X-BAPI-TIMESTAMPstringYesUTC timestamp in milliseconds
X-BAPI-SIGNstringYesRequest signature (see Signature Algorithm)
X-BAPI-RECV-WINDOWstringNoRequest validity window in ms, default 5000

Common Response Format

Success Response

{
"retCode": 20000,
"retMsg": "Success",
"result": {
// Business data
}
}

Failure Response

{
"retCode": 40001,
"retMsg": "Error description",
"result": null
}

Response Fields

ParameterTypeDescription
retCodeintResponse code, 20000 indicates success
retMsgstringResponse message
resultobject/nullResponse data, null on failure

HTTP Status Codes

HTTP StatusDescriptionScenario
200SuccessBusiness success or failure (distinguished by retCode)
400Bad RequestParameter format error, missing required field
401UnauthorizedToken invalid or expired
403ForbiddenIP not in whitelist, no API permission
404Not FoundAPI path error
429Too Many RequestsRate limit triggered
500Internal Server ErrorSystem exception, please retry
503Service UnavailableSystem maintenance

Field Length Limits

Field TypeMax LengthExample Fields
Merchant ID32merchant_id
User ID64user_id, merchant_user_id
Agreement No64agreement_no, external_agreement_no
Order No64out_trade_no, out_refund_no
Trade No64trade_no, refund_no
Amount32amount.total
Currency Code16currency
URL512notify_url, return_url
Description256order_desc, refund_reason
Title128order_title
Extra Params2048extra_params (JSON string)

Idempotency

Idempotency is guaranteed through business unique indexes:

Business ScenarioIdempotency KeyUnique Index
Sign Requestexternal_agreement_no(merchant_id, external_agreement_no)
Deduction Orderout_trade_no(merchant_id, out_trade_no)
Refund Requestout_refund_no(merchant_id, out_refund_no)

Notes:

  • X-BAPI-RECV-WINDOW (unit in milliseconds, default 5000) specifies how long an HTTP request is valid and prevents replay attacks
  • Repeated requests with the same merchant order number return the result of the first request

API Timeout Recommendations

APIRecommended TimeoutDescription
Sign Request10 secondsSync return sign link
Sign Confirmation10 secondsSync return sign status
Unsign10 secondsSync return unsign result
Agreement Deduction30 secondsMay involve on-chain operations
Deduction Refund30 secondsMay involve on-chain operations
Query APIs10 secondsSync return query result

Timeout Handling:

  • After timeout, call query API to confirm actual status
  • Deduction/refund timeout does not mean failure
  • Confirm final status through query or async notification

Concurrency Handling

Same Agreement Concurrent Deductions

  • Same agreement supports concurrent deduction requests
  • Each deduction needs different out_trade_no
  • Limit verification is real-time; concurrent requests may be rejected if exceeding quota

Same Order Repeated Requests

  • Requests with same out_trade_no are treated as the same transaction
  • After first request succeeds, repeated requests return the first result (idempotent)
  • After first request fails, use a new out_trade_no to retry

Transaction Status Flow

Deduction Status

                    ┌─────────────┐
│ PROCESSING │
└──────┬──────┘

┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ SUCCESS │ │ FAILED │ │ TIMEOUT │
└─────────────┘ └─────────────┘ └─────────────┘
StatusDescriptionFollow-up Actions
PROCESSINGDeduction in progressWait for notification or query
SUCCESSDeduction successfulCan initiate refund
FAILEDDeduction failedRetry with new order number
TIMEOUTDeduction timeoutQuery to confirm, then decide

Refund Status

                    ┌─────────────┐
│ PROCESSING │
└──────┬──────┘

┌──────────┴──────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ SUCCESS │ │ FAILED │
└─────────────┘ └─────────────┘
StatusDescriptionFollow-up Actions
PROCESSINGRefund in progressWait for notification or query
SUCCESSRefund successfulFunds returned to user
FAILEDRefund failedCheck reason, retry with new refund number

Refund Notes:

  • Refund amount cannot exceed refundable amount
  • Same transaction supports multiple partial refunds
  • Used quota is restored after successful refund

Rate Limiting

Rate Limit Strategy

API TypeDimensionThresholdDescription
Sign RequestMerchant + User10/minuteSame merchant for same user
Agreement DeductionMerchant1000/secondMerchant-level QPS
Agreement DeductionAgreement10/secondSingle agreement frequency
Query APIsMerchant5000/secondAll query APIs shared
Refund APIMerchant500/secondMerchant-level refund rate

Rate Limit Response

HTTP status 429 with body:

{
"retCode": 42900,
"retMsg": "Too many requests, please try again later",
"result": {
"retry_after": 1000
}
}

Handling Recommendations

  1. Exponential Backoff: Retry with delays (1s, 2s, 4s, 8s)
  2. Request Merging: Use list query API instead of multiple single queries
  3. Async Processing: Use message queue for peak shaving in high concurrency
  4. Monitoring: Monitor 429 response ratio, adjust strategy accordingly

Agreement Type Description

Agreement type (agreement_type) defines the deduction mode of agreement payment, affecting deduction frequency, limit configuration, and agreement lifecycle.

Agreement Type Comparison

TypeDescriptionApplicable ScenariosDeduction FrequencyLimit Configuration SupportAgreement Lifecycle
CYCLEPeriodic deductionFixed periodic deduction for subscription scenariosPeriodic deduction (e.g., monthly)Single limit + Period limits (DAY/WEEK/MONTH/YEAR)Long-term validity, expires upon term end or cancellation
NON_CYCLENon-periodic deductionNon-fixed deduction cycle, merchant can initiate anytimeIrregular deduction (triggered by actual consumption)Single limit + Period limits (DAY/WEEK/MONTH/YEAR)Long-term validity, expires upon term end or cancellation
SINGLESingle authorizationOne-time valid, agreement automatically expires after deductionOne-time deduction onlySingle limit onlyShort-term validity, automatically expires after successful deduction

Typical Scenario Examples

CYCLE - Periodic Deduction

  • Membership Subscription: Video membership, music subscription, gym monthly card, cloud service annual fee
  • Bill Payment: Monthly utility bills, property fees, monthly mobile plan fees
  • Characteristics: Fixed deduction time, amounts may be same or different

NON_CYCLE - Non-Periodic Deduction

  • Transportation Services: Ride-hailing, parking fees, ETC tolls, public transit
  • Food & Beverage: Food delivery orders, restaurant membership deduction
  • Lifestyle Services: Laundry, repair, car rental
  • Characteristics: Triggered by actual consumption, irregular deduction frequency and amounts

SINGLE - Single Authorization

  • Pre-authorization Scenarios: Hotel deposits, car rental deposits
  • One-time Deduction: One-time authorized payment, temporary deduction
  • Characteristics: Agreement automatically expires after deduction, no manual cancellation needed

Limit Configuration Description

CYCLE and NON_CYCLE Types:

  • Support Single Limit (single_limit): Maximum amount per deduction
  • Support Period Limits (period_limits):
    • DAY: Daily accumulated deduction limit
    • WEEK: Weekly accumulated deduction limit
    • MONTH: Monthly accumulated deduction limit
    • YEAR: Yearly accumulated deduction limit
  • Multiple period limits can be configured simultaneously, platform validates all limits

SINGLE Type:

  • Only supports Single Limit (single_limit)
  • Period limits not supported (as agreement expires after deduction)

Agreement Lifecycle Comparison

OperationCYCLENON_CYCLESINGLE
After SignSIGNED status, can deductSIGNED status, can deductSIGNED status, can deduct
First DeductionRemains SIGNEDRemains SIGNEDAutomatically becomes UNSIGNED (agreement expires)
Multiple DeductionsSupportedSupportedNot supported (expires after first deduction)
User CancellationSupportedSupportedNot applicable (auto-expires after deduction)
Merchant CancellationSupportedSupportedNot applicable (auto-expires after deduction)
Agreement ExpirationBecomes EXPIREDBecomes EXPIREDNot applicable (auto-expires after deduction)

Usage Recommendations

  1. Choose Appropriate Type:

    • Subscription-based business: Choose CYCLE
    • On-demand consumption business: Choose NON_CYCLE
    • One-time authorization: Choose SINGLE
  2. Limit Configuration Principles:

    • Single limit should cover most transaction scenarios
    • Period limits prevent excessive short-term deductions
    • CYCLE type recommended to configure monthly limit
    • NON_CYCLE type recommended to configure daily limit
  3. Agreement Management:

    • CYCLE/NON_CYCLE agreements require active cancellation or await expiration
    • SINGLE agreements auto-expire after deduction, no management needed
    • Recommend setting reasonable validity period (sign_valid_time) for long-term agreements