1. 前置依赖
接入准备
小程序开发环境配置
APIv3接口规则。
私钥和证书、APIv3密钥。
2. 集成SDK
为了帮助开发者更好的调用接口,我们提供 微信支付APIv3官方SDK ,请根据自身开发语言,选择对应的SDK库集成到项目,并在商户平台配置平台证书。
目前微信支付提供JAVA、PHP、GO三种语言版本的SDK,封装了签名生成、签名验证、敏感信息加/解密、媒体文件上传等基础接口功能。
各编程语言的SDK对“小程序支付”的业务接口支持不一样,如若未支持相关业务接口,你可以使用SDK中的HTTP类实现发送HTTP请求,它会自动生成签名和验证签名。
如下通用基础功能接口,已经在SDK中完成封装,可替换相关参数后快速测试。
签名生成
签名验证
敏感信息加解密
merchantPrivateKey(私钥)
wechatpayCertificates(平台证书)
APIV3Key(V3 key)
若使用的编程语言无对应的SDK,则需要按照接口规则与接口详细信息自行开发。
3. 小程序支付业务接入说明
3.1. 业务流程图
3.1.1. 关键步骤说明
步骤4: 商户通过小程序下单创建支付订单。注意下单传入的参数appid
,必须为用户选购并且付款的微信小程序AppID。
步骤7: 生成带签名支付信息,商户必须使用下单时的appid
,作为签名参数。签名方法参考:小程序调起支付API
步骤9: 商户小程序内小程序SDK调起微信支付,详见小程序API文档 。小程序SDK会自动将当前用户使用的小程序AppID传给微信支付,微信支付将会校验当前小程序AppID是否与下单、签名所使用的一致。
步骤16: 用户支付成功后,商户可接收到微信支付支付结果通知支付通知API。
步骤21: 商户在没有接收到微信支付结果通知的情况下需要主动调用查询订单API查询支付结果。
| 注意: 建议为确保收款成功避免资金损失,无论是否收到支付成功通知都请主动查单。 |
|
3.2. API接入(含示例代码)
本章节展示了如何使用微信支付服务端 SDK 快速接入小程序支付产品,完成与微信支付对接的部分。
3.2.1. 【服务端】小程序下单
步骤说明: 用户通过商户小程序进入商户网页,当用户选择相关商品购买时,商户系统先调用该接口在微信支付服务后台生成预支付交易单。
1public void CreateOrder() throws Exception{
2
3HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/miniprogram");
4
5
6String reqdata = "{"
7 + "\"amount\": {"
8 + "\"total\": 100,"
9 + "\"currency\": \"CNY\""
10 + "},"
11 + "\"mchid\": \"1900006891\","
12 + "\"description\": \"Image形象店-深圳腾大-QQ公仔\","
13 + "\"notify_url\": \"https://www.weixin.qq.com/wxpay/pay.php\","
14 + "\"payer\": {"
15 + "\"openid\": \"o4GgauE1lgaPsLabrYvqhVg7O8yA\"" + "},"
16 + "\"out_trade_no\": \"1217752501201407033233388881\","
17 + "\"goods_tag\": \"WXG\","
18 + "\"appid\": \"wxdace645e0bc2c424\"" + "}";
19StringEntity entity = new StringEntity(reqdata,"utf-8");
20entity.setContentType("application/json");
21httpPost.setEntity(entity);
22httpPost.setHeader("Accept", "application/json");
23
24CloseableHttpResponse response = httpClient.execute(httpPost);
25try {
26 int statusCode = response.getStatusLine().getStatusCode();
27 if (statusCode == 200) {
28 System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
29 } else if (statusCode == 204) {
30 System.out.println("success");
31 } else {
32 System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
33 throw new IOException("request failed");
34 }
35} finally {
36 response.close();
37}
38}
1try {
2 $resp = $client->request(
3 'POST',
4 'https://api.mch.weixin.qq.com/v3/pay/transactions/miniprogram',
5 [
6
7 'json' => [
8 "time_expire" => "2018-06-08T10:34:56+08:00",
9 "amount" => [
10 "total" => 100,
11 "currency" => "CNY",
12 ],
13 "mchid" => "1230000109",
14 "description" => "Image形象店-深圳腾大-QQ公仔",
15 "notify_url" => "https://www.weixin.qq.com/wxpay/pay.php",
16 "payer" => [
17 "openid" => "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o",
18 ],
19 "out_trade_no" => "1217752501201407033233368018",
20 "goods_tag" => "WXG",
21 "appid" => "wxd678efh567hg6787",
22 "attach" => "自定义数据说明",
23 "scene_info" => [
24 "store_info" => [
25 "address" => "广东省深圳市南山区科技中一道10000号",
26 "area_code" => "440305",
27 "name" => "腾讯大厦分店",
28 "id" => "0001",
29 ],
30 "device_id" => "013467007045764",
31 "payer_client_ip" => "14.23.150.211",
32 ]
33 ],
34 'headers' => [ 'Accept' => 'application/json' ]
35 ]
36 );
37 $statusCode = $resp->getStatusCode();
38 if ($statusCode == 200) {
39 echo "success,return body = " . $resp->getBody()->getContents()."\n";
40 } else if ($statusCode == 204) {
41 echo "success";
42 }
43} catch (RequestException $e) {
44
45 echo $e->getMessage()."\n";
46 if ($e->hasResponse()) {
47 echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
48 }
49 return;
50}
out_trade_no: 商户系统内部订单号,只能是数字、大小写字母_-*且在同一个商户号下唯一。
description: 商品描述。
notify_url: 支付回调通知URL,该地址必须为直接可访问的URL,不允许携带查询串。
total: 订单总金额,单位为分。
OpenID: OpenID是微信用户在AppID下的唯一用户标识(AppID不同,则获取到的OpenID就不同),可用于永久标记一个用户。OpenID获取方式请参考以下文档小程序获取OpenID 、公众号获取OpenID、App获取OpenID。
更多参数、响应详情及错误码请参见小程序下单接口文档。
3.2.2. 【客户端】小程序调起支付API
步骤说明: 通过小程序下单成功获取预支付交易会话标识(prepay_id) 后,需要通过小程序调起支付API来调起微信支付收银台。
1wx.requestPayment(
2{
3"timeStamp": "1414561699",
4"nonceStr": "5K8264ILTKCH16CQ2502SI8ZNMTM67VS",
5"package": "prepay_id=wx201410272009395522657a690389285100",
6"signType": "RSA",
7"paySign": "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==",
8
9"success":function(res){
10
11},
12"fail":function(res){
13
14},
15"complete":function(res){
16
17}
18})
3.2.3. 【服务端】接收支付结果通知
步骤说明: 当用户完成支付,微信会把相关支付结果将通过异步回调的方式通知商户,商户需要接收处理,并按文档规范返回应答。
验证签名
解密回调报文
支付回调和查单实现指引
| 注意: 支付结果通知是以POST 方法访问商户设置的通知URL,通知的数据以JSON 格式通过请求主体(BODY)传输。通知的数据包括了加密的支付结果详情 加密不能保证通知请求来自微信。微信会对发送给商户的通知进行签名,并将签名值放在通知的HTTP头Wechatpay-Signature。商户应当验证签名,以确认请求来自微信,而不是其他的第三方。签名验证的算法请参考 《微信支付API v3签名验证》。 支付通知HTTP应答码为200或204才会当作正常接收,当回调处理异常时,应答的HTTP状态码应为500,或者4xx 商户成功接收到回调通知后应返回成功的HTTP应答码为200或204 同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。 推荐的做法是,当商户系统收到通知进行处理时,先检查对应业务数据的状态,并判断该通知是否已经处理。如果未处理,则再进行处理;如果已处理,则直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱 对后台通知交互时,如果微信收到商户的应答不符合规范或超时,微信认为通知失败,微信会通过一定的策略定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功。(通知频率为15s/15s/30s/3m/10m/20m/30m/30m/30m/60m/3h/3h/3h/6h/6h - 总计 24h4m)特别提醒: 商户系统对于开启结果通知的内容一定要做签名验证,并校验通知的信息是否与商户侧的信息一致,防止数据泄露导致出现“假通知”,造成资金损失。 特别提醒: 商户系统对于开启结果通知的内容一定要做签名验证,并校验通知的信息是否与商户侧的信息一致,防止数据泄露导致出现“假通知”,造成资金损失。
|
|
3.2.4. 【服务端】查询订单
步骤说明:当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知时,商户可通过查询订单接口核实订单支付状态
1public void QueryOrder() throws Exception {
2
3
4 URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/pay/transactions/id/4200000745202011093730578574");
5 uriBuilder.setParameter("mchid", mchId);
6
7
8 HttpGet httpGet = new HttpGet(uriBuilder.build());
9 httpGet.addHeader("Accept", "application/json");
10 CloseableHttpResponse response = httpClient.execute(httpGet);
11
12 try {
13 int statusCode = response.getStatusLine().getStatusCode();
14 if (statusCode == 200) {
15 System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
16 } else if (statusCode == 204) {
17 System.out.println("success");
18 } else {
19 System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
20 throw new IOException("request failed");
21 }
22 } finally {
23 response.close();
24 }
25}
1try {
2 $resp = $client->request(
3 'GET',
4 'https://api.mch.weixin.qq.com/v3/pay/transactions/id/1217752501201407033233368018?mchid=1230000109',
5 [
6 'headers' => [ 'Accept' => 'application/json']
7 ]
8 );
9 $statusCode = $resp->getStatusCode();
10 if ($statusCode == 200) {
11 echo "success,return body = " . $resp->getBody()->getContents()."\n";
12 } else if ($statusCode == 204) {
13 echo "success";
14 }
15} catch (RequestException $e) {
16
17 echo $e->getMessage()."\n";
18 if ($e->hasResponse()) {
19 echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
20 }
21 return;
22}
3.2.5. 【服务端】关闭订单
步骤说明:当商户订单支付失败需要生成新单号重新发起支付,要对原订单号调用关单,避免重复支付;系统下单后,用户支付超时,系统退出不再受理,避免用户继续,请调用关单接口
JAVA
1public void CloseOrder() throws Exception {
2
3
4 HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/sdkphp12345678920201028112429/close");
5
6 String reqdata ="{\"mchid\": \""+mchId+"\"}";
7
8 StringEntity entity = new StringEntity(reqdata,"utf-8");
9 entity.setContentType("application/json");
10 httpPost.setEntity(entity);
11 httpPost.setHeader("Accept", "application/json");
12
13
14 CloseableHttpResponse response = httpClient.execute(httpPost);
15 try {
16 int statusCode = response.getStatusLine().getStatusCode();
17 if (statusCode == 200) {
18 System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
19 } else if (statusCode == 204) {
20 System.out.println("success");
21 } else {
22 System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
23 throw new IOException("request failed");
24 }
25 } finally {
26 response.close();
27 }
28 }
1try {
2 $resp = $client->request(
3 'POST',
4 'https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}/close',
5 [
6
7 'json' => [
8 "mchid " => "1230000109",
9 ],
10 'headers' => [ 'Accept' => 'application/json' ]
11 ]
12 );
13 $statusCode = $resp->getStatusCode();
14 if ($statusCode == 200) {
15 echo "success,return body = " . $resp->getBody()->getContents()."\n";
16 } else if ($statusCode == 204) {
17 echo "success";
18 }
19 } catch (RequestException $e) {
20
21 echo $e->getMessage()."\n";
22 if ($e->hasResponse()) {
23 echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
24 }
25 return;
26 }
更多参数、响应详情及错误码请参见 关闭订单接口文档。
3.2.6. 【服务端】申请交易账单
步骤说明: 微信支付按天提供交易账单文件,商户可以通过该接口获取账单文件的下载地址。
1public void TradeBill() throws Exception {
2
3
4 URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/bill/tradebill");
5 uriBuilder.setParameter("bill_date", "2020-11-09");
6 uriBuilder.setParameter("bill_type", "ALL");
7
8
9 HttpGet httpGet = new HttpGet(uriBuilder.build());
10 httpGet.addHeader("Accept", "application/json");
11 CloseableHttpResponse response = httpClient.execute(httpGet);
12
13 try {
14 int statusCode = response.getStatusLine().getStatusCode();
15 if (statusCode == 200) {
16 System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
17 } else if (statusCode == 204) {
18 System.out.println("success");
19 } else {
20 System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
21 throw new IOException("request failed");
22 }
23 } finally {
24 response.close();
25 }
26}
1try {
2 $resp = $client->request(
3 'GET',
4 'https://api.mch.weixin.qq.com/v3/bill/tradebill?bill_date=2019-06-11&bill_type=ALL', //请求URL
5 [
6 'headers' => [ 'Accept' => 'application/json']
7 ]
8 );
9 $statusCode = $resp->getStatusCode();
10 if ($statusCode == 200) { //处理成功
11 echo "success,return body = " . $resp->getBody()->getContents()."\n";
12 } else if ($statusCode == 204) { //处理成功,无返回Body
13 echo "success";
14 }
15} catch (RequestException $e) {
16 // 进行错误处理
17 echo $e->getMessage()."\n";
18 if ($e->hasResponse()) {
19 echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
20 }
21 return;
22}
3.2.7. 【服务端】下载账单
步骤说明:通过申请交易账单接口获取到账单下载地址(download_url)后,再通过该接口获取到对应的账单文件,文件内包含交易相关的金额、时间、营销等信息,供商户核对订单、退款、银行到账等情况。
| 注意: 账单文件的下载地址的有效时间为30s。 强烈建议商户将实际账单文件的哈希值和之前从接口获取到的哈希值进行比对,以确认数据的完整性。 该接口响应的信息请求头中不包含微信接口响应的签名值,因此需要跳过验签的流程。 微信在次日9点启动生成前一天的对账单,建议商户10点后再获取。
|
|
1public void DownloadUrl(String download_url) throws Exception{
2 PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
3
4
5
6 httpClient = WechatPayHttpClientBuilder.create().withMerchant(mchId, mchSerialNo, merchantPrivateKey).withValidator((response) -> true).build();
7
8
9
10 URIBuilder uriBuilder = new URIBuilder(download_url);
11 HttpGet httpGet = new HttpGet(uriBuilder.build());
12 httpGet.addHeader("Accept", "application/json");
13
14
15 CloseableHttpResponse response = httpClient.execute(httpGet);
16 try {
17 int statusCode = response.getStatusLine().getStatusCode();
18 if (statusCode == 200) {
19 System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
20 } else if (statusCode == 204) {
21 System.out.println("success");
22 } else {
23 System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
24 throw new IOException("request failed");
25 }
26 } finally {
27 response.close();
28 }
29}
1try {
2 $resp = $client->request(
3 'GET',
4 'https://api.mch.weixin.qq.com/v3/billdownload/file?token=xx',
5 [
6 'headers' => [ 'Accept' => 'application/json']
7 ]
8 );
9 $statusCode = $resp->getStatusCode();
10 if ($statusCode == 200) {
11 echo "success,return body = " . $resp->getBody()->getContents()."\n";
12 } else if ($statusCode == 204) {
13 echo "success";
14 }
15} catch (RequestException $e) {
16
17 echo $e->getMessage()."\n";
18 if ($e->hasResponse()) {
19 echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
20 }
21 return;
22}
更多参数、响应详情及错误码请参见 下载账单接口文档。