H5在微信环境调用微信支付

这里用的是 vue项目;
首先在mounted中判断是否有openId,如果没有,则去获取

let openid = localStorage.getItem('openid');
  if (!openid || openid == 'null' || openid == 'undefined') {
    this.getWechatOauth();
}
 //获取微信openId
  async getWechatOauth() {
      const code = this.GetQueryString('code')   //获取code
      let local = window.location.href;          //获取当前路由  ----------- 这个路由需要至少在test的环境,并且被添加在appId对应的公众号中
      if(!code) {  //在当前路由中获取不到code
          const APPID = process.env.VUE_APP_BASE_WECHAT_APPID
          //scope=snsapi_base  snsapi_base-不弹出授权页面,直接跳转,只能获取用户openid;  snsapi_userinfo-弹出授权页面,可通过openid拿到昵称、性别、所在地
          window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_base#wechat_redirect'
      }else {  //获取到code,继续获取openId
          this.wechatOauth(code)
      }
  },
  //微信授权
  async wechatOauth(code){
      //  通过后端提供的接口,获取openId,
      wechatOauth({code:code}).then(res => {
          localStorage.setItem('openid', res.id);
      })
  }
//从路由中获取code
  GetQueryString (name) {
      const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      const r = window.location.search.substr(1).match(reg);

      if (r != null) return unescape(r[2]);
      return null;
  },

以上内容最好在进入页面是获取到,也可以在调起支付前完成,看心情,推荐进入页面获取

//  获取到openId之后,调起支付时调用该方法
onBridge() {
            let { appid, nonce_str, sign, prepay_id, timestamp } = this.charge;   //这里面的参数是调用支付的必要参数,如果可以的话可以让后端统一返回
            let _this = this;
            WeixinJSBridge.invoke(
                "getBrandWCPayRequest", _this.charge,
                wxResponse => {
                    if (wxResponse.err_msg == "get_brand_wcpay_request:ok") {
                        Toast('支付成功');
                        this.$router.replace({path:'成功后跳转的页面',query:{'参数'}})
                    }
                    if (wxResponse.err_msg == "get_brand_wcpay_request:fail") {
                        Toast.fail('支付失败');
                    }
                    if (wxResponse.err_msg == "get_brand_wcpay_request:cancel") {
                        Toast.fail('支付取消');
                    }
                }
            );
                                
        },

posted on 2022-01-04 11:32  白黑besos  阅读(658)  评论(0编辑  收藏  举报

导航