美文网首页
小程序之微信支付

小程序之微信支付

作者: 何事西风悲画扇_4b46 | 来源:发表于2018-12-22 09:46 被阅读0次

小程序页面

<button class='pay_fixed_right' formType="submit1" bindtap='pay' style="background:{{color}}">去支付</button>

小程序js 中间**就是需要替换的域名,openid需要自己小程序的

pay: function (e) {

    var openId = "o7Rrj5M-METpuTV8mNxv6_6gn1sw";

    var tradeNo = "85511613375";

    var amount = "0.01";

    var body = "餐费";

    wx.request({

      url: 'http://**/app/pay',

      method: 'POST',

      data: {

        openId: openId,

        tradeNo: tradeNo,

        tradeType: 'JSAPI',

        amount: amount,

        body: body,

      },    //参数为键值对字符串

      header: {

        //设置参数内容类型为x-www-form-urlencoded

        "Accept": "*/*", 'Content-Type': 'application/json'

      },

      success: function (e) {

        var data = e.data.wxPayResponse;

        wx.requestPayment({

          'timeStamp': data.timeStamp.toString(),

          'nonceStr': data.nonceStr,

          'package': data.package_wx,

          'signType': 'MD5',

          'paySign': data.sign,

          success: function (event) {

            // success   

            wx.showToast({

              title: '支付成功',

              icon: 'success',

              duration: 2000

            });

            //处理  业务逻辑



          },

          fail: function (error) {

            // fail   

            console.log("支付失败")

            wx.showToast({

              title: '支付失败',

              icon: 'none',

              duration: 2000

            });

          }

        })

      }

    })

  }

代码删减了些,不过问题不大

开始服务端了

AppWxPayController.java

@Autowired

    private WxPayService wxPayService;

private Logger logger = LoggerFactory.getLogger(getClass());



    @PostMapping("pay")

    @ApiOperation("微信支付")

    public R pay(@RequestBody PayParam payParam){

    WxPayEntity wxPayEntity=wxPayService.pay(payParam);//请求订单统一接口

    return R.ok().put("wxPayResponse", wxPayEntity);

    }

@PostMapping("payNotifyUrl")

    @ApiOperation("微信支付回调")

    public String payNotifyUrl(HttpServletRequest request){

        String xmlString = WxPayUtils.getXmlString(request);

        logger.info("----微信支付回调接收到的数据如下:---" + xmlString);

    return wxPayService.payAsyncNotify(xmlString);

    }

服务端支付接口和回调

/**

    * 调用微信支付-统一下单接口

    * @param payParam 用户传入的订单信息

    * @return

    */

    WxPayEntity pay(PayParam payParam);

WxPayService.java

service下面是实现类

WxPayServiceImpl.java 统一下单+回调

