一个简单的微信小程序支付demo

一个简单的微信小程序支付demo

一个简单的微信小程序支付demo_第1张图片

//    .wxml
<button bindtap='payment'>支付 0.01</button>

//   .js
//在这里演示支付的过程,获取openid不做解释
payment: function () {
var that = this;
console.log('openid=' + app.globalData.openid);
 
//请求后台发起支付,获取5个参数,data中放入支付的总额及其openid
//请求为示例
wx.request({
url: 'https://服务器域名/****/wx_pay',
data: { openid: app.globalData.openid, money: "0.01" },
// method: 'POST',
// header: { "Content-Type": "application/json;charset=UTF-8"},
success: res => {
console.log("服务端返回订单号");
if (res ) {
//接受的5个参数,调用这个方法成功,微信就会弹出输入密码的界面
wx.requestPayment({
timeStamp: res.data.data.timeStamp,
nonceStr: res.data.data.nonceStr,
package: res.data.data.package,
signType: res.data.data.signType,
paySign: res.data.data.paySign,
 
success: payRes => {
//支付成功后,可以做一些逻辑判断
console.log('支付成功!');
console.dir(payRes);
},
fail: payFail => {
console.log('支付失败!');
console.dir(payFail);
}
})
} else {
console.log('后台没有接受到5个参数');
}
},
fail: fail => {
console.log('支付获取参数失败!');
console.dir(fail);
}
})
}





@RequestMapping("wx_pay")
public Result<?> generateSignature(@RequestParam String openid , @RequestParam String money) throws Exception {
     
     
             Map<String, String> reqParams = new HashMap<>();
                //微信分配的小程序ID
                reqParams.put("appid",APPID);
                //微信支付分配的商户号
                reqParams.put("mch_id", MCH_ID);
                //随机字符串
                reqParams.put("nonce_str", WXPayUtil.generateNonceStr());
                //签名类型
                reqParams.put("sign_type", "MD5");
                //充值订单 商品描述
                reqParams.put("body",  "-测试-充值订单-微信小程序");
                //商户订单号
                reqParams.put("out_trade_no", WXPayUtil.createBillNo() );
                //订单总金额,单位为分
                reqParams.put("total_fee", WXPayUtil.getMoney(money)  );
                //终端IP
                reqParams.put("spbill_create_ip", "127.0.0.1");
                //通知地址
                reqParams.put("notify_url", NOTIFY_URL);
                //交易类型
                reqParams.put("trade_type", "JSAPI");
                //用户标识      、openid(在接口文档中 如果交易类型设置成'JSAPI'则必须传入openid)
                reqParams.put("openid", openid);
                //第一次签名
                String sign = WXPayUtil.generateSignature(reqParams, MCHAPI_KEY);
                reqParams.put("sign", sign);
                /*
                 *  调用支付定义下单API,返回预付单信息 prepay_id
                 */
                String xmlResult = HttpUtil.doSSLPost(WxProgramPayConfig.UNIFIED_ORDER_URL, WXPayUtil.mapToXml(reqParams));
                 
                 
                 
                //解析统一下单返回结果的xml
                Map<String, String> result = WXPayUtil.xmlToMap(xmlResult);
                 
                //返回状态码
                String return_code = (String) result.get("return_code");
                String return_Msg = String.valueOf(result.get("return_msg"));
                 
                //预付单信息
                String prepay_id = result.get("prepay_id");
     
                /*
                 * 小程序调起支付数据签名
                 */
                Map<String, String> packageParams = new HashMap<String, String>();
                if(return_code == "SUCCESS" || return_code.equals("SUCCESS")){
                     //返回的预付单信息
                       
                    packageParams.put("appId",APPID);
                    //这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误
                    packageParams.put("timeStamp",  String.valueOf(WXPayUtil.getCurrentTimestampMs()));
                    packageParams.put("nonceStr", WXPayUtil.generateNonceStr());
                    packageParams.put("package", "prepay_id=" + prepay_id);
                    packageParams.put("signType", "MD5");
                     
                    //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                    String packageSign = WXPayUtil.generateSignature(packageParams, MCHAPI_KEY);
                    packageParams.put("paySign", packageSign);
                    logger.info("=======================第二次签名:" + packageSign + "=====================");
                     
                    return ResultGenerator.genSuccessResult(packageParams);
                }else{
                      logger.info("支付返回状态码错误 ===>" + return_code);
                      logger.info("支付返回状态码错误 ===>" + WXPayUtil.getMsg(return_code));
                      return ResultGenerator.genSuccessResult(return_code);
                }
                 
         
         
         
         
 
 
 
}





/**
     * 微信小程序支付成功回调函数
     * @param request
     * @param response
     * @throws Exception
     */
     @ApiIgnore
        @RequestMapping("/WeChatNotify")
        public void weChatNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
            logger.info("【进入微信支付回调通知】");
              BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
                String line = null;
                StringBuilder sb = new StringBuilder();
                while((line = br.readLine())!=null){
                    sb.append(line);
                }
                br.close();
                 
                 
               // 解析xml成map
                Map<String, String> map = new HashMap<String, String>();
                map = XMLUtil.doXMLParse(sb.toString());
                String resXml = "";
                System.out.println("接收到的报文:" + sb.toString());
                 
                // 过滤空 设置 TreeMap
                SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
                Iterator it = map.keySet().iterator();
                while (it.hasNext()) {
                    String parameter = (String) it.next();
                    String parameterValue = map.get(parameter);
          
                    String v = "";
                    if (null != parameterValue) {
                        v = parameterValue.trim();
                    }
                    packageParams.put(parameter, v);
                }
                 
              
                String returnCode = (String) map.get("return_code");
                if("SUCCESS".equals(returnCode)){
                    //验证签名是否正确
                        if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, MCHAPI_KEY)) {
                        
                            // 这里是支付成功
                            /**此处添加自己的业务逻辑代码start**/
//                          String mch_id = (String) packageParams.get("mch_id");
//                          String openid = (String) packageParams.get("openid");
                            String out_trade_no = (String) packageParams.get("out_trade_no"); //订单号
//                          String prepay_id = (String) packageParams.get("prepay_id");
                            Integer total_fee = Integer.parseInt((String)packageParams.get("total_fee"));
                            String attach = (String)packageParams.get("attach"); //商家数据包,原样返回------扩展字段
//                          JSONObject json = JSON.parseObject(attach);
//                          String notifyUrl = json.getString("notifyUrl");
                             
//                         
                        /**此处添加自己的业务逻辑代码end**/
              
                        //通知微信服务器已经支付成功
                        resXml = "" + ""
                                + "" + " ";
                    }
                }else{
                    resXml = "" + ""
                            + "" + " ";
                }
                System.out.println(resXml);
                System.out.println("微信支付回调数据结束");
              
                BufferedOutputStream out = new BufferedOutputStream(
                        response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
                 
                 
        }

你可能感兴趣的:(一个简单的微信小程序支付demo)