操作步骤

1. 判断是否授权过头像昵称

2. 若未授权,判断是否是微信浏览器打开

// 判断是否微信浏览器
isWXBrowser() {
  return (
    String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) = "micromessenger");
  },

3. 若是微信浏览器打开,判断地址栏是否返回code

// 截取地址栏code
getUrlCode(name) {
  return (
    decodeURIComponent(
      (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(location.href) || [, ""])[1].replace(/\+/g, "%20")
    ) || null
  );
},

4. 若有code,根据code获取相关信息,无code,需跳转授权页面获取code

//访问微信地址,用来获取code
getWeChatCode() {
  //处理域名
  let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
  let appid = 'wx77b2************'
  window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + local + "&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
},

5. 判断使用

if(!this.userInfo.avatar){ // 未授权头像昵称
    this.isWXBrowser = this.isWXBrowser();
    if (this.isWXBrowser) {
      let code = this.getUrlCode("code");
      if (code) {
        this.wxLogin(code);
      } else {
        this.getWeChatCode(); //微信授权
      }
    }
  }

后续出现点击获取头像昵称无反应的情况并报错[Component] <button>: chooseAvatar:fail api scope is not declared in the privacy agreement

是由于小程序的隐私协议更新小程序隐私协议开发指南 | 微信开放文档

1. 需在小程序后台设置用户隐私保护指引添加收集头像昵称的信息类型

2. 在manifest.json中添加"__usePrivacyCheck__":true,

"mp-weixin" : {
    "__usePrivacyCheck__":true,
}

3. 将基础库设为2.30.4

4. 待后台隐私协议审核通过后 将代码重新提交并发布到线上

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