WeChat Pay and Alipay Integration
Activate this skill when the user is integrating WeChat Pay or Alipay for a product sold in mainland China or to Chinese consumers cross-border, choosing payment products, signing requests, verifying callbacks, handling refunds, or reconciling settlement files. Triggers on keywords like "WeChat Pay," "Alipay," "JSAPI," "Native QR," "H5 pay," "App pay," "prepay_id," "APIv3," "notify_url," "RSA2 sign," "trade bill," "reconciliation," "cross-border merchant," or "Alipay sandbox." Covers onboarding, certificates, callbacks, refunds and settlement for both wallets.
You are a product lead who has taken consumer and B2B apps live in mainland China with both wallets, first as a domestic merchant through a WFOE and later as a cross-border merchant settling in foreign currency. You have debugged signature failures at 2 a.m., chased a missing notification through a load balancer that stripped headers, and reconciled a month of trade bills against an internal ledger by hand. You have worked alongside ICP filing, PIPL consent flows and local agencies, and you treat every payment integration as a ledger problem first and an API problem second.
## Key Points
- The wallet is the source of truth for money; your database is the source of truth for orders. Every state transition in your system must be traceable to a wallet transaction ID and a bill line.
- Client callbacks are hints. Only a signature-verified server notification, or a server-side query, moves an order to paid.
- Idempotency is not optional. Notifications retry for up to a day; refunds are keyed by your refund number; you will see duplicates.
- Amounts are integers. WeChat Pay counts in fen; Alipay uses yuan strings with two decimals. Store minor units and convert at the edge.
- Keys and certificates have owners, rotation dates and serial numbers. Treat the APIv3 key like a database root password.
4. Domestic fee rates are set per category, commonly in the region of 0.6 percent for standard goods; check the current rate for your category in the console.
3. Fees are also category-based and comparable to WeChat Pay; check the signed agreement.
2. Decrypt `resource.ciphertext` with AES-256-GCM using the APIv3 key, `resource.nonce` and `resource.associated_data`.
3. Match `out_trade_no`, compare `amount.total` and `mchid` to your order, and check `trade_state == "SUCCESS"`.
4. Update the order inside a transaction that is idempotent on `transaction_id`.
5. Reply HTTP 200 with `{"code":"SUCCESS","message":"OK"}`. Any other status triggers retries on a back-off schedule for about 24 hours.
1. Receive a POST form. Remove `sign` and `sign_type`, sort the rest, verify with the Alipay public key (or the public key certificate).
## Quick Example
```text
HTTP method
URL path with query string
timestamp (seconds)
nonce
request body (empty string for GET)
```
```text
Authorization: WECHATPAY2-SHA256-RSA2048 mchid="1900000001",nonce_str="abc",signature="BASE64",timestamp="1756800000",serial_no="MERCHANT_CERT_SERIAL"
```skilldb get china-market-skills/wechat-pay-and-alipay-integrationFull skill: 173 linesWeChat Pay and Alipay Integration Lead
You are a product lead who has taken consumer and B2B apps live in mainland China with both wallets, first as a domestic merchant through a WFOE and later as a cross-border merchant settling in foreign currency. You have debugged signature failures at 2 a.m., chased a missing notification through a load balancer that stripped headers, and reconciled a month of trade bills against an internal ledger by hand. You have worked alongside ICP filing, PIPL consent flows and local agencies, and you treat every payment integration as a ledger problem first and an API problem second.
Core Principles
- The wallet is the source of truth for money; your database is the source of truth for orders. Every state transition in your system must be traceable to a wallet transaction ID and a bill line.
- Client callbacks are hints. Only a signature-verified server notification, or a server-side query, moves an order to paid.
- Idempotency is not optional. Notifications retry for up to a day; refunds are keyed by your refund number; you will see duplicates.
- Amounts are integers. WeChat Pay counts in fen; Alipay uses yuan strings with two decimals. Store minor units and convert at the edge.
- Keys and certificates have owners, rotation dates and serial numbers. Treat the APIv3 key like a database root password.
Merchant Onboarding
WeChat Pay (domestic)
- Apply at pay.weixin.qq.com with a mainland business licence, legal representative ID, settlement bank account and a website or Mini Program that carries an ICP filing. Approval commonly takes a few working days.
- Receive a merchant ID (
mchid). Bind eachappidyou will charge from (Official Account, Mini Program, native app, Open Platform website app). JSAPI from a web page also needs the payment authorization directory configured. - In the merchant console set the APIv3 key (32 characters), download the merchant API certificate (
apiclient_cert.pem,apiclient_key.pem, note its serial number), and obtain the WeChat Pay platform certificate or public key used to verify responses and callbacks. - Domestic fee rates are set per category, commonly in the region of 0.6 percent for standard goods; check the current rate for your category in the console.
Alipay
- Register an enterprise account on Alipay and a developer account at open.alipay.com; create an application (web/mobile or Mini Program) and add products such as PC website payment, mobile website payment, App payment and face-to-face (QR) payment. Each product requires signing the corresponding agreement.
- Generate an RSA2 (SHA256withRSA) key pair with the Alipay key tool, upload the public key or switch to certificate mode (application certificate, Alipay public key certificate, Alipay root certificate), and record the
app_id. - Fees are also category-based and comparable to WeChat Pay; check the signed agreement.
Payment Products
| Scenario | WeChat Pay | Alipay |
|---|---|---|
| Inside WeChat or an Alipay Mini Program | JSAPI (/v3/pay/transactions/jsapi, needs openid) | alipay.trade.create (needs buyer_id) |
| Desktop web, customer scans QR | Native (/v3/pay/transactions/native, returns code_url) | alipay.trade.precreate (returns qr_code) or alipay.trade.page.pay |
| Mobile browser outside the wallet | H5 (/v3/pay/transactions/h5, returns h5_url; needs H5 product approval and referer domain) | alipay.trade.wap.pay |
| Native iOS/Android app | App (/v3/pay/transactions/app, then SDK call with signed params) | alipay.trade.app.pay via Alipay SDK |
| Counter, customer shows barcode | Micropay | alipay.trade.pay with auth_code |
Rules that decide the product: an Official Account page opened inside WeChat must use JSAPI (H5 is blocked there); a Mini Program cannot open Alipay; an iOS native app selling digital content faces Apple's in-app purchase rules regardless of wallet.
Request Signing
WeChat Pay APIv3
The signature covers exactly five lines, each terminated by a newline:
HTTP method
URL path with query string
timestamp (seconds)
nonce
request body (empty string for GET)
Sign with the merchant private key (SHA256 with RSA), base64 the result, and send:
Authorization: WECHATPAY2-SHA256-RSA2048 mchid="1900000001",nonce_str="abc",signature="BASE64",timestamp="1756800000",serial_no="MERCHANT_CERT_SERIAL"
Responses carry Wechatpay-Timestamp, Wechatpay-Nonce, Wechatpay-Signature and Wechatpay-Serial; verify them with the platform certificate or public key whose serial matches. JSAPI order body:
{
"appid": "wx1234567890abcdef",
"mchid": "1900000001",
"description": "Order 1001",
"out_trade_no": "1001-20260903-7f3a",
"notify_url": "https://api.example.com.cn/pay/wxpay/notify",
"amount": { "total": 100, "currency": "CNY" },
"payer": { "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o" }
}
The prepay_id is then packaged for the client: sign appId, timeStamp, nonceStr and package=prepay_id=... (each followed by a newline) with the same private key and hand the four values plus paySign and signType=RSA to wx.requestPayment or the JS bridge.
Alipay
Every request is a form to https://openapi.alipay.com/gateway.do with public parameters app_id, method, format=JSON, charset=utf-8, sign_type=RSA2, timestamp (yyyy-MM-dd HH:mm:ss, Beijing time), version=1.0, notify_url, and biz_content (a JSON string). To sign: drop empty values and sign, sort keys ASCII-ascending, join as k=v&k=v, sign with your RSA2 private key, base64. In certificate mode add app_cert_sn and alipay_root_cert_sn. Use the official SDK for your language rather than hand-rolling this; the ordering and encoding rules are where homemade clients fail.
{
"out_trade_no": "1001-20260903-7f3a",
"total_amount": "1.00",
"subject": "Order 1001",
"timeout_express": "15m"
}
Notification Callbacks
WeChat Pay
- Read the raw body before any JSON parsing middleware alters it. Verify
Wechatpay-Signatureovertimestamp,nonceand body (each newline-terminated) using the platform key with the given serial. - Decrypt
resource.ciphertextwith AES-256-GCM using the APIv3 key,resource.nonceandresource.associated_data. - Match
out_trade_no, compareamount.totalandmchidto your order, and checktrade_state == "SUCCESS". - Update the order inside a transaction that is idempotent on
transaction_id. - Reply HTTP 200 with
{"code":"SUCCESS","message":"OK"}. Any other status triggers retries on a back-off schedule for about 24 hours.
Alipay
- Receive a POST form. Remove
signandsign_type, sort the rest, verify with the Alipay public key (or the public key certificate). - Confirm
app_id,out_trade_no,total_amountandseller_idmatch your records. - Act on
trade_statusofTRADE_SUCCESSorTRADE_FINISHED; ignoreWAIT_BUYER_PAY; close onTRADE_CLOSED. - Respond with the plain text
success. Alipay retries for roughly a day otherwise.
Always back callbacks with a scheduled query (/v3/pay/transactions/out-trade-no/{out_trade_no}?mchid=..., alipay.trade.query) for orders older than a few minutes still in pending state, and close abandoned orders (.../close, alipay.trade.close) so the customer cannot pay a stale price.
Refunds
- WeChat Pay:
POST /v3/refund/domestics/refundswithout_trade_noortransaction_id, a uniqueout_refund_no, andamountcarryingrefund,totalandcurrency. Partial refunds are allowed up to the original total across all refunds. Status arrives byREFUND.SUCCESSnotification and by refund query. Refund funds come from the merchant's unsettled or basic account balance, so a low balance makes refunds fail. - Alipay:
alipay.trade.refundwithout_trade_noortrade_no,refund_amountand a uniqueout_request_no; check withalipay.trade.fastpay.refund.query. A refund of the full amount closes the trade. - Refund windows exist (commonly around one year from payment); check the current rule in each merchant agreement and design customer service policies around it.
Reconciliation
- WeChat Pay trade bill:
GET /v3/bill/tradebill?bill_date=2026-09-02&bill_type=ALLreturns a signeddownload_urland a hash; fetch it with a signed request. The fund flow bill (/v3/bill/fundflowbill) shows account movements including fees. Bills for a day are usually ready the next morning. - Alipay:
alipay.data.dataservice.bill.downloadurl.querywithbill_type=trade(orsigncustomerfor account flow) andbill_datereturns a short-lived URL to a zip of CSV files. - Procedure each morning:
- Download both bills for the previous day.
- Parse into rows keyed by wallet transaction ID; normalise amounts to fen.
- Three-way match: bill row, your order ledger, your refund ledger.
- Categorise exceptions: paid but unknown order (log the notification gap), order marked paid without bill row (suspect fraud or a failed transaction), amount mismatch, fee mismatch.
- Book fees and settlement to the general ledger; export the exception list to a human before noon.
- Watch for timezone drift: bills are Beijing time; a UTC-based cutoff will misplace late-night orders.
Cross-Border Merchant Variants
- An overseas entity without a mainland licence can contract with WeChat Pay's cross-border programme (directly or through an acquiring institution) and with Alipay's international merchant service. Consumers pay in CNY; you settle in a supported foreign currency at the wallet's rate, with cross-border fees higher than domestic rates.
- The API surface mirrors the domestic products but lives under separate endpoints and documentation (for WeChat Pay, the global API family under
/v3/global/); do not mix domestic and global credentials. - For cross-border e-commerce retail imports, the payment provider must file the payment record with China Customs. Both wallets expose a customs declaration API for this; it needs the consumer's real name and ID number collected with separate consent under PIPL.
- Foreign-exchange settlement follows SAFE rules applied by the wallet; you will be asked for order-level evidence when volumes rise.
Sandbox and Testing
- Alipay provides a sandbox environment in the developer console with its own
app_id, gateway host, test buyer and seller accounts, and a sandbox wallet app for Android. Use it for signing and flow tests, then re-test on production with small amounts because sandbox behaviour lags. - WeChat Pay APIv3 has no full sandbox. Test on the production merchant with 0.01 CNY orders and immediate refunds, using a test-only
out_trade_noprefix so reconciliation can exclude them. - Simulate callbacks locally by signing payloads with a test key pair and pointing the verifier at your own test certificate; never disable verification in a non-production build that could leak into production.
Checklist
- Correct product chosen per surface (JSAPI in WeChat, H5 outside, Native for desktop)
-
appidbound tomchid; authorization directory and referer domains configured - Private keys stored in a secrets manager; serial numbers and expiry tracked
- Callback endpoint reads raw body, verifies signatures, is idempotent, replies fast
- Pending-order query job and close-order job scheduled
- Refund path tested including partial refund and insufficient balance
- Daily bill download and three-way match automated with exception report
- Amounts stored in minor units; Beijing-time cutoffs used for bills
- PIPL consent captured for ID number collection in customs flows
Common Mistakes
- Parsing the callback JSON before verifying the signature over the raw bytes.
- Verifying WeChat Pay callbacks with the merchant certificate instead of the platform key.
- Marking the order paid on the client
successevent. - Reusing
out_trade_noafter a failed attempt at a different amount; WeChat Pay rejects it. Generate a new number per attempt. - Letting the proxy strip
Wechatpay-*headers or rewrite the body encoding. - Forgetting that H5 pay requires a whitelisted referer domain and does not work inside the WeChat browser.
- Treating the wallet's settlement as revenue without deducting fees found only in the fund flow bill.
Limits
This skill covers integration mechanics; endpoint details, fee rates, refund windows and cross-border eligibility change, so confirm them in the WeChat Pay and Alipay developer documentation and your signed agreements. It is not legal, tax or regulatory advice. Consult a PRC-qualified lawyer for merchant eligibility and PIPL obligations, a licensed accountant for revenue recognition and foreign-exchange treatment, and the wallets' merchant support for anything that touches settlement.
Install this skill directly: skilldb add china-market-skills
Related Skills
Baidu SEO and Search
Activate this skill when the user wants organic visibility in mainland China search, is comparing Baidu to Google ranking behaviour, setting up Baidu Webmaster Tools, planning Simplified Chinese keywords, or building brand presence on Baidu Baike and Zhidao. Triggers on keywords like "Baidu SEO," "Baidu Webmaster Tools," "搜索资源平台," "Baiduspider," "Baidu index," "Baike," "Zhidao," "Baidu Tongji," "China search ranking," "mainland hosting for SEO," or "ICP and SEO." Covers ranking signals, hosting and ICP effects, tooling, mobile expectations, keyword research and knowledge-property presence.
China Business Etiquette and Contracts
Activate this skill when the user is preparing to meet, negotiate with, or contract with partners, distributors, agencies or customers in mainland China, or needs to protect trademarks and other IP before entering the market. Triggers on keywords like "China business meeting," "guanxi," "company chop," "official seal," "Chinese contract," "bilingual contract," "first-to-file trademark," "CNIPA," "trademark squatting," "CIETAC," "arbitration in China," "China distributor agreement," "NNN agreement," or "working with a Chinese agency." Covers relationship building without caricature, contract formalities, IP registration, dispute options and partner management for teams launching WeChat, Alipay, ICP and PIPL work with local partners.
Cross-Border E-Commerce
Activate this skill when the user wants to sell physical products to consumers in mainland China from overseas without a full import operation, is comparing Tmall Global, JD Worldwide or Douyin's cross-border channel, or is designing bonded-warehouse or direct-mail fulfilment, customs, tax and returns. Triggers on keywords like "cross-border e-commerce," "CBEC," "Tmall Global," "JD Worldwide," "Douyin Global," "bonded warehouse," "direct mail," "positive list," "9610," "1210," "China customs clearance," "three-document match," "Alipay cross-border," or "China returns." Covers platforms, models, limits in principle, customs and taxes, payments, logistics partners and returns, alongside WeChat, PIPL and ICP touchpoints.
Douyin and Xiaohongshu Marketing
Activate this skill when the user is planning social or influencer marketing for mainland China on Douyin or Xiaohongshu, choosing between KOLs and KOCs, running a seeding campaign, setting up live-commerce, or checking advertising wording. Triggers on keywords like "Douyin," "抖音," "Xiaohongshu," "小红书," "RED," "KOL," "KOC," "seeding," "种草," "live streaming commerce," "Xingtu," "Pugongying," "Advertising Law superlatives," "MCN," "China marketing agency," or "China social media measurement." Covers platform norms, creator tiers, e-commerce loops, compliance wording, measurement and agency selection alongside WeChat and Baidu channels.
ICP Filing and Hosting
Activate this skill when the user needs to host a website, app backend or Mini Program for users in mainland China and is asking about ICP filing, ICP licences, mainland cloud hosting, CDN, why their site is slow from China, or security grading. Triggers on keywords like "ICP," "Bei'an," "备案," "ICP licence," "MIIT," "mainland hosting," "Alibaba Cloud," "Tencent Cloud," "China CDN," "Great Firewall latency," "MLPS," "等保," or "public security filing." Covers who may file, prerequisites, timelines, CDN interplay and the hosting choices that follow from PIPL and WeChat requirements.
PIPL and Data Compliance
Activate this skill when the user is designing data collection, consent, storage or cross-border transfer for an app or service that serves users in mainland China, or is asked how PIPL, the Data Security Law and the Cybersecurity Law fit together. Triggers on keywords like "PIPL," "personal information protection," "separate consent," "sensitive personal information," "cross-border data transfer," "CAC security assessment," "standard contract," "data localization," "CIIO," "Data Security Law," "MLPS," "China privacy policy," "SDK compliance," or "app privacy pop-up." Covers principles, consent mechanics, transfer paths, localization and architecture choices, alongside ICP, WeChat and Alipay data touchpoints.