H5 及 web 页面微信授权登录流程

H5页面分享到微信获取用户信息

注意:我们要求调试微信网页授权,必须开发者微信号与公众号建立绑定关系
需求背景:将H5页面分享到微信,页面中的功能需要登录,所以再进行功能操作前需要调起登录

授权登录

1、微信登录的几种情况:
PC端:

PC端微信浏览器 -> 网页内嵌二维码方式(需要扫码,使用微信服务号的 appid 和 appsecret)

PC端其他浏览器 -> 跳转微信的扫码登录页面(需要扫码,使用微信开放平台注册的PC应用 appid 和 appsecret)

移动端:

微信客户端打开 -> 直接调用微信授权(不扫码,使用微信服务号的 appid 和 appsecret)

其他手机浏览器打开 -> 跳转微信的扫码登录页面(需要扫码,使用微信开放平台注册的PC应用 appid 和 appsecret)

2、区分是否是PC环境的方法:

function IsPC(){
    
      
     var userAgentInfo = navigator.userAgent;
     var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");  
     var flag = true;  
     for (var v = 0; v < Agents.length; v++) {
    
      
         if (userAgentInfo.indexOf(Agents[v]) > 0) {
    
     flag = false; break; }  
     }  
     return flag;  
  }
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    
    
    //alert(navigator.userAgent);  
    window.location.href ="iPhone.html";
} else if (/(Android)/i.test(navigator.userAgent)) {
    
    
    //alert(navigator.userAgent); 
    window.location.href ="Android.html";
} else {
    
    
    window.location.href ="pc.html";
};

获取用户信息流程

  1. 获取微信中的code
// 获取微信用户code
    getWxCode() {
    
    
      let appid = "公众号appid"; // 一定是小程序和微信公众号进行了绑定,否则不生效
      let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
      
      appid}&redirect_uri=${
      
      encodeURIComponent(
        location.href
      )}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`;
      this.code = this.getUrlCode().code;
      //如果没有code 去获取code
      if (this.code == null) {
    
    
        window.location.href = url;
      } else {
    
    
        //获取到code后的逻辑
        console.log("code", this.code);
        this.login();
      }
    },

2.截取url中的code

// 截取url中的code
    getUrlCode() {
    
    
      var url = location.search;
      var theRequest = new Object();
      if (url.indexOf("?") !== -1) {
    
    
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
    
    
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    },

3.调用登录接口

async login() {
    
    
      console.log("开始登录");
      const data = {
    
    
        code: this.code,
        udid: "081cvZ280Toa1F1VfB180Jv8380cvZ2i",
        appletType: 4
      };
      ajaxMethod.doAjax("接口地址", data, (res) => {
    
    
        if (res.success) {
    
    
          if (res.datas.token) {
    
    
            setLocalStorageBykey("ticket", res.datas.token);
            console.log("登录后进行Ticket缓存");
          }
          return;
        }
      });
    },

猜你喜欢

转载自blog.csdn.net/m0_44973790/article/details/130762849