In order to provide a simple, consistent and easy-to-use development experience to merchants while ensuring payment security, we have launched the latest WeChat Pay APIv3 interface. Please refer to “APIv3 Interface Rules” for the specific rules of this API version.
To help developers call the open interface, the development libraries of Java、PHP、GO are provided, encapsulating the basic functions such as signature generation, signature verification, encryption/decryption of sensitive information, and media document upload
The document shows how to use the WeChat Pay server SDK to In-App Payment by scanning code and interface with WeChat Pay.
• The code examples in the document illustrate the basic usage of API. Before running the code, the example parameters in the code need to be replaced with the merchant's own account and request parameters.
• The access steps below are for your information, and should be evaluated and modified according to the merchant’s own business demands.
Procedure: Submit a pre-order request for mini program payment through this interface, obtain the prepay_id to call payment.
Code example
@Test
//Call Unified Order API
public void unifiedOrderTest() throws IOException {
String unifiedOrderBody = String.join("\n" ,
"{" ,
"'sp_appid': 'wx2421b1c4370ec43b'," ,
"'sp_mchid': '10000100'," ,
"'sub_mchid': '20000100'," ,
"'sub_appid': 'wx352671b037b437ec'," ,
"'out_trade_no': '20150806125346'," ,
"'merchant_category_code': '1011'," ,
"'payer': {" ,
"'sub_openid': 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o'" ,
"}," ,
"'notify_url': 'https://wxpay.wxutil.com/pub_v2/pay/notify.v2.php'," ,
"'trade_type': 'JSAPI'," ,
"'amount': {" ,
"'total': 10000," ,
"'currency': 'HKD'" ,
"}," ,
"'attach': 'Payment test'," ,
"'description': 'Miniprogramm Pay test'," ,
"'detail': {" ,
"'cost_price': 10000," ,
"'receipt_id': '1234'," ,
"'goods_detail': [{" ,
"'goods_id': 'iphone6s_16G'," ,
"'wxpay_goods_id': '1001'," ,
"'goods_name': 'iPhone6s 16G'," ,
"'quantity': 1," ,
"'price': 528800" ,
"}]" ,
"}," ,
"'scene_info': {" ,
"'payer_client_ip': '14.23.150.211'," ,
"'device_ip': '59.37.125.32'," ,
"'device_id': '013467007045764'," ,
"'operator_id': 'P001'," ,
"'store_info': {" ,
"'id': 'SZTX001'" ,
"}" ,
"}" ,
"}").replace("'","\"");
HttpPost httpPost = new HttpPost("https://apihk.mch.weixin.qq.com/v3/global/transactions/jsapi");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(unifiedOrderBody));
CloseableHttpResponse response = httpClient.execute(httpPost);
//Process the response
}
Critical parameters:
out_trade_no: internal order ID in merchant’s system
notify_url: For the address used to receive the asynchronous payment result callback notification, the notification URL must be a URL that is accessible by the external network and cannot carry any parameters. Please use an HTTPS protocol link
openid: User’s unique ID under the corresponding merchant appid will be returned only when appid is passed. For details on how to retrieve openid, see Obtaining openid
sub_openid: It is the user’s unique ID under the sub-merchant sub_appid, and either sp_openid or sub_openid can be selected. If sub_openid is selected, sub_appid must be passed in. Before an order is placed, the【Web Authorization】interface needs to be called to obtain the user’s openid.
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: The merchant needs to return the payment transaction ID received and paySign to the mini program, and then pull up the WeChat payment cashier in the mini program for the user to confirm the order information and payment.
Constructing Signature String
There are four lines in the signature string, and each line is a parameter. Each line ends with \n (Newline character; the ASCII code value is 0x0A), and even the last line shall ends with \n.If the parameter itself ends with \n, an additional \n is also required
Fields and formats involved in the signature:
Mini Program id
Time stamp
Random string
An extension string for order details
Example of a string to be signed:
wx8888888888888888
1414561699
5K8264ILTKch16CQ2502SI8ZNMTM67VS
prepay_id=123456789
Calculate Signature Value:
Sign in the same way as the request data signature , use the merchant's private key to sign the signature string with SHA256 with RSA, and perform Base64 encoding on the signature result to obtain the signature value.
wx.requestPayment(
{
"timeStamp": "1414561699",
"nonceStr": "5K8264ILTKch16CQ2502SI8ZNMTM67VS",
"package": "prepay_id=wx201410272009395522657a690389285100",
"signType": "RSA",
"paySign": "UGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==",
'success':function(res){},
'fail':function(res){},
'complete':function(res){}
})
Critical parameters:
paySign: constructed payment signature
package:The value of the prepay_id parameter returned by the unified order placement API, in the format of prepay_id=***
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: The merchant is required to take the initiative to check the order status after placing an order for a certain period of time.
Code example:
@Test
//Call query order API
public void queryOrderTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/transactions/id/" +
"4200123456789000?sub_mchid=100012321&sp_mchid=1900000000");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
}
Critical parameters:
id: WeChat payment order ID
out_trade_no: internal order ID in merchant’s system
Query with any order ID above. Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After the payment is completed and the payment status is SUCCESS, call this interface to submit a refund request.
Code example
@Test
//Call Refund API
public void refundTest() throws IOException {
String refundBody = String.join("\n" ,
"{" ,
"'sp_appid': 'wx2421b1c4370ec43b', " ,
"'sp_mchid': '10000100'," ,
"'sub_mchid': '20000100'," ,
"'transaction_id': '1008450740201411110005820873'," ,
"'out_refund_no': 'R20150806125346'," ,
" 'amount' : {" ,
" 'refund': 5," ,
" 'total':10," ,
" 'currency':'HKD'" ,
" }," ,
" 'reason': 'The item has been sold out.'," ,
" 'source': 'REFUND_SOURCE_UNSETTLED_FUNDS'" ,
"}").replace("'","\"");
HttpPost httpPost = new HttpPost("https://apihk.mch.weixin.qq.com/v3/global/refunds");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(refundBody));
CloseableHttpResponse response = httpClient.execute(httpPost);
//Process the response
}
Critical parameters:
out_trade_no: internal order ID in merchant’s system
transaction_id: WeChat order ID
out_refund_no: internal refund No. in merchant’s system, which should correspond to order ID
notify_url: address for receiving refund results
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After submitting a refund request, query the refund status by calling this interface.
Code example
@Test
//Call Query Refund API
public void querySingleRefundTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/refunds/out-refund-no/RYX001?sub_mchid=100012321&sp_mchid=1900000000");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
}
Critical parameters:
out_trade_no: internal refund No. in merchant’s system
refund_id:WeChat payment refund order ID
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After submitting a refund request, query all refund information corresponding to one payment order.
Code example
@Test
//Call Query All Refund API
public void queryAllRefundTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/refunds" +
"?out_trade_no=YX202111100020&count=10&offset=0&sp_mchid=1900000000&sub_mchid=100012321");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
}
Critical parameters:
out_trade_no: Internal order ID in merchant’s system
transaction_id: WeChat order ID
offset: Start position of paging
count: Number of records returned in a single page, up to 20 records.
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: Merchants can download the historical transaction statements by calling this interface on a daily basis, and correct the payment information by reconciling the statements.
Code example
@Test
//Downloading Reconciliation API
public void downloadReconTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/statements?date=20220401&mchid=1900000000");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
}
Critical parameters:
date: Statement date, format: 20180103
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After placing an order, call this interface to close the orders not paid, allowing the merchant replace the order ID to re-order and initiate payment or avoid repeated payment by the user after quiting merchant's system without accepting the order.
Code example
@Test
//Call close order API
public void closeOrderTest() throws IOException {
String closeBody = String.join("\n" ,
"{" ,
" 'sp_mchid': '10000100'," ,
" 'sub_mchid': '20000100'" ,
"}").replace("'","\"");
HttpPost httpPost = new HttpPost("https://apihk.mch.weixin.qq.com/v3/global/transactions/out-trade-no/YX001/close");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(closeBody));
CloseableHttpResponse response = httpClient.execute(httpPost);
System.out.println(response.getStatusLine().getStatusCode());
}
Critical parameters:
out_trade_no: Internal order ID in merchant’s system
transaction_id: WeChat order ID
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: Before calling other interfaces, call this interface to download the platform certificate to verify the signature of the returned message and decrypt the encrypted fields therein.
Code example
@Test
//Call certificate downloading API
public void certDownloadingTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/certificates");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
//Get the response body: EntityUtils.toString(response.getEntity());
//Get the response status code: response.getStatusLine().getStatusCode();
//Instead of calling the API to download platform certificate,
//We also recommend use the certificateMenager to get the valid certificate
verifier.getValidCertificate();
}
Critical parameters: None
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After the user makes the payment, WeChat Pay will push the payment result notification to the notify_url introduced while placing the order, and the merchant needs to feed back accordingly after receiving the notification.
• The same notification may be sent to the merchant system multiple times. The merchant system must be able to process duplicate notifications properly. It is recommended to first check the status of the corresponding business data when receiving a notification for processing, and determine whether the notification has been processed. If it has not been processed, the notification should be processed once again; if it has been processed, the success result should be returned. Before status checking and processing of the business data, a data lock should be used to implement concurrency control and avoid data confusion caused by function reentry.
• If no callback is received from WeChat side after all notification frequencies (4 hours), the merchant shall call the Query Order interface to confirm the order status.
Special reminder: The merchant system must perform signature verification for the content of the notification of payment results, and verify whether the returned order amount is consistent with that of the merchant side, thus preventing any "false notifications" and even loss of funds caused by data leakage.
After the payment is made, WeChat will send the related payment result and user information to the merchant. The merchant needs to receive and process the information, and return the response successfully. Only the successful payments will be notified.
When interacting with the background notification, if the response received by WeChat from the merchant is not success or timed out, WeChat thinks the notification fails. WeChat will periodically resend the notification according to the specified policy to maximize the success rate of the notification, but WeChat does not guarantee final success of the notification. ((Notification frequency is 15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - total 24h and 4m)) for repeated notification.
The payment result notification accesses the notification URL set by the merchant using the POST method, and the notification data is transmitted through the request body (BODY) in the JSON format. The data in the notification includes the encrypted payment result details.
The certificate decryption process is detailed as follows
1、Obtain the merchant's key from the merchant platform, and record it as “key”.
2、Get the corresponding parameters “nonce” and “associated_data” for the algorithm described in “algorithm” (currently AEAD_AES_256_GCM).
3、Decrypt “ciphertext” with “key”, “nonce” and “associated_data” (decode base64 for ciphertext first, and then decrypt it) to obtain the certificate content
Encryption does not guarantee that the notification requests come from WeChat. WeChat will sign the notification sent to the merchant and put the signature value in the HTTP header Wechatpay-Signature of the notification. Merchants should verify the signature to confirm that the request comes from WeChat, and not any other third parties. For the signature verification algorithm, please refer to WeChat Pay API V3 Signature Verification.
Notification of Successful Payments
{
"id":"EV-2018022511223320873",
"create_time":"20180225112233",
"resource_type":"encrypt-resource",
"event_type":"TRANSACTION.SUCCESS",
"resource" : {
"algorithm":"AEAD_AES_256_GCM",
"ciphertext": "...",
"nonce": "...",
"associated_data": ""
}
}
An example of the resource object obtained after the merchant decrypts the resource object
{
"id": "1008450740201411110005820873",
"sp_appid": "wx2421b1c4370ec43b",
"sp_mchid": "10000100",
"sub_mchid": "20000100",
"out_trade_no": "20150806125346",
"payer": {
"sp_openid": "oUpF8uN95-Ptaags6E_roPHg7AG0"
},
"amount" : {
"total": 528800,
"currency": "HKD",
"payer_total": 518799,
"payer_currency": "CNY",
"exchange_rate" : {
"type": "SETTLEMENT_RATE",
"rate": 8000000
}
},
"trade_type": "MICROPAY",
"trade_state": "SUCCESS",
"trade_state_desc": "支付成功",
"bank_type": "CCB_DEBIT",
"attach": "支付测试",
"success_time": "2018-06-08T10:34:56+08:00",
"promotion_detail":[
{
"promotion_id":"109519",
"name":"单品惠-6",
"scope":"SINGLE",
"type":"DISCOUNT",
"amount":1,
"currency":"HKD",
"activity_id":"931386",
"wechatpay_contribute_amount":1,
"merchant_contribute_amount":0,
"other_contribute_amount":0,
"goods_detail":[
{
"goods_id":"iphone6s_16G",
"goods_remark":"商品备注",
"quantity":1,
"price":528800
}
]
}
]
}
The http response code of the payment notification should be either 200 or 204 for normal receipt. In case of any callback processing error, the HTTP status code of the response should be 500 or 4xx.
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After the user makes the payment, WeChat Pay will push the payment result notification to the notify_url introduced while placing the order, and the merchant needs to feed back accordingly after receiving the notification.
• The same notification may be sent to the merchant system multiple times. The merchant system must be able to process duplicate notifications properly. It is recommended to first check the status of the corresponding business data when receiving a notification for processing, and determine whether the notification has been processed. If not, the notification should be processed; if it has been processed, the success result should be returned. Before status checking and processing of the business data, a data lock should be used to implement concurrency control and avoid data confusion caused by function reentry.
• If no callback is received from WeChat side after all notification frequencies (4 hours), the merchant shall call the Query Order interface to confirm the order status.
Special reminder: The merchant system must perform signature verification for the content of the notification of payment results, and verify whether the returned order amount is consistent with that of the merchant side, thus preventing any "false notification" and even capital loss caused by data leakage.
In case of any refund status changes, WeChat will send the related refund results to the merchant.
When interacting with the background notification, if the response received by WeChat from the merchant is not success or timed out, WeChat thinks the notification fails. WeChat will periodically resend the notification according to the specified policy to maximize the success rate of the notification, but WeChat does not guarantee final success of the notification. ((Notification frequency is 15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - total 24h and 4m))
The deduction result notification accesses the notification URL set by the merchant using the POST method, and the notification data is transmitted through the request body (BODY) in the JSON format. The data in the notification includes the details about the encrypted refund result.
The certificate decryption process is detailed as follows
1、Obtain the merchant's key from the merchant platform, and record it as “key”.
2、Get the corresponding parameters “nonce” and “associated_data” for the algorithm described in “algorithm” (currently AEAD_AES_256_GCM).
3、Decrypt “ciphertext” with “key”, “nonce” and “associated_data” (perfomr base64 decoding for ciphertext first, and then decrypt it) to obtain the certificate content
Encryption does not guarantee that the notification requests come from WeChat. WeChat will sign the notification sent to the merchant and put the signature value in the HTTP header Wechatpay-Signature of the notification. Merchants should verify the signature to confirm that the request comes from WeChat, and not any other third parties. For the signature verification algorithm, please refer to WeChat Pay API V3 Signature Verification.
Notification of Refund Result
{
"id": "EV-2018022511223320873",
"create_time": "2018-06-08T10:34:56+08:00",
"resource_type": "encrypt-resource",
"event_type": "REFUND.SUCCESS",
"summary": "退款成功",
"resource": {
"original_type": "refund",
"algorithm": "AEAD_AES_256_GCM",
"ciphertext": "...",
"associated_data": "",
"nonce": "..."
}
}
An example of the resource object obtained after the merchant decrypts the resource object
{
"sp_mchid": "1900000100",
"sub_mchid": "1900000109",
"transaction_id": "1008450740201411110005820873",
"out_trade_no": "20150806125346",
"refund_id": "50200207182018070300011301001",
"out_refund_no": "7752501201407033233368018",
"refund_status": "SUCCESS",
"success_time": "2018-06-08T10:34:56+08:00",
"recv_account": "招商银行信用卡0403",
"fund_source": "REFUND_SOURCE_UNSETTLED_FUNDS",
"amount" : {
"total": 528800,
"currency": "HKD",
"refund": 528800,
"payer_total": 528800,
"payer_refund": 528800,
"payer_currency": "HKD",
"exchange_rate" : {
"type": "SETTLEMENT_RATE",
"rate": 100000000
}
}
}
The http response code of the refund notification should be either 200 or 204 for normal receipt. In case of any callback processing error, the HTTP status code of the response should be 500 or 4xx.
Please refer to the API document for ordering by scanning code for other critical parameters.
Procedure: After transactions are completed, the merchant can query the settled fund details (sette_state is SETTLED) or the unsettled fund details (sette_state is UNSETTLE) by settlement date.
Code example
@Test
//Query Settlement API
public void querySettlementTest() throws IOException {
HttpGet httpGet = new HttpGet("https://apihk.mch.weixin.qq.com/v3/global/settle/settlements" +
"?sub_mchid=100012321&settle_state=SETTLED&settle_start_date=20221225" +
"&settle_end_date=20221226&offset=10&limit=5");
httpGet.addHeader("Accept", "application/json");
httpGet.addHeader("Content-type", "application/json; charset=utf-8");
CloseableHttpResponse response = httpClient.execute(httpGet);
//Process the response
}
Critical parameters:
settle_state: Fund settlement status, enumeration value:
SETTLED:settled
UNSETTLE:not settled
Please refer to the API document for ordering by scanning code for other critical parameters.
Customer Service Tel
Business Development
9:00-18:00
Monday-Friday GMT+8
Technical Support
WeChat Pay Global
ICP证