本篇內(nèi)容介紹了“如何使用API v3接口”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
創(chuàng)新互聯(lián)建站專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計(jì)制作、做網(wǎng)站、奉賢網(wǎng)絡(luò)推廣、微信小程序定制開(kāi)發(fā)、奉賢網(wǎng)絡(luò)營(yíng)銷、奉賢企業(yè)策劃、奉賢品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)建站為所有大學(xué)生創(chuàng)業(yè)者提供奉賢建站搭建服務(wù),24小時(shí)服務(wù)熱線:18980820575,官方網(wǎng)址:www.cdcxhl.com
jdk:1.8 wechatpay-apache-httpclient:0.2.2
筆者以微信小程序支付接口為例展開(kāi)說(shuō)明,至于小程序注冊(cè)、認(rèn)證、微信支付注冊(cè)本文概不說(shuō)明。
登錄微信支付后臺(tái),進(jìn)入賬戶中心,API安全設(shè)置,如下圖 申請(qǐng)商戶證書(shū),如下圖 點(diǎn)擊“申請(qǐng)證書(shū)”按鈕后,彈出生成API證書(shū)申請(qǐng)框,如下圖 根據(jù)提示下載證書(shū)工具,當(dāng)前頁(yè)面不要關(guān)閉,下載證書(shū)工具后打開(kāi),如下圖
點(diǎn)擊“申請(qǐng)證書(shū)”按鈕后,進(jìn)入填寫商戶信息界面,商戶信息經(jīng)測(cè)試是自動(dòng)填充的,如下圖 點(diǎn)擊“下一步”,進(jìn)入復(fù)制請(qǐng)求串界面,如下圖 將證書(shū)請(qǐng)求串進(jìn)行復(fù)制,復(fù)制后回到上述微信支付后臺(tái)申請(qǐng)API證書(shū)頁(yè)面,將請(qǐng)求串進(jìn)行復(fù)制,經(jīng)測(cè)試自動(dòng)幫你完成復(fù)制粘貼,請(qǐng)求串復(fù)制后點(diǎn)擊“下一步”操作,進(jìn)入復(fù)制證書(shū)串步驟,如下圖 點(diǎn)擊“復(fù)制證書(shū)串”,將復(fù)制的證書(shū)串粘貼至證書(shū)工具中,如下圖 點(diǎn)擊“下一步”完成商戶證書(shū)的申請(qǐng),如下圖 商戶API證書(shū)已生成,點(diǎn)擊查看證書(shū)文件夾,即可查看證書(shū)信息,如下圖 在微信支付商戶后臺(tái)可獲取商戶API證書(shū)序列號(hào)及證書(shū)有效期,如下圖
設(shè)置API密鑰,現(xiàn)階段由于微信支付原先老接口并未全部升級(jí)至API v3版,涉及新老接口共存的情況,所以API密鑰及APIV3密鑰都需進(jìn)行設(shè)置,新老接口請(qǐng)查閱微信支付開(kāi)發(fā)文檔 API v2老版本密鑰設(shè)置 API v3密鑰設(shè)置
微信平臺(tái)證書(shū)下載,查閱開(kāi)發(fā)文檔,微信已提供證書(shū)下載工具 如下圖
關(guān)注本文末尾微信公眾號(hào),回復(fù)“666”獲取常用開(kāi)發(fā)工具包,內(nèi)含常用開(kāi)發(fā)組件及微信證書(shū)下載工具,節(jié)省下載時(shí)間。
下載平臺(tái)證書(shū)至本地,執(zhí)行命令
必需參數(shù)有: 商戶的私鑰文件,即 -f (商戶API證書(shū)中apiclient_key.pem文件路徑) 證書(shū)解密的密鑰,即 -k (微信支付后臺(tái)設(shè)置的APIv3密鑰) 商戶號(hào),即 -m (微信支付商戶號(hào),可在微信支付后臺(tái)查閱) 保存證書(shū)的路徑,即 -o (微信平臺(tái)證書(shū)保存路徑) 商戶證書(shū)的序列號(hào),即 -s (商戶API證書(shū),即上述第一步申請(qǐng)商戶API證書(shū)序列號(hào)) 非必需參數(shù)有: 微信支付證書(shū),用于驗(yàn)簽,即 -c 完整命令如下 java -jar CertificateDownloader-1.1.jar -k ${apiV3key} -m ${mchId} -f ${mchPrivateKeyFilePath} -s ${mchSerialNo} -o ${outputFilePath}
至此基礎(chǔ)配置參數(shù)已準(zhǔn)備就緒
在請(qǐng)求接口之前先了解下接口中一些參數(shù)概念,首次接觸最容易搞混的就是商戶API證書(shū)和平臺(tái)證書(shū),如下圖
以往老吐槽微信支付接口文檔不友好,沒(méi)有sdk,現(xiàn)在API v3版本給你提供了一個(gè)客戶端,這點(diǎn)還是可以點(diǎn)贊的,對(duì)于開(kāi)發(fā)人員來(lái)說(shuō),demo代碼直接拿過(guò)來(lái),更改下配置參數(shù)就可以跑通,那簡(jiǎn)直是對(duì)程序員莫大的關(guān)懷,這方面阿里相對(duì)做的比較好
talk is cheap, show me the code
以post請(qǐng)求方式說(shuō)明,get請(qǐng)求類似
private static String basePostRequest(String requestUrl,String requestJson) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; try { PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8"))); X509Certificate wechatpayCertificate = PemUtil.loadCertificate(new ByteArrayInputStream(certificate.getBytes("utf-8"))); ArrayListlistCertificates = new ArrayList<>(); listCertificates.add(wechatpayCertificate); httpClient = WechatPayHttpClientBuilder.create() .withMerchant(mchId, mchSerialNo, merchantPrivateKey) .withWechatpay(listCertificates) .build(); HttpPost httpPost = new HttpPost(requestUrl); // NOTE: 建議指定charset=utf-8。低于4.4.6版本的HttpCore,不能正確的設(shè)置字符集,可能導(dǎo)致簽名錯(cuò)誤 StringEntity reqEntity = new StringEntity(requestJson, ContentType.create("application/json", "utf-8")); httpPost.setEntity(reqEntity); httpPost.addHeader("Accept", "application/json"); response = httpClient.execute(httpPost); entity = response.getEntity(); return EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); } finally { // 關(guān)閉流 } return null; }
方法中涉及參數(shù)說(shuō)明
PemUtil.java類為com.wechat.pay.contrib.apache.httpclient.util.PemUtil
請(qǐng)求簽名及應(yīng)答簽名校驗(yàn)該客戶端均已幫你處理好,心中對(duì)微信支付開(kāi)發(fā)文檔有了一點(diǎn)點(diǎn)好感。根據(jù)具體接口方法傳入接口地址及相應(yīng)接口參數(shù)JSON數(shù)據(jù)即可完成接口聯(lián)調(diào)測(cè)試。
以小程序調(diào)起支付接口為例,簡(jiǎn)單說(shuō)明參數(shù)簽名方式,先看下文檔中簽名是怎么說(shuō)的,如下圖
/** * 微信支付-前端喚起支付參數(shù) * prepay_id=wx201410272009395522657a690389285100 * @param packageStr 預(yù)下單接口返回?cái)?shù)據(jù) 預(yù)支付交易會(huì)話標(biāo)識(shí) prepay_id * @return */ public static MapcreatePayParams(String packageStr) { Map resultMap = new HashMap<>(); String nonceStr = StringUtil.getUUID(); Long timestamp = System.currentTimeMillis() / 1000; String message = buildMessage(timestamp, nonceStr, packageStr); String signature = null; try { signature = sign(message.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } resultMap.put("appId", appId); resultMap.put("timeStamp",timestamp.toString()); resultMap.put("nonceStr",nonceStr); resultMap.put("package",packageStr); resultMap.put("signType","RSA"); resultMap.put("paySign",signature); return resultMap; } /** * 微信支付-前端喚起支付參數(shù)-簽名 * @param message 簽名數(shù)據(jù) * @return */ public static String sign(byte[] message) { try{ Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(getPrivateKey(keyFilePath)); sign.update(message); return Base64.getEncoder().encodeToString(sign.sign()); } catch(Exception e) { e.printStackTrace(); } return null; } /** * 微信支付-前端喚起支付參數(shù)-構(gòu)建簽名參數(shù) * @param nonceStr 簽名數(shù)據(jù) * @return */ public static String buildMessage(long timestamp, String nonceStr, String packageStr) { return appId + "\n" + timestamp + "\n" + nonceStr + "\n" + packageStr + "\n"; } /** * 微信支付-前端喚起支付參數(shù)-獲取商戶私鑰 * * @param filename 私鑰文件路徑 (required) * @return 私鑰對(duì)象 */ public static PrivateKey getPrivateKey(String filename) throws IOException { String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8"); try { String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replaceAll("\\s+", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate( new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("當(dāng)前Java環(huán)境不支持RSA", e); } catch (InvalidKeySpecException e) { throw new RuntimeException("無(wú)效的密鑰格式"); } }
方法中涉及參數(shù)說(shuō)明
回調(diào)通知涉及驗(yàn)簽及解密
回調(diào)數(shù)據(jù)獲取
String body = request.getReader().lines().collect(Collectors.joining());
驗(yàn)簽
/** * 回調(diào)驗(yàn)簽 * https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay4_1.shtml * @param wechatpaySerial 回調(diào)head頭部 * @param wechatpaySignature 回調(diào)head頭部 * @param wechatpayTimestamp 回調(diào)head頭部 * @param wechatpayNonce 回調(diào)head頭部 * @param body 請(qǐng)求數(shù)據(jù) * @return */ public static boolean responseSignVerify(String wechatpaySerial, String wechatpaySignature, String wechatpayTimestamp, String wechatpayNonce, String body) { FileInputStream fileInputStream = null; try { String signatureStr = buildMessage(wechatpayTimestamp, wechatpayNonce, body); Signature signer = Signature.getInstance("SHA256withRSA"); fileInputStream = new FileInputStream(weixin_platform_cert_path); X509Certificate receivedCertificate = loadCertificate(fileInputStream); signer.initVerify(receivedCertificate); signer.update(signatureStr.getBytes(StandardCharsets.UTF_8)); return signer.verify(Base64.getDecoder().decode(wechatpaySignature)); } catch (Exception e ) { e.printStackTrace(); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } /** * 回調(diào)驗(yàn)簽-加載微信平臺(tái)證書(shū) * @param inputStream * @return */ public static X509Certificate loadCertificate(InputStream inputStream) { try { CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); cert.checkValidity(); return cert; } catch (CertificateExpiredException e) { throw new RuntimeException("證書(shū)已過(guò)期", e); } catch (CertificateNotYetValidException e) { throw new RuntimeException("證書(shū)尚未生效", e); } catch (CertificateException e) { throw new RuntimeException("無(wú)效的證書(shū)", e); } } /** * 回調(diào)驗(yàn)簽-構(gòu)建簽名數(shù)據(jù) * @param * @return */ public static String buildMessage(String wechatpayTimestamp, String wechatpayNonce, String body) { return wechatpayTimestamp + "\n" + wechatpayNonce + "\n" + body + "\n"; }
方法中涉及參數(shù)說(shuō)明
解密
// https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtml AesUtil wxAesUtil = new AesUtil(apiv3.getBytes()); String jsonStr = wxAesUtil.decryptToString("associated_data".getBytes(),"nonce".getBytes(),"ciphertext");
方法中涉及參數(shù)說(shuō)明
“如何使用API v3接口”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!