業務流程
- 在後臺調用統一下單接口獲取prepay_id(預支付交易會話標識)
- 小程序端調用支付API喚起支付
- 完整支付,後調鏈接中更新訂單信息
步驟一:商戶在小程序中先調用該接口在微信支付服務後臺生成預支付交易單,返回正確的預支付交易後調起支付。
使用了支付工具包:best-pay-sdk
<dependency>
<groupId>cn.springboot</groupId>
<artifactId>best-pay-sdk</artifactId>
<version>1.3.0.BETA</version>
</dependency>
相關代碼:
/** * 請求微信後臺統一下單 * 喚起微信支付 */
WxPayConfig wxPayConfig = new WxPayConfig();
wxPayConfig.setMiniAppId(wechatAccountConfig.getMiniAppId());
wxPayConfig.setAppSecret(wechatAccountConfig.getMiniAppSecret());
wxPayConfig.setMchId(wechatAccountConfig.getMchId());
wxPayConfig.setMchKey(wechatAccountConfig.getMchKey());
wxPayConfig.setNotifyUrl(wechatAccountConfig.getNotifyUrl());
bestPayService.setWxPayConfig(wxPayConfig); PayRequest payRequest = new PayRequest();
payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_MINI); payRequest.setOrderId(orderId);
payRequest.setOrderName("微信小程序支付訂單"); payRequest.setSpbillCreateIp(ip);
payRequest.setOrderAmount(priceSum); payRequest.setOpenid(order.getOpenid()); PayResponse
response = bestPayService.pay(payRequest); log.info("【發起支付】request={}",
JsonUtil.toJson(payRequest)); response.setOrderId(orderId);
return Result.ok(response);
步驟二:微信小小程序端調用支付api,喚起支付
相關代碼
api._post('/wx/api/payorder', data).then(res => {
console.log(res.result)
if (res.success) { //微信統一下單 喚起微信支付
wx.requestPayment({
timeStamp: res.result.timeStamp,
nonceStr: res.result.nonceStr,
package: res.result.package,
signType: res.result.signType,
paySign: res.result.paySign,
success(r) { },
fail(r) {
var data = { }
api._post('/wx/api/updataorder', data).then(res => {})
}
})
}
})
步驟三:異步回調中校驗金額,更新訂單
相關代碼
/**
* 微信支付異步回調
* 注意:這裏金額和訂單中的對比
* @param req
* @return
*/
@RequestMapping(value = "/notify", method = RequestMethod.POST)
public ModelAndView notify(@RequestBody String notifyData){
log.info("【異步通知】支付平臺的數據request={}", notifyData);
PayResponse response = bestPayService.asyncNotify(notifyData);
log.info("【異步通知】處理後的數據data={}", JsonUtil.toJson(response));
//返回成功信息給支付平臺,否則會不停的異步通知
if (response.getPayPlatformEnum() == BestPayPlatformEnum.WX) {
log.info("支付成功");
return new ModelAndView("pay/responeSuccessForWx");
}else if (response.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) {
return new ModelAndView("pay/responeSuccessForAlipay");
}
throw new RuntimeException("錯誤的支付平臺");
}
注意:
1.回調通知注意事項:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=23_8&index=5
2.只要支付成功在異步回調
關注公衆號獲取更多動態: