随笔 - 83,  文章 - 6,  评论 - 20,  阅读 - 10万

由于wx.login的调用次数有限制,有些业务逻辑必须要登录获取到openid,所以想到如下解决方法

解决方法:

1.app.js种实现统一的登录方法,再有需要用到的地方调用一次就可以,如有已经调用过了的就直接读取openid。

复制代码
App({
  /**
  * 定义全局变量
  */
  globalData: {
    openid: '', //用户openid
  },
  onLaunch: function () {

  },
  
  /**
   * 登录获取openid
   */
  Login: function(){
    var that = this;
    return new Promise(function(resolve, reject){
      var globalData_openid = that.globalData.openid;
      console.log(!globalData_openid);
      if(!globalData_openid)
      {
        wx.login({
          success: function(res) {
            //console.log(res.code)
            // 发送 res.code 到后台换取 openId, unionId
            let jsCode = res.code;
            wx.request({
              url: 'https://*****/JsCode2Session', //仅为示例,并非真实的接口地址
              data: {
                js_code: jsCode
              },
              method:'GET',
              header: {
                'content-type': 'application/json' // 默认值
              },
              success (res) {
                console.log(res.data)
                var openid = res.data.openid;
                //获取用户信息成功
                that.globalData.openid = openid;
                //console.log(that.globalData.openid);
                wx.setStorageSync('openid', openid);
                resolve(res.data)
              },
              fail (res) {
                console.log(res)
              },
              complete (res) {
                console.log(res)
              }
            })
          }
        });
      }
      else
      {
        var res = {
          openid:globalData_openid,
        }
        resolve(res);
      }
    })
  }
})
复制代码

2.页面js的调用方法代码

复制代码
const app = getApp()

Page({
  data: {},
  onLoad() {  
    var taht = this;
    //这里需要录openid
    app.Login().then(function(res){ 
       if(res)
       {
            let openid=res.openid; 
            //这里写你使用的逻辑代码
       }
    });
  }
})
复制代码

以上基本实现了我所想要的,如果已经获取到openid了,就直接使用globalData中参数openid,就不需要通过wx.login去获取了,从而避免了多次调用wx.login。

posted on   £冷☆月№  阅读(1150)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示