uniapp项目嵌入微信公众号,授权登录

发布时间 2023-06-25 13:48:56作者: 阿宇爱吃鱼

1.创建公众号

2.配置公众号信息 =>公众号设置 =>账号详情

                                                   =>功能设置 =>配置业务、js接口安全、网页授权域名

                             =>人员设置:绑定开发者微信号

3.基本配置 =>appid,appsecret,配置白名单(服务器ip地址)

4.web开发者工具菜单:绑定开发者微信号

5.自定义菜单:菜单内容选择跳转网页,地址写服务器上h5所在地址

(要关注公众号才能成功获取用户信息)

 

uniapp项目:

1.定义变量:isWechat:false

2.在刚进入页面时判断是否已经授权登录过(code有无,每次授权code只能使用一次)

onLoad() {

   var that = this;

   var userData = uni.getStorageSync('userData');

   if (userData != null && userData != {} && userData != '' &&

         userData.id != '' && userData.id != undefined && userData.id != null) {

         console.log('登录')

   } else {

         that.isWeixin = that.isWechat()

         if (that.isWeixin) {

             that.checkWeChatCode()

         }

    }

}

3.

/*微信登录相关  start*/

  isWechat() { //用来判断是否是微信内置的浏览器

   return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";

  },

 

  getUrlCode(name) {//用来提取code

   return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ' ' ])[1].replace(/\+/g, '%20')) || null

  },

 

  checkWeChatCode() { //检查浏览器地址栏中微信接口返回的code,微信授权成功之后返回的code 调接口用过了就不会再弹窗了

   var that = this

   let code = that.getUrlCode('code')

   let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址

   let appid = 自己公众号的appid;

   if (code == null || code == '') { 

    window.location.href =

     "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid +"&redirect_uri=" +local+"&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";

   } else {

    var param = {};

    param.code = code

    api.登录接口({ //从后台获取用户信息

     data: param

    }).then((res) => {

     console.log(res)

     if (res.ret == 1 && res.data != null) {

      uni.setStorageSync('isLogin', true)

      uni.setStorageSync('userData', res.data);

     }

    }).catch((res) => {})

   }

  },

  /*微信登录相关  end*/

 

 

 

参考:

  1.https://blog.csdn.net/qq_37899792/article/details/109236912

  2.https://blog.csdn.net/wh20141212/article/details/107123467?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-0&spm=1001.2101.3001.4242

  3.https://juejin.cn/post/6844904174488911879