springboot项目实现微信扫码支付
我们需要有 appid(APPID)、商户号(MCH_ID)、密钥。
这三个都是在微信平台注册的,工作中做的时候公司会提供,不用担心。注册流程就不叭叭了,自行解决~~~
来吧, 展示
首先去微信公众平台下载SDK和DEMO ,点击下载地址
https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=11_1
下载解压后把这些文件拷贝到自己项目中,后面需要用
// appid
private static final String APPID = "*********";
// 商户号
private static final String MCH_ID = "*********";
// 密钥
private static final String PARTNERKEY = "********";
// 回调地址
private static final String NOTIFYURL = "*********";
// 统一下单接口
private static final String URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
@GetMapping("/weiXinPay")
public String weiXinPay(String out_trade_no, String total_fee, String good_id){
HashMap<String, String> map = new HashMap<>();
// APPID
map.put("appid", APPID);
// 商户号
map.put("mch_id", MCH_ID);
// 随机字符串
map.put("nonce_str", WXPayUtil.generateNonceStr());
// 商品描述
map.put("body", "测试支付");
// 商户订单号
map.put("out_trade_no",out_trade_no);
// 标价金额
map.put("total_fee",total_fee);
// 终端IP
map.put("spbill_create_ip","127.0.0.1");
// 通知地址(回调地址)
map.put("notify_url",NOTIFYURL);
// 交易类型
map.put("trade_type","NATIVE");
// 商品ID
map.put("product_id",good_id);
try {
// 将参数转成xml // PARTNERKEY: 密钥
String signedXml = WXPayUtil.generateSignedXml(map, PARTNERKEY);
// 用的hutool工具类, 相当于https请求 // URL: 统一下单接口
String post = HttpUtil.post(URL, signedXml);
// 将返回值转成map
Map<String, String> toMap = WXPayUtil.xmlToMap(post);
// 生成二维码的url
String code_url = toMap.get("code_url");
return code_url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
上面代码可以拿到微信返回给我们生成二维码的URL,直接拿到前端展示就ok。
说明一点, 通知地址(回调地址) notify_url 必须是外网能访问到的, 不然微信调用不到的。
// 回调地址调用的方法
public void notifyUrl(HttpServletRequest request){
try {
InputStream inStream = request.getInputStream();
BufferedReader in = null;
String result = "";
in = new BufferedReader(
new InputStreamReader(inStream));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
//===============下面根据自己的需求写逻辑===========================
} catch (IOException e) {
e.printStackTrace();
}
}
回调方法中 result 可以得到一个xml , 我们根据自己的需求拿到想要的值即可。
展示完毕, 欢迎程序员们验收~~~
以上仅是自己写的一个demo, 需要的可以参考下,有意见欢迎评论区留言