1.当点击微信登录的时候调用自定义的方法 weixinlogin 会让用户授权,当用户授权成功的时候会返回一个带code的地址

weixinlogin() {
          weixinAuthUrl().then(res => {//请求后台接口的方法
              if (res.link) window.location.href = res.link;//res.link 用户同意授权 返回code
          });        
    }

2.当有code参数的时候,在页面创建的时候去判断是否存在code

created(){
this.initDataFn();
}
initDataFn() {
      try {
        const url=window.location.href;//获取当前地址栏
        const aid=GetQueryByString(url,'aid');//GetQueryByString 自己封装的方法来获取地址栏的参数
      	let start=url.indexOf("code");
        const code=url.substr(start+5,32);
        if (start>=0){//如果存在code
          weixinlogin(code,this.fromId)  //code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
            .then(res => {
              fundebug.notify('微信登录信息',JSON.stringify(res))
              this.setInitData()
                .then(() => {
                  window.location.replace(
                    window.location.origin + window.location.pathname + "#/?aid="+aid;//授权成功返回的页面
                  );
                })
                .catch(err => {
                });
            })
            .catch(err => {
              window.location.replace(
               window.location.origin + window.location.pathname + "#/login?aid="+aid
              );
            });
        }
      } catch (err) {

      }
    }

获取地址栏的参数的方法

export const GetQueryByString = (str,name) => {
	// var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	// if(!str.split("?")[1])return null;
	// var r = str.split("?")[1].match(reg); //匹配目标参数
	// if (r != null) {
	// 	return decodeURIComponent(r[2]);
	//
	// }
	// return null; //返回参数值

	//获取?号出现几次
	var tempArr = str.split('?');

	// //如果大于1
	if(tempArr.length-1>1){
		var rt = null;
		for(var i in tempArr){
			var s = tempArr[i]
			var reg1 = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			var r1 = s.match(reg1); //匹配目标参数
			if (r1 != null) {
				rt = decodeURIComponent(r1[2]);//一直覆盖,要最后的就行了
			}
		}

		return rt
	}

	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	if(!str.split("?")[1])return null;
	var r = str.split("?")[1].match(reg); //匹配目标参数

	if (r != null) {
		return decodeURIComponent(r[2]);

	}
	return null; //返回参数值

}
Logo

前往低代码交流专区

更多推荐