开发指引

更新时间:2024.09.19

1. 接口规则

为了在保证支付安全的前提下,带给商户简单、一致且易用的开发体验,我们推出了全新的微信支付APIv3接口。该版本API的具体规则请参考APIv3接口规则

2. 开发准备

2.1. 搭建和配置开发环境

开发者应当依据自身的编程语言来构建并配置相应的开发环境。

3. 快速接入

3.1. 业务流程图

重点步骤说明:

步骤2 用户确认支付后,商户调用微信支付Native下单API生成预支付交易以获取支付二维码链接code_url;

商户调用Native下单API后,分正常返回和异常返回情况:

  • 正常返回: 返回code_url,商户可根据返回的code_url来生成调用OpenSDK的签名以执行下一步。

  • 异常返回: 返回HTTP code或错误码,商户可根据HTTP code列表错误码说明来排查原因并执行下一步操作。

步骤4 商户根据返回的code_url生成二维码供用户扫描,有关二维码的规则请参考3.2.2部分的说明。

步骤9-11 商户根据返回的code_url生成二维码供用户扫描,有关二维码的规则请参考3.2.2部分的说明。

  • 方法一: 支付结果通知。用户支付成功后,微信支付会将支付成功的结果以回调通知的形式同步给商户,商户的回调地址需要在调用Native下单API时传入notify_url参数。

  • 方法二: 当因网络抖动或本身notify_url存在问题等原因,导致无法接收到回调通知时,商户也可主动调用查询订单API来获取订单状态。

3.2. API接入(含示例代码)

本章节展示了如何使用微信支付服务端 SDK 快速接入Native支付产品,完成与微信支付对接的部分。

注意

  • 文档中的代码示例是用来阐述 API 基本使用方法,代码中的示例参数需替换成商户自己账号及请求参数才能跑通

  • 以下接入步骤仅提供参考,请商户结合自身业务需求进行评估、修改。

3.2.1. 【服务端】Native下单

步骤说明: 用户在商户PC网站内完成商品选择后进入支付页面,商户需要通过后端请求该Native下单API来获取支付二维码链接code_url。

JAVA代码示例:

1public void CreateOrder() throws Exception{
2HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
3  // 请求body参数
4  String reqdata = "{"
5          + "\"time_expire\":\"2018-06-08T10:34:56+08:00\","
6          + "\"amount\": {"
7          + "\"total\":100,"
8          + "\"currency\":\"CNY\""
9          + "},"
10          + "\"mchid\":\"1230000109\","
11          + "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
12          + "\"notify_url\":\"https://www.weixin.qq.com/wxpay/pay.php\","
13          + "\"out_trade_no\":\"1217752501201407033233368018\","
14          + "\"goods_tag\":\"WXG\","
15          + "\"appid\":\"wxd678efh567hg6787\","
16          + "\"attach\":\"自定义数据说明\","
17          + "\"detail\": {"
18          + "\"invoice_id\":\"wx123\","
19          + "\"goods_detail\": ["
20          + "{"
21          + "\"goods_name\":\"iPhoneX 256G\","
22          + "\"wechatpay_goods_id\":\"1001\","
23          + "\"quantity\":1,"
24          + "\"merchant_goods_id\":\"商品编码\","
25          + "\"unit_price\":828800"
26          + "},"
27          + "{"
28          + "\"goods_name\":\"iPhoneX 256G\","
29          + "\"wechatpay_goods_id\":\"1001\","
30          + "\"quantity\":1,"
31          + "\"merchant_goods_id\":\"商品编码\","
32          + "\"unit_price\":828800"
33          + "}"
34          + "],"
35          + "\"cost_price\":608800"
36          + "},"
37          + "\"scene_info\": {"
38          + "\"store_info\": {"
39          + "\"address\":\"广东省深圳市南山区科技中一道10000号\","
40          + "\"area_code\":\"440305\","
41          + "\"name\":\"腾讯大厦分店\","
42          + "\"id\":\"0001\""
43          + "},"
44          + "\"device_id\":\"013467007045764\","
45          + "\"payer_client_ip\":\"14.23.150.211\""
46          + "}"
47          + "}";
48  StringEntity entity = new StringEntity(reqdata,"utf-8");
49  entity.setContentType("application/json");
50  httpPost.setEntity(entity);
51  httpPost.setHeader("Accept", "application/json");
52  //完成签名并执行请求
53  CloseableHttpResponse response = httpClient.execute(httpPost);
54  try {
55      int statusCode = response.getStatusLine().getStatusCode();
56      if (statusCode == 200) { //处理成功
57          System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
58      } else if (statusCode == 204) { //处理成功,无返回Body
59          System.out.println("success");
60      } else {
61          System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
62          throw new IOException("request failed");
63      }
64  } finally {
65      response.close();
66  }
67}

PHP代码示例:

