當下,微信小程序十分火爆,現在無論是購物還是生活服務,都是推薦你使用微信小程序,主要是它無需下載安裝就可以使用,讓手機變得非常清爽,給用戶也帶來很大的方便之處。
今天給大家分享的是,微信小程序 API v3 支付。
目錄
1、效果演示
2、微信小程序支付官方文檔
3、生成密鑰、生成證書
4、如何生成簽名
5、微信小程序下單接口
6、微信小程序商戶訂單查詢接口
一、效果演示
步驟1:用戶選擇好商品,提交訂單,服務端下預訂單
步驟2:小程序端拉起支付控件,并完成支付
步驟3:查詢支付結果
步驟4:完成支付,顯示支付結果
二、微信小程序支付官方文檔
- 2.1 API v3 密鑰
- 2.2 如何生成請求簽名
- 2.3 小程序下單接口
- 2.4 商戶訂單號查詢訂單接口
三、生成密碼,生成證書
看 【2.1】文檔,生成 API v3 密鑰 和 API 證書。
注意:
1、生成證書,需要配合客戶端軟件(WXCertUtil)生成。
2、附件中的三份文件(證書pkcs12格式、證書pem格式、證書密鑰pem格式)。建議讀一讀 證書使用說明.txt
。
四、生成簽名
這一步是相當復雜,我們一定要把【2.2】文檔多讀幾遍。
先說結論,這一步主要是構建下面這樣一個東西:
Authorization: 認證類型 簽名信息
認證類型是 WECHATPAY2-SHA256-RSA2048
。
簽名信息:
- 發起請求的商戶(包括直連商戶、服務商或渠道商)的商戶號mchid
- 商戶API證書序列號serial_no,用于聲明所使用的證書
- 請求隨機串nonce_str
- 時間戳timestamp
- 簽名值signature
商戶號 mchid,這個拿到了。
商戶API證書序列號serial_no,這個有兩種方式,一是從證書(p12)文件中獲取,二是在后臺查看:【API安全 > 申請API證書 > 點擊“管理證書” > “證書序列號”】
下面就來重點說一下這個簽名了。
格式:
HTTP請求方法\n
URL\n
請求時間戳\n
請求隨機串\n
請求報文主體\n
HTTP請求方法,每個接口都不一樣,比如下單接口是POST,查詢接口是GET。
URL,這是是除去域名,后面的全部。官方文檔是這樣說的:
第二步,獲取請求的絕對URL,并去除域名部分得到參與簽名的URL。如果請求中有查詢參數,URL末尾應附加有'?'和對應的查詢字符串。
請求時間戳,這個是秒數。
接口報文體,官網也說的比較詳細,
第五步,獲取請求中的請求報文主體(request body)。
請求方法為GET時,報文主體為空。
當請求方法為POST或PUT時,請使用真實發送的JSON報文。
圖片上傳API,請使用meta對應的JSON報文。
對于下載證書的接口來說,請求報文主體是一個空串。
綜合起來,就是這樣的,舉個例子:
GET\n
/v3/certificates\n
1554208460\n
593BEC0C930BF1AFEB40B4A08C8FB242\n
\n
下一個難點來了,計算簽名。
簽名方式:使用商戶私鑰對待簽名串進行SHA256 with RSA簽名,并對簽名結果進行Base64編碼得到簽名值。
簡單來說,
1:就是先要讀到商戶私鑰,
2:然后使用私鑰進行SHA256 with RSA簽名,
3:Base64編碼
到這里,就算得到 Authorization 的值了。
五、微信小程序下單接口
下面我們就以小程序下單接口來做說明。
首先,構造下單的參數
WechatAppletPayRequest request = new WechatAppletPayRequest();
request.setAppId(merchantConfigBo.getAppId());
request.setMchId(merchantConfigBo.getMchId());
request.setDescription("演示訂單");
request.setOutTradeNo(orderId);
request.setNotifyUrl("https://examine.com/pay/notify");
request.setAmount(amount);
request.setPayer(payer);
這里需要說明的,過期時間(time_expire)格式為:yyyy-MM-DDTHH:mm:ss+TIMEZONE
。
應該如何賦值呢?
LocalDateTime timeExpire = LocalDateTime.now().plusMinutes(30);
OffsetDateTime offsetDateTime = OffsetDateTime.of(timeExpire, ZoneOffset.of("+8"));
String timeExpireStr = offsetDateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX"));
request.setTimeExpire(timeExpireStr);
我們對請求參數進行 json 格式轉換:
String param = JsonUtils.convertString(request);
獲取證書:
public KeyPair createPKCS12(String keyPath, String keyAlias, String keyPass) {
try {
char[] pem = keyPass.toCharArray();
InputStream inputStream = new FileInputStream(keyPath);
synchronized (lock) {
if (store == null) {
synchronized (lock) {
store = KeyStore.getInstance("PKCS12");
store.load(inputStream, pem);
}
}
}
X509Certificate certificate = (X509Certificate) store.getCertificate(keyAlias);
certificate.checkValidity();
// 證書的序列號 也有用
String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase();
// 證書的 公鑰
PublicKey publicKey = certificate.getPublicKey();
// 證書的私鑰
PrivateKey storeKey = (PrivateKey) store.getKey(keyAlias, pem);
return new KeyPair(publicKey, storeKey);
} catch (Exception e) {
throw new IllegalStateException("Cannot load keys from store: " + keyPath, e);
}
}
獲取到證書,就可以用私鑰進行簽名
public static String sign(String url,
String method,
long timestamp,
String nonceStr,
String body,
KeyPair keyPair) {
try {
String canonicalUrl = getCanonicalUrl(url);
String signatureStr = Stream.of(method, canonicalUrl, String.valueOf(timestamp), nonceStr, body)
.collect(Collectors.joining("\n", "", "\n"));
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(keyPair.getPrivate());
sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(sign.sign());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
然后進行拼接:
private String getToken(String mchId, String nonceStr, long timestamp, String serialNo, String signature) {
final String TOKEN_PATTERN = "mchid=\"%s\",nonce_str=\"%s\",timestamp=\"%d\",serial_no=\"%s\",signature=\"%s\"";
// 生成token
return String.format(TOKEN_PATTERN,
mchId,
nonceStr, timestamp, serialNo, signature);
}
最后就是用http工具發起請求:
private String httpPost(String url, String token, String param) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept", "application/json");
headerMap.put("Content-Type", "application/json");
headerMap.put("Authorization", "WECHATPAY2-SHA256-RSA2048 " + token);
Request request = new Request();
request.setUrl(url);
request.setParam(param);
request.setMethod(Request.Method.POST);
request.setUtil(Request.Util.OkHttp);
request.setParamFormat(Request.ParamFormat.JSON);
Request.Option option = new Request.Option();
option.setHeaders(headerMap);
try {
return HttpUtils.execute(request, option);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
以上就是post方式請求微信 API v3 接口
六、微信小程序商戶訂單查詢接口
支付查詢是GET方式,如果你沒有仔細看第【四】點,可能會遇到一些問題
我們先構造url:
String payQueryUrl = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/%s";
String url = String.format(payQueryUrl, dto.getOutTradeNo());
url += "?mchid=" + merchantConfigBo.getMchId();
簽名時,獲取url需要注意,參數也需要帶上
public static String getCanonicalUrl(String url) {
try {
URL u = new URL(url);
String query = u.getQuery();
String result = u.getPath();
if (StringUtils.hasText(query)) {
result = result + "?" + query;
}
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
請求方法為GET時,報文主體為空。
private String httpGet(String url, String token) {
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept", "application/json");
headerMap.put("Content-Type", "application/json");
headerMap.put("Authorization", "WECHATPAY2-SHA256-RSA2048 " + token);
Request request = new Request();
request.setUrl(url);
request.setMethod(Request.Method.GET);
request.setUtil(Request.Util.OkHttp);
Request.Option option = new Request.Option();
option.setHeaders(headerMap);
try {
return HttpUtils.execute(request, option);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
小程序調起支付
最后,補充一下,在小程序端如何拉起支付:
文檔:
小程序調起支付,需要 appId
,也需要簽名。
AppId 這種一般都會配到后臺,所以,建議簽名放到后臺,如下:
public static String paySign(String appid, String packageStr, long timestamp, String nonceStr, KeyPair keyPair) {
try {
String message = appid + "\n"
+ timestamp + "\n"
+ nonceStr + "\n"
+ packageStr + "\n";
//簽名方式
Signature sign = Signature.getInstance("SHA256withRSA");
sign.initSign(keyPair.getPrivate());
sign.update(message.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(sign.sign());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
只需要將簽名號的參數返回給小程序就好了。
wx.requestPayment({
timeStamp: payVo.timeStamp,
nonceStr: payVo.nonceStr,
package: payVo.packageStr,
signType: 'RSA',
paySign: payVo.paySign,
success (res: any) {
wx.navigateTo({
url: `/pages/cashier/index?id=${id}`
})
},
fail (res) {
console.error(res);
}
})