微信H5支付開發(maven倉庫版)
阿新 • • 發佈:2018-12-05
官方文件:https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_1
開發之前確認開通了H5支付功能
一、安裝微信sdk
二、建立config類
package com.xiuchefang.config; import com.github.wxpay.sdk.WXPayConfig; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream;/** * Created by 15117 on 2018/11/27. */ public class XCFWXPayConfig implements WXPayConfig { private byte[] certData; public XCFWXPayConfig() throws Exception { String certPath = "***"; File file = new File(certPath); InputStream stream = new FileInputStream(file);this.certData = new byte[(int)file.length()]; stream.read(this.certData); stream.close(); } @Override public String getAppID() { return "***"; } @Override public String getMchID() { return "***"; } @Override public String getKey() {return "***"; } @Override public InputStream getCertStream() { return new ByteArrayInputStream(this.certData); } @Override public int getHttpConnectTimeoutMs() { return 8000; } @Override public int getHttpReadTimeoutMs() { return 10000; } }
三、呼叫微信支付介面下單
使用者ip獲取
(1)微信使用者ip獲取指引:https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_5
(2)程式碼獲取ip指引:https://www.cnblogs.com/SongG-blogs/p/9083512.html
*注意抽象方法作用域
支付簽名錯誤排產方法
1、確認公眾號的appSecret和商戶號的API金鑰沒有搞混。
2、重置商戶API金鑰(注意專案中記得更新api金鑰)
3、確認公眾號授權的域名和目錄是正確的
針對redirect_url處理
前臺進行頁面跳轉
支付成功之後處理,微信請求notify_url
@Override public synchronized void payNotify(HttpServletRequest request, HttpServletResponse response) { System.out.println("微信支付回撥"); try { String resXml = ""; XCFWXPayConfig xcfwxPayConfig = new XCFWXPayConfig(); WXPay wxPay = new WXPay(xcfwxPayConfig); InputStream inStream = request.getInputStream(); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); String result = new String(outSteam.toByteArray(), "utf-8");// 獲取微信呼叫我們notify_url的返回資訊 Map<String, String> map = WXPayUtil.xmlToMap(result); if (wxPay.isPayResultNotifySignatureValid(map)) { System.out.println("微信支付-簽名驗證成功"); resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; //業務處理開始 //業務處理結束 } BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); out.write(resXml.getBytes()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
其它常見錯誤解決辦法(https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4)