微信支付流程

//第一步,前端找后台获取公众号 appId
//第二步,带着appid去微信授权,需要获取url的code(encodeURIComponent(local)或者encodeURI(local))

import { weChatPay } from "./wxPay";//获取封装好的公共支付方法
  if (code === null || code === "") {
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          appId +
          "&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
      }  else {
//第三步,带着code去找后台取openid
        const res = await basic.tongyidiaoyongjiekou.get(
          "/pay/opnidQuery",
          {
            code: code
          }
        );
        this.openid = res.data.openid;
      }
//第四步,前面会执行你们需要执行的步骤,第四步,调用微信统一下单接口,
  async wxPayOrder(orderId) {
      const res = await basic.requestFromUniversal.post("/pay/unifiedorder", {
        outTradeNo: parseFloat(orderId),//订单编号
        openId: this.openid,//openid
        totalFee:  this.price*100,//价格
        body: this.giftName//名字
      });

      const timeStamp = res.retObj.timeStamp;
      const appId = res.retObj.appId;
      const nonceStr = res.retObj.nonceStr;
      const packageVal = res.retObj.package;
      const paySign = res.retObj.sign;
//此时,后台会给你拉起支付需要的参数。
      return {
        timeStamp,
        appId,
        nonceStr,
        packageVal,
        paySign
      };
    }
//第五步,在拿到参数后,拉起微信,并防止结束后的回调。
 const oRes = await this.wxPayOrder(orderId);
        const Result = weChatPay(
          oRes.appId,
          oRes.timeStamp,
          oRes.nonceStr,
          oRes.packageVal,
          oRes.paySign
        )
        Result.then(()=>{
            console.log('支付呼起结束')
        })

//--------获取链接code的函数
function getUrlParam  (name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg);  // 匹配目标参数
  if (r != null) {
      return unescape(r[2]);  // 返回参数值
  } else {
      return null;
  }
}

const code = getUrlParam('code') 
//获取local
const local = window.location.href

//封装好的微信内部函数===================适合上面方法调用
//微信支付
export async function weChatPay(appId, timeStamp, nonceStr, packageVal, paySign) {
    //微信支付
    function onBridgeReady() {
        return new Promise(resolve => {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                "appId": appId,
                "timeStamp": timeStamp,
                "nonceStr": nonceStr,
                "package": packageVal,
                "signType": "MD5",//加密方式需要一致
                "paySign": paySign,
            },
                function (res) {
                    resolve();
                    /*??为什么成功的回调放进成功的判断调不起??*/
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                    } else {
                        console.log(res.err_msg)
                    }
                });
        })
    }


    if (typeof window.WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        return onBridgeReady()
    }
}

//微信内部函数结束========================
//-------------------------------分割线----------------------------------------------------------------------

//普通的微信内部配置+++++++++++++++++++++++++++++++++
//payData  为传递的参数
//微信支付
function _onBridgeReady(payData, successCallback, failCallback) {
    window.WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
            appId: payData.appid || payData.appId,
            timeStamp: payData.timestamp || payData.timeStamp,
            nonceStr: payData.nonce_str || payData.nonceStr,
            package: payData.package || 'prepay_id=' + payData.prepay_id,
            signType: payData.signType || 'MD5',
            paySign: payData.pay_sign || payData.paySign
        },
        function(respData) {
            if (respData.err_msg === 'get_brand_wcpay_request:ok') {
                successCallback();
            } else if (respData.err_msg === 'get_brand_wcpay_request:cancel') {
                failCallback();
            }
        }
    );
}

//微信支付
export function weChatPay(payData, successCallback, failCallback) {
    if (typeof window.WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
            document.addEventListener(
                'WeixinJSBridgeReady',
                _onBridgeReady,
                false
            );
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', _onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', _onBridgeReady);
        }
    } else {
        _onBridgeReady(payData, successCallback, failCallback);
    }
}
//普通配置结束+++++++++++++++++++++++++++++++

//****注意点
//1.后台签名需注意,sign 为之前前给后的订单信息(价格,名字,订单号...)后台去拼接加密再给前端。
//2.前端给微信的 package 格式应为 ‘prepay_id=u802345jgfjsdfgsdg888’,注意prepay_id=
//3.total_fee  不能为0    应该乘100,因为支付时的钱是分

你可能感兴趣的:(微信支付流程)