1try {
2$resp = $client->request(
3    'POST',
4    'https://api.mch.weixin.qq.com/v3/pay/transactions/native', //请求URL
5    [
6        // JSON请求体
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            "out_trade_no" => "1217752501201407033233368018", 
17            "goods_tag" => "WXG", 
18            "appid" => "wxd678efh567hg6787", 
19            "attach" => "自定义数据说明", 
20            "detail" => [
21                "invoice_id" => "wx123", 
22                "goods_detail" => [
23                    [
24                        "goods_name" => "iPhoneX 256G", 
25                        "wechatpay_goods_id" => "1001", 
26                        "quantity" => 1, 
27                        "merchant_goods_id" => "商品编码", 
28                        "unit_price" => 828800, 
29                    ],
30                    [
31                        "goods_name" => "iPhoneX 256G", 
32                        "wechatpay_goods_id" => "1001", 
33                        "quantity" => 1, 
34                        "merchant_goods_id" => "商品编码", 
35                        "unit_price" => 828800, 
36                    ],
37                ],
38                "cost_price" => 608800, 
39            ],
40            "scene_info" => [
41                "store_info" => [
42                    "address" => "广东省深圳市南山区科技中一道10000号", 
43                    "area_code" => "440305", 
44                    "name" => "腾讯大厦分店", 
45                    "id" => "0001", 
46                ],
47                "device_id" => "013467007045764", 
48                "payer_client_ip" => "14.23.150.211", 
49            ]
50        ],
51        'headers' => [ 'Accept' => 'application/json' ]
52    ]
53);
54$statusCode = $resp->getStatusCode();
55if ($statusCode == 200) { //处理成功
56    echo "success,return body = " . $resp->getBody()->getContents()."\n";
57} else if ($statusCode == 204) { //处理成功,无返回Body
58    echo "success";
59}
60} catch (RequestException $e) {
61// 进行错误处理
62echo $e->getMessage()."\n";
63if ($e->hasResponse()) {
64    echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
65}
66return;
67  
68}

重要入参说明:

  • out_trade_no: 商户系统内部订单号,只能是数字、大小写字母_-*且在同一个商户号下唯一。

  • description: 商品描述。

  • notify_url: 支付回调通知URL,该地址必须为直接可访问的URL,不允许携带查询串。

  • total: 订单总金额,单位为分。

更多参数、响应详情及错误码请参见Native下单接口文档。

3.2.2. 【客户端】生成支付二维码

步骤说明: 通过Native下单API成功获取支付二维码链接(code_url)后,需要在前端(PC网页或POS机具)生成二维码供用户扫描支付。

注意

  • code_url对应链接格式:weixin://pay.weixin.qq.com/bizpayurl/up?pr=NwY5Mz9&groupid=00。请商户调用第三方库将code_url生成二维码图片。该模式链接较短,生成的二维码打印到结账小票上的识别率较高。

例如,weixin://pay.weixin.qq.com/bizpayurl/up?pr=NwY5Mz9&groupid=00 生成二维码见下图


  • 更多二维码的相关背景知识可参考

https://www.qrcode.com/zh/index.html

3.2.3. 【服务端】接收支付结果通知

步骤说明: 当用户完成支付,微信会把相关支付结果将通过异步回调的方式通知商户,商户需要接收处理,并按文档规范返回应答

注意

  • 支付结果通知是以POST 方法访问商户设置的通知URL,通知的数据以JSON 格式通过请求主体(BODY)传输。通知的数据包括了加密的支付结果详情。

  • ature。商户应当验证签名,以确认请求来自微信,而不是其他的第三方。签名验证的算法请参考 《微信支付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. 【服务端】查询订单

步骤说明: 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知时,商户可通过查询订单接口核实订单支付状态

注意

需要调用查询接口的情况:

  • 当商户后台、网络、服务器等出现异常,商户系统最终未接收到支付通知。

  • 调用支付接口后,返回系统错误或未知交易状态情况。

  • 调用付款码支付API,返回USERPAYING的状态。

  • 调用关单或撤销接口API之前,需确认支付状态。

JAVA代码示例:

1public void QueryOrder() throws Exception {
2   
3  //请求URL
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}

PHP代码示例:

1try {
2    $resp = $client->request(
3        'GET',
4        'https://api.mch.weixin.qq.com/v3/pay/transactions/id/1217752501201407033233368018?mchid=1230000109', //请求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.5. 【服务端】关闭订单

步骤说明: 当商户订单支付失败需要生成新单号重新发起支付,要对原订单号调用关单,避免重复支付;系统下单后,用户支付超时,系统退出不再受理,避免用户继续,请调用关单接口

注意

  • 关单没有时间限制,建议在订单生成后间隔几分钟(最短5分钟)再调用关单接口,避免出现订单状态同步不及时导致关单失败。

  • 已支付成功的订单不能关闭。

JAVA代码示例:

1public void CloseOrder() throws Exception {
2     
3    //请求URL
4    HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/sdkphp12345678920201028112429/close");
5    //请求body参数
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  }

PHP代码示例:

1try {
2    $resp = $client->request(
3        'POST',
4        'https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}/close', //请求URL
5        [
6            // JSON请求体
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) { //处理成功,无返回Body
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  }

更多参数、响应详情及错误码请参见 关闭订单通知API接口文档。

3.2.6. 【服务端】申请交易账单

步骤说明: 微信支付按天提供交易账单文件,商户可以通过该接口获取账单文件的下载地址。

JAVA代码示例:

1public void TradeBill() throws Exception {
2   
3  //请求URL
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}

PHP代码示例:

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点后再获取。

JAVA代码示例:

1public void DownloadUrl(String download_url) throws Exception{
2      PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
3       
4      //初始化httpClient
5      //该接口无需进行签名验证、通过withValidator((response) -> true)实现
6      httpClient =  WechatPayHttpClientBuilder.create().withMerchant(mchId, mchSerialNo, merchantPrivateKey).withValidator((response) -> true).build();
7       
8      //请求URL
9      //账单文件的下载地址的有效时间为30s
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    }

PHP代码示例:

1try {
2    $resp = $client->request(
3        'GET',
4        'https://api.mch.weixin.qq.com/v3/billdownload/file?token=xx', //请求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}

更多参数、响应详情及错误码请参见 下载账单接口文档。

4. 常见问题

Q:微信native支付生成的二维码有有效期吗?

A:一个二维码的有效期是根据Native下单接口返回的code_url决定,code_url的有效期是2小时。

Q:native支付扫码后提示:支付失败,该商户暂不支持通过长按识别二维码完成支付

A:微信支付已经不支持通过长按识别二维码的方式或通过相册识别二维码的方式完成支付。