微信小程序支付

當(dāng)下,微信小程序十分火爆,現(xiàn)在無論是購(gòu)物還是生活服務(wù),都是推薦你使用微信小程序,主要是它無需下載安裝就可以使用,讓手機(jī)變得非常清爽,給用戶也帶來很大的方便之處。

今天給大家分享的是,微信小程序 API v3 支付。

目錄

1、效果演示
2、微信小程序支付官方文檔
3、生成密鑰、生成證書
4、如何生成簽名
5、微信小程序下單接口
6、微信小程序商戶訂單查詢接口

一、效果演示

步驟1:用戶選擇好商品,提交訂單,服務(wù)端下預(yù)訂單

prepay.png

步驟2:小程序端拉起支付控件,并完成支付

pay.png

步驟3:查詢支付結(jié)果

pay-query.png

步驟4:完成支付,顯示支付結(jié)果

pay-result.png

二、微信小程序支付官方文檔

三、生成密碼,生成證書

看 【2.1】文檔,生成 API v3 密鑰 和 API 證書。

注意:

1、生成證書,需要配合客戶端軟件(WXCertUtil)生成。
2、附件中的三份文件(證書pkcs12格式、證書pem格式、證書密鑰pem格式)。建議讀一讀 證書使用說明.txt。

四、生成簽名

這一步是相當(dāng)復(fù)雜,我們一定要把【2.2】文檔多讀幾遍。

先說結(jié)論,這一步主要是構(gòu)建下面這樣一個(gè)東西:

Authorization: 認(rèn)證類型 簽名信息

認(rèn)證類型是 WECHATPAY2-SHA256-RSA2048。

簽名信息:

  • 發(fā)起請(qǐng)求的商戶(包括直連商戶、服務(wù)商或渠道商)的商戶號(hào)mchid
  • 商戶API證書序列號(hào)serial_no,用于聲明所使用的證書
  • 請(qǐng)求隨機(jī)串nonce_str
  • 時(shí)間戳timestamp
  • 簽名值signature

商戶號(hào) mchid,這個(gè)拿到了。
商戶API證書序列號(hào)serial_no,這個(gè)有兩種方式,一是從證書(p12)文件中獲取,二是在后臺(tái)查看:【API安全 > 申請(qǐng)API證書 > 點(diǎn)擊“管理證書” > “證書序列號(hào)”】

下面就來重點(diǎn)說一下這個(gè)簽名了。

格式:

HTTP請(qǐng)求方法\n
URL\n
請(qǐng)求時(shí)間戳\n
請(qǐng)求隨機(jī)串\n
請(qǐng)求報(bào)文主體\n

HTTP請(qǐng)求方法,每個(gè)接口都不一樣,比如下單接口是POST,查詢接口是GET。

URL,這是是除去域名,后面的全部。官方文檔是這樣說的:

第二步,獲取請(qǐng)求的絕對(duì)URL,并去除域名部分得到參與簽名的URL。如果請(qǐng)求中有查詢參數(shù),URL末尾應(yīng)附加有'?'和對(duì)應(yīng)的查詢字符串。

請(qǐng)求時(shí)間戳,這個(gè)是秒數(shù)。

接口報(bào)文體,官網(wǎng)也說的比較詳細(xì),

第五步,獲取請(qǐng)求中的請(qǐng)求報(bào)文主體(request body)。

請(qǐng)求方法為GET時(shí),報(bào)文主體為空。
當(dāng)請(qǐng)求方法為POST或PUT時(shí),請(qǐng)使用真實(shí)發(fā)送的JSON報(bào)文。
圖片上傳API,請(qǐng)使用meta對(duì)應(yīng)的JSON報(bào)文。
對(duì)于下載證書的接口來說,請(qǐng)求報(bào)文主體是一個(gè)空串。

綜合起來,就是這樣的,舉個(gè)例子:

GET\n 
/v3/certificates\n 
1554208460\n 
593BEC0C930BF1AFEB40B4A08C8FB242\n 
\n

下一個(gè)難點(diǎn)來了,計(jì)算簽名。

簽名方式:使用商戶私鑰對(duì)待簽名串進(jìn)行SHA256 with RSA簽名,并對(duì)簽名結(jié)果進(jìn)行Base64編碼得到簽名值。

簡(jiǎn)單來說,
1:就是先要讀到商戶私鑰,
2:然后使用私鑰進(jìn)行SHA256 with RSA簽名,
3:Base64編碼

到這里,就算得到 Authorization 的值了。

五、微信小程序下單接口

下面我們就以小程序下單接口來做說明。

首先,構(gòu)造下單的參數(shù)

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);

這里需要說明的,過期時(shí)間(time_expire)格式為:yyyy-MM-DDTHH:mm:ss+TIMEZONE

應(yīng)該如何賦值呢?

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);

我們對(duì)請(qǐng)求參數(shù)進(jìn)行 json 格式轉(zhuǎn)換:

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();
        // 證書的序列號(hào) 也有用
        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);
    }
}

獲取到證書,就可以用私鑰進(jìn)行簽名

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);
    }
}

然后進(jìn)行拼接:

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工具發(fā)起請(qǐng)求:

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方式請(qǐng)求微信 API v3 接口

六、微信小程序商戶訂單查詢接口

支付查詢是GET方式,如果你沒有仔細(xì)看第【四】點(diǎn),可能會(huì)遇到一些問題

我們先構(gòu)造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();

簽名時(shí),獲取url需要注意,參數(shù)也需要帶上

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);
    }
}

請(qǐng)求方法為GET時(shí),報(bào)文主體為空。

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);
    }
}

小程序調(diào)起支付

最后,補(bǔ)充一下,在小程序端如何拉起支付:

文檔:

小程序調(diào)起支付,需要 appId,也需要簽名。

AppId 這種一般都會(huì)配到后臺(tái),所以,建議簽名放到后臺(tái),如下:

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);
    }
}

只需要將簽名號(hào)的參數(shù)返回給小程序就好了。

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);
    }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容