微信小程序开发,微信小程序轻松实现微信支付及微信提现到零钱功能

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/love468092550/article/details/87370267

最近做了一个小程序用到了微信支付及零钱提现功能。

准备工作,开发之前,我们需要有下面这些东西:

  • appId
  • 密钥(小程序配置界面)
  • 商户号
  • api密钥(商家后台自己设置)

1,小程序代码实现

      <view class='pay_btn_view'>
             <button class='pay_btn' bindtap='btn_to_pay' 
                     data-keyword="{{hmhDataInfo}}">立即购买</button>
      </view>

小程序js实现部分 

btn_to_pay: function (e) {


    //显示加载数据
    this.setData({
      loadingHidden: false
    });

    var paymoney = e.currentTarget.dataset.keyword.serviceprice;
    console.info(" === " + this.data.pay_state + " , money = " + paymoney);
    var content = "";
    var type = 0;
    if (this.data.pay_state==0){
      content = "你选择了月";
      type = 1;
    } else if (this.data.pay_state==1){
      content = "你选择了三个月";
      type = 2;
    } else if (this.data.pay_state==2){
      content = "你选择了年";
      type = 3;
    } else if (this.data.pay_state == 3) {
      content = "你选择了终生";
      type = 4;
    }

    var openid = wx.getStorageSync("openId");
    if (openid != '') {
      //关闭授权层
      this.setData({
        isRuleTrue: false,
      })
    } else {
      //显示弹出层
      this.setData({
        isRuleTrue: true
      })
    }

    var that = this;
    wx.request({
      url: getApp().data.servsers + '/dp/sys/wxpay/topay?price=' + paymoney + '&open_id=' + openid + '&type=' + type,
      method: "GET",
      header: {
        'content-type': 'application/text'
      },
      success: function (res) {
        that.setData({
          loadingHidden: true
        });
       
        var nonceStr = res.data.userInfoPay.nonceStr;
        var packages = res.data.userInfoPay.packages;
        var pay_price = res.data.userInfoPay.pay_price;
        var sign = res.data.userInfoPay.sign;
        var timeStamp = res.data.userInfoPay.timeStamp;
        //只有status 为 0 才可以正常支付
        var status = res.data.userInfoPay.status;
        if(status==0){
          wx.requestPayment({
            'timeStamp': timeStamp,
            'nonceStr': nonceStr,
            'package': packages,
            'signType': 'MD5',
            'paySign': sign,
            'success': function (succ) {
                wx.showModal({
                  title: '提示',
                  content: '支付成功',
                  success: function (e) { 
                      if(e.confirm){
                          console.info(" success === ");
                          //跳转到用户信息页面
                        setTimeout(function () {
                          wx.switchTab({
                            url: '../myinfo/myinfo'
                          })
                        }, 500)

                      }else if(e.cancel){
                        console.info(" cancel === ");
                      }
                  },//接口调用成功
                  fail: function () { 

                  },  //接口调用失败的回调函数  
                  complete: function () {

                   } //接口调用结束的回调函数  
                });
            
            },
            'fail': function (err) {
                wx.showModal({
                  title: '提示',
                  content: '支付失败'
                });
            },
            'complete': function (comp) {

            }
          })
        }else{
          wx.showModal({
            title: '提示',
            content: '支付验证失败'
          });
        }
      }
    })

  },

 

