官方文档: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)