10

前端微信JSAPI支付

 3 years ago
source link: https://aoppp.com/qian-duan-jsonapizhi-fu/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这篇文章适合没做过微信JSAPI支付的人,用过的大佬可以浅略看看,本文采用JQ + 搜狐提供的ip搜索

第一步,环境

JSAPI是用户通过消息或扫描二维码在微信内打开网页时,可以调用微信支付完成下单购买的流程

1.他是在微信浏览器里面才能调起的`支付方式`
2.上面说到既然是微信浏览器,我们就要想到`微信开发者工具` => 公众号开发(进行去调试)

第二步,登录

1.开发工具弄好了,接下来就是拿到哪个微信号给你付钱了。
2.要想微信号给公众号(你)付钱,首先你就要让微信用户授权给你这个公众号(用户和公众号会有个id,就是openid))

接下来就是怎么去拿到openid呢,详情看官网官方文档

获取openid官方文档介绍

var ua = navigator.userAgent.toLowerCase();
// 判断是否在微信浏览器
if (ua.indexOf('micromessenger') != -1) {
  if (!openid) {
      let code;
      try {
      	  // 获取到code,以拿到openid
          code = v['code'];
      } catch (err) {
          code = false;
      }
      // 判断是否授权
      if (!code) {
          // 商家id
          let appid = "wx5b77d71e115cb6a4";
          // 需要回调的地址,-》当前路径下的online-recharge.html
          let redirect_uri = payHref() + 'online-recharge.html';
          // 授权类型
          let scope = 'snsapi_base';
          location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
      } else {
          // 请求接口,获取openid
          let url = ApiUrl() + '/pay/vx/get-openid';
          axios.post(url,
              { "messageType": 0, "messageContent": code }) //也可以直接拼接在url
              .then(function (rs) {
                  if (rs.data.messageCode == 500) {
                      $.alert(rs.data.errorMessage);
                  }
                  if (rs.data.messageCode == 200) {
                      console.log(rs.data.messageContent)
                      let messageContent = JSON.parse(rs.data.messageContent);
                      if (messageContent.errcode) {
                          $.alert('获取openid失败');
                      } else {
                          let openid = messageContent.openid;
                          if (openid) {
                          	  // 将openid存到缓存中
                              storeage.setItem("openid", openid);
                          }
                      }
                  }
              })
      }
  }

第四步,调起支付

<!-- 搜狐提供的ip搜索, returnCitySN["cip"] -->
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
// 
if (in_weixin) {
	// openid 
    let openid = storeage["openid"];
    // 当前手机的IP
    let cip = returnCitySN["cip"];
    // 支付类型
    let tradeType = "JSAPI";
    // 购买信息组成的对象
    let messageContent_pay = {
        "userGuid": userGuid,
        "unitGuid": unitGuid,
        "cardNumber": cardNumber,
        "logicalCardNumber": logicalCardNumber,
        "rechargeWallet": walletNo,
        "rechargeModel": 2,
        "rechargeAmount": $("#amount").val(),
        "ip": cip,
        "openid": openid,
        "tradeType": tradeType,
    }
    // 获取微信支付信息
    wx_pay(messageContent_pay)
} else {
    $.alert('请到微信公众号充值')
}
// 获取微信支付信息
function wx_pay(messageContent) {
    let url = ApiUrl() + '/pay/vx/vxPay';
    axios({
        method: 'POST',
        url,
        data: qs.stringify(messageContent), headers: { 'content-type': 'application/x-www-form-urlencoded' },
    }) //也可以直接拼接在url
        .then(function (rs) {
            if (rs.data.messageCode == 200) {
                let timeStamp = (new Date()).getTime();
                let appId = "wx5b77d71e115cb6a4";
                // 调起微信支付密码窗口
                onBridgeReady(rs.data.messageContent.payRequest, rs.data.messageContent.outTradeNo)
            } else {
                $.alert(rs.data.errorMessage);
            }

        })
}
// 这个是调起微信支付密码窗口,输完密码后会微信后台会给到你回调,这时候你就完成了本次支付
function onBridgeReady(payObj, outTradeNo) {
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', payObj,
        function (res) {
        	// 支付成功
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示:
                //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
                // 跳转到自己写的订单详情页面
                location.href = myHref() + "recharge-result.html?out_trade_no=" + outTradeNo;
            } else {
                $.alert('支付失败');
            }
        });
}

本文为作者原创或转载,允许转载,由憧憬在 aoppp.com发布 转载请说明文章出处。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK