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

1.创建公众号 https://mp.weixin.qq.com/

2.配置公众号信息

  1)公众号设置 =>账号详情

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

        2)人员设置:绑定开发者微信号

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()
         }
    }
}
/*微信登录相关  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*/

更多参考:

uni-app开发的h5,使用微信授权登录(前置条件+具体代码)_uniapp h5 微信授权登录-CSDN博客

H5之微信授权登陆 (uniapp网页版微信授权登录)_h5 实现授权登录 ui设计-CSDN博客

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

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值