微信小程序开发者微信小程序开发小程序学习

微信小程序支付

2019-11-23  本文已影响0人  挣扎在黑暗中的码畜

业务流程

clipboard.png
  1. 在后台调用统一下单接口获取prepay_id(预支付交易会话标识)
  2. 小程序端调用支付API唤起支付
  3. 完整支付,后调链接中更新订单信息

步骤一:商户在小程序中先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易后调起支付。

使用了支付工具包: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.只要支付成功在异步回调
关注公众号获取更多动态:

qrcode_for_gh_200a17174ff1_258.jpg
上一篇 下一篇

猜你喜欢

热点阅读