2,后台接口实现

 

 /****
     * 小程序端支付接口
     * oZvme4q2Oi7Dz3FChXc4G_3kqw28
     * @return
     * @throws Exception
     */
    @RequestMapping("/topay")
    public R wxUserPay(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) throws Exception {
        logger.info("wechat pay #####################################################");
        String pay_price = request.getParameter("price");
        String open_id = request.getParameter("open_id");
        String type = request.getParameter("type");
        String orderNo = Sha1Util.getOrderNumber();
        Map<String, Object> resultInfo = new HashMap<String, Object>();
        if(!"".equals(open_id)&&open_id!=null){
            logger.info("wxUserPay >>>>> "+pay_price+" , open_id = "+open_id+ " , orderNo = "+orderNo);
            //先查询用户然后,生成订单保存到数据库(状态为待支付)
            HmhOrderInfoEntity orderInfoEntity = new HmhOrderInfoEntity();
            orderInfoEntity.setCreateTime(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            orderInfoEntity.setOpenid(open_id);
            orderInfoEntity.setPayPrice(pay_price);
            orderInfoEntity.setStatus(0); //等待付款
            orderInfoEntity.setOrderid(orderNo);
            orderInfoEntity.setOrderType(0);
            orderInfoEntity.setType(Integer.parseInt(type));
            hmhOrderInfoService.saveHmhOrderInfo(orderInfoEntity);
            //金额转化为分为单位
            float sessionmoney = Float.parseFloat(pay_price);
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            //商户相关资料
            String appid = HmhConfig.APP_ID;
            String appsecret = HmhConfig.APP_secret;
            String partner = HmhConfig.pertenr;
            String partnerkey = HmhConfig.pertnerKey;
            String currTime = TenpayUtil.getCurrTime();
            //8位日期
            String strTime = currTime.substring(8, currTime.length());
            //四位随机数
            String strRandom = TenpayUtil.buildRandom(4) + "";
            //10位序列号,可以自行调整。
            String strReq = strTime + strRandom;
            //商户号
            String mch_id = partner;
            //子商户号  非必输
            //String sub_mch_id="";
            //设备号   非必输
            String device_info="";
            //随机数
            String nonce_str = strReq;
            //商品描述
            //String body = describe;
            //商品描述根据情况修改
            String body = "xxx管理服务费";
            //附加数据
            String attach = "";
            //商户订单号
            String out_trade_no = orderNo;
            int intMoney = Integer.parseInt(finalmoney);
            //总金额以分为单位,不带小数点
            int total_fee = intMoney;
            //订单生成的机器 IP
            String spbill_create_ip = request.getRemoteAddr();
            //订 单 生 成 时 间   非必输
//			String time_start ="";
            //订单失效时间      非必输
//			String time_expire = "";
            //商品标记   非必输
//			String goods_tag = "";
            //这里notify_url是 支付完成后微信发给该链接信息,可以判断会员是否支付成功,改变订单状态等。
            String notify_url =wxpay_notify;
            String trade_type = "JSAPI";
            //非必输
            SortedMap<String, String> packageParams = new TreeMap<String, String>();
            packageParams.put("appid", appid);
            packageParams.put("mch_id", mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("body", body);
            packageParams.put("attach", attach);
            packageParams.put("out_trade_no", out_trade_no);

            //这里写的金额为1 分到时修改
            packageParams.put("total_fee", String.valueOf(total_fee));
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", notify_url);
            packageParams.put("trade_type", trade_type);
            packageParams.put("openid", open_id);
            RequestHandler reqHandler = new RequestHandler(request, response);
            reqHandler.init(appid, appsecret, partnerkey);
            String sign = reqHandler.createSign(packageParams);
            String xml="<xml>"+
                    "<appid>"+appid+"</appid>"+
                    "<mch_id>"+mch_id+"</mch_id>"+
                    "<nonce_str>"+nonce_str+"</nonce_str>"+
                    "<sign>"+sign+"</sign>"+
                    "<body><![CDATA["+body+"]]></body>"+
                    "<attach>"+attach+"</attach>"+
                    "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
                    //金额,这里写的1 分到时修改
                    "<total_fee>"+String.valueOf(total_fee)+"</total_fee>"+
                    "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
                    "<notify_url>"+notify_url+"</notify_url>"+
                    "<trade_type>"+trade_type+"</trade_type>"+
                    "<openid>"+open_id+"</openid>"+
                    "</xml>";
            String createOrderURL = HmhConfig.unifiedorder;
            String prepay_id="";
            try {
                prepay_id = new GetWxOrderno().getPayNo(createOrderURL, xml);
                logger.info("prepay_id >>>>> "+prepay_id);
                if("".equals(prepay_id)){
                    resultInfo.put("status",3);
                    resultInfo.put("msg","统一支付接口获取预支付订单出错");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            SortedMap<String, String> finalpackage = new TreeMap<String, String>();
            String appid2 = appid;
            String timestamp = Sha1Util.getTimeStamp();
            String nonceStr2 = nonce_str;
            String prepay_id2 = "prepay_id="+prepay_id;
            String packages = prepay_id2;
            finalpackage.put("appId", appid2);
            finalpackage.put("timeStamp", timestamp);
            finalpackage.put("nonceStr", nonceStr2);
            finalpackage.put("package", packages);
            finalpackage.put("signType", "MD5");
            String finalsign = reqHandler.createSign(finalpackage);
            Map<String, Object> map= new HashMap<String, Object>();
            map.put("status", 0);
            map.put("appId", appid2);
            map.put("timeStamp", timestamp);
            map.put("nonceStr", nonceStr2);
            map.put("packages", packages);
            map.put("sign", finalsign);
            map.put("pay_price", pay_price);
            map.put("open_id", open_id);
            resultInfo.put("userInfoPay",map);
            resultInfo.put("status",0);
            resultInfo.put("msg","支付成功");
        }else{
            logger.info("用户open_id为空");
            resultInfo.put("status",1);
            resultInfo.put("msg","用户open_id为空");
        }
        return R.ok(1,resultInfo);
    }

小程序提现接口java代码实现

//提现到零钱
    //https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
    @RequestMapping("/transfer")
    public R transfer(HttpServletRequest request, HttpServletResponse response) {

        String openid = request.getParameter("openid");
        String amount = request.getParameter("amount");

        Map<String, Object> resultInfo = new HashMap<String, Object>();
        String tk_order_id = Sha1Util.getTXOrderNumber();
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        System.out.println(" == >> "+tk_order_id);
        String mch_appid = HmhConfig.APP_ID; //商户账号appid
        String mchid = HmhConfig.pertenr; //商户号
        String nonce_str = uuid; //随机32位字符串
        String partner_trade_no = tk_order_id; //商户订单号
//        String openid = "";//用户openid
        String check_name = "NO_CHECK"; //校验用户姓名选项 (NO_CHECK:不校验真实姓名 FORCE_CHECK:强校验真实姓名)
        String re_user_name = "xxx"; //收款用户姓名
//        String amount = ""; //企业付款金额,单位为分
        String desc = "xxx"; //企业付款备注
        String spbill_create_ip = "10.2.3.11"; //Ip地址

        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", mch_appid);
        packageParams.put("mchid", mchid);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("partner_trade_no", partner_trade_no);
        packageParams.put("openid", openid);
        packageParams.put("check_name", check_name);
        packageParams.put("re_user_name", re_user_name);
        packageParams.put("amount", amount);
        packageParams.put("desc", desc);
        packageParams.put("spbill_create_ip", spbill_create_ip);

        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(mch_appid, HmhConfig.APP_secret, HmhConfig.pertnerKey);
        String sign = reqHandler.createSign(packageParams); ////签名

        String transferXml = "<xml>" +
                "<mch_appid>"+mch_appid+"</mch_appid>" +
                "<mchid>"+mchid+"</mchid>" +
                "<nonce_str>"+nonce_str+"</nonce_str>" +
                "<partner_trade_no>"+partner_trade_no+"</partner_trade_no>" +
                "<openid>"+openid+"</openid>" +
                "<check_name>"+check_name+"</check_name>" +
                "<re_user_name>"+re_user_name+"</re_user_name>" +
                "<amount>"+amount+"</amount>" +
                "<desc>"+desc+"</desc>" +
                "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>" +
                "<sign>"+sign+"</sign>" +
                "</xml>";

        String  result= new GetWxOrderno().getPayNo(HmhConfig.transferurl, transferXml);

        resultInfo.put("status",1);
        resultInfo.put("msg",result);

        return R.ok(1,resultInfo);
    }

注意,小程序提现需要配置证书

 当发现调用不起来支付时请检查,域名,商户后台配置支付目录。

微信支付文档:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1

更多优质文章请关注我的微信公众号【java后端技术精选】,回复“1024”和“面试”可以领取优质的视频学习资源

展开阅读全文

没有更多推荐了,返回首页