JAVA-微信支付开发

怕忘记,记录一下。

首先。先看一边官方文档。https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1

然后。微信公众号设置支付目录及授权域名

参照https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_3

具体流程

用户发起支付请求 --> 重定向至微信授权 -->微信重定向至服务器接口 --> 创建订单信息跳转至支付页面 --> 统一下单 --> 等待用户支付,微信回调 --> 接口接收到微信通知 --> 完成支付流程

1.

 用户发起支付请求,重定向至微信提供的授权接口,需携带参数

appid 为 公众号的APP_ID

redirect_uri 为 微信处理完授权 回调接口 需要进行URLEncode

state 为微信回调时携带的参数 根据需要填写 我这里填的是手机号

https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeChatConfig.APP_ID+"&redirect_uri="+URLEncoder.encode(WeChatConfig.CALL_BACK_URL)+"&response_type=code&scope=snsapi_base&state="+phonenmb+"#wechat_redirect";

2.

用户同意授权会获得一个code,通过这个code获取授权的access_token

String code = request.getParameter("code");
AuthToken authToken = WeChatUtils.getTokenByAuthCode(code);

在这里,我预先根据用户信息创建了一个未支付订单,将订单信息传到支付页面

3.

用户查看支付信息,同意后进行支付,进入统一下单

主要是构建微信统一下单需要的各种参数

//构建微信统一下单需要的参数
Map<String,String> map = Maps.newHashMap();
//用户ID
map.put("userId",userId);
//用户标识openId
map.put("openId",openid);
//请求Ip地址
map.put("remoteIp",request.getRemoteAddr());
//调用统一下单service
Map<String,Object> resultMap = WeChatPayService.unifiedOrderJsApi(order,map);
//通信标识
String returnCode = (String) resultMap.get("return_code");
//交易标识
String resultCode = (String) resultMap.get("result_code");
//返回信息
String return_msg = (String) resultMap.get("return_msg");

成功的情况下微信会返回

returnCode=SUCCESS

result_code=SUCCESS

return_msg=OK

失败的话查看msg信息,对照开发文档

只有当returnCode与resultCode均返回“success”,才代表微信支付统一下单成功

然后需要将信息传递到支付页面

//微信公众号AppId
String appId = (String) resultMap.get("appid");
//当前时间戳
String timeStamp = WeChatUtils.getTimeStamp();
//统一下单返回的预支付id
String prepayId = "prepay_id="+resultMap.get("prepay_id");
//不长于32位的随机字符串
String nonceStr = WeChatUtils.getRandomStr(32);
//自然升序map
SortedMap<String,Object> signMap = Maps.newTreeMap();
signMap.put("appId",appId);
signMap.put("package",prepayId);
signMap.put("timeStamp",timeStamp);
signMap.put("nonceStr",nonceStr);
signMap.put("signType","MD5");
model.addAttribute("appId",appId);
model.addAttribute("timeStamp",timeStamp);
model.addAttribute("nonceStr",nonceStr);
model.addAttribute("prepayId",prepayId);
//获取签名
model.addAttribute("paySign",WeChatUtils.getSign(signMap));

其中最重要的是签名,签名没有问题,支付流程基本上就完成了

4.

支付成功回调接口

支付后,微信会发送成功信息到步骤1中的redirect_uri接口

返回信息 XML解析到Map中

验证其中return_code 是否为SUCCESS

是则支付成功,保存微信返回的支付数据,return_msg = OK

否则支付失败,打印一下return_msg 信息处理

猜你喜欢

转载自my.oschina.net/xingyu4j/blog/1800991
今日推荐