zoukankan      html  css  js  c++  java
  • 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('支付取消');
                        }
                    }
                );
                                    
            },
    
    昼以继夜,行走不息
  • 相关阅读:
    1013 数素数
    1012 数字分类
    1010 一元多项式求导
    react-dnd 介绍及使用,react-dnd实现拖拽效果,
    FormData用法详解 var formdata=new FormData();
    【原生】js,setInterval,clearInterval
    <a>标签中的href="javascript:;"是什么意思?
    【git】 log git历史 记录
    CSS3 calc() 函数,width: calc(100%
    字符串截取,方法,slice,substring,substr。
  • 原文地址:https://www.cnblogs.com/changx/p/15761874.html
Copyright © 2011-2022 走看看