private Logger logger = LoggerFactory.getLogger(getClass());

    /* (non-Javadoc) 

    * <p>Title: pay</p> 

    * <p>Description: 统一下单接口</p> 

    * @param payParam

    * @return 

    * @see com.alpha.modules.wxpay.service.WxPayService#pay(com.alpha.modules.wxpay.form.PayParam) 

    */

    public WxPayEntity pay(PayParam payParam) {

        WxPayUnifiedorderResponse response = null;

        try {

            //组织统一下单接口请求参数

            WxPayUnifiedorderRequest request = new WxPayUnifiedorderRequest();

            request.setAppid(WxConfigure.getAppID());

            request.setBody(payParam.getBody());

            request.setMchId(WxConfigure.getMch_id());

            request.setNonceStr(WxPayUtils.getRandomStr(32));

            request.setNotifyUrl(WxConfigure.getPayNotifyUrl());

            request.setOpenid(payParam.getOpenId());

            request.setOutTradeNo(payParam.getTradeNo());

            request.setSpbillCreateIp(WxPayUtils.getIpAddr());//获取ip

            request.setTotalFee(WxPayUtils.yuanToFen(payParam.getAmount()));

            request.setTradeType(payParam.getTradeType());

            request.setSign(WxPayUtils.signByMD5(request, WxConfigure.getKey()));

            Retrofit retrofit = new Retrofit.Builder()

                    .baseUrl("https://api.mch.weixin.qq.com")

                    .addConverterFactory(SimpleXmlConverterFactory.create())

                    .build();

            String xml = WxPayUtils.objToXML(request);

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);

            Call<WxPayUnifiedorderResponse> call = retrofit.create(WxPayApi.class).UNIFIEDORDER_RESPONSE_CALL(requestBody);

            Response<WxPayUnifiedorderResponse> retrofitResponse = call.execute();

            response = retrofitResponse.body();

            if(!response.getReturnCode().equals("SUCCESS")) {

                throw new RuntimeException("【微信统一支付】发起支付, returnCode != SUCCESS, returnMsg = " + response.getReturnMsg());

            }

            if (!response.getResultCode().equals("SUCCESS")) {

                throw new RuntimeException("【微信统一支付】发起支付, resultCode != SUCCESS, err_code = " + response.getErrCode() + " err_code_des=" + response.getErrCodeDes());

            }

        } catch (IllegalAccessException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return buildWxPayResponse(response);

    }

    private WxPayEntity buildWxPayResponse(WxPayUnifiedorderResponse wxPayUnifiedorderResponse) {

        String timeStamps = String.valueOf(System.currentTimeMillis() / 1000L); //微信接口时间戳为10位字符串

        String package_wx = "prepay_id=" + wxPayUnifiedorderResponse.getPrepayId(); //返回前台package字段值为

        WxPayEntity wxPayEntity = new WxPayEntity();

        try {

            wxPayEntity.setTimeStamp(timeStamps);

            wxPayEntity.setNonceStr(WxPayUtils.getRandomStr(32));

            wxPayEntity.setPackage_wx(package_wx);

            wxPayEntity.setAppid(WxConfigure.getAppID());

            wxPayEntity.setSignType("MD5");

            Map<String, String> wxResMap = buildWxResMap(wxPayEntity);

            wxPayEntity.setSign(WxPayUtils.signByMD5(wxResMap, WxConfigure.getKey()));

        } catch (Exception e) {

            e.printStackTrace();

        }

        return wxPayEntity;

    }

    /**

    * 构造返回小程序签名参数(小程序支付二次签名)

    * @param wxPayEntity

    * @return

    */

    private Map<String,String> buildWxResMap(WxPayEntity wxPayEntity) {

        Map<String, String> wxResMap = new HashMap<>();

        wxResMap.put("appId", wxPayEntity.getAppid());

        wxResMap.put("nonceStr", wxPayEntity.getNonceStr());

        wxResMap.put("package", wxPayEntity.getPackage_wx());

        wxResMap.put("signType", "MD5");

        wxResMap.put("timeStamp", wxPayEntity.getTimeStamp());

        return wxResMap;

    }

    /* (non-Javadoc) 

    * <p>Title: payAsyncNotify</p> 

    * <p>Description: 支付回调接口</p> 

    * @param notifyData

    * @return 

    * @see com.alpha.modules.wxpay.service.WxPayService#payAsyncNotify(java.lang.String) 

    */

    public String payAsyncNotify(String notifyData) {

        WxPayNotifyResponse wxPayNotifyResponse = (WxPayNotifyResponse) WxPayUtils.xmlToObj(notifyData, WxPayNotifyResponse.class);

        try {

        String sign= WxPayUtils.signByMD5(wxPayNotifyResponse, WxConfigure.getKey());

        if (sign.equals(wxPayNotifyResponse.getSign())) {

            throw new RuntimeException("【微信支付异步通知】签名验证失败");

        }

        if(!wxPayNotifyResponse.getReturnCode().equals("SUCCESS")) {

    throw new RuntimeException("【微信支付异步通知】发起支付, returnCode != SUCCESS, returnMsg = " + wxPayNotifyResponse.getReturnMsg());

}

//该订单已支付直接返回

if (!wxPayNotifyResponse.getResultCode().equals("SUCCESS")

        && wxPayNotifyResponse.getErrCode().equals("ORDERPAID")) {

logger.info("【微信付款】付款成功通知:"+wxPayNotifyResponse.getOutTradeNo()+"付款成功");

return WxPayUtils.returnXML(wxPayNotifyResponse.getReturnCode());

}

if (!wxPayNotifyResponse.getResultCode().equals("SUCCESS")) {

    throw new RuntimeException("【微信支付异步通知】发起支付, resultCode != SUCCESS, err_code = " + wxPayNotifyResponse.getErrCode() + " err_code_des=" + wxPayNotifyResponse.getErrCodeDes());

}

logger.info("【微信付款】付款成功通知:"+wxPayNotifyResponse.getOutTradeNo()+"付款成功");

        } catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return WxPayUtils.returnXML(wxPayNotifyResponse.getReturnCode());

    }

在贴上调用微信接口的api

WxPayApi.java

/**

    * 统一下单接口

    * @param body

    * @return

    */

    @POST("pay/unifiedorder")

    Call<WxPayUnifiedorderResponse> UNIFIEDORDER_RESPONSE_CALL(@Body RequestBody body);

这里微信支付的代码就全部完结了。如若遇到问题可以加我q:850728581,有空会给解答或者留邮箱发源码
下一篇:小程序之微信退款

相关文章

网友评论

      本文标题:小程序之微信支付

      本文链接:https://www.haomeiwen.com/subject/hbxikqtx.html