小程序获取用户openid,code

https://developers.weixin.qq.com/community/develop/doc/0004e229464d78c1d557ed5e359404

https://blog.csdn.net/weixin_43055905/article/details/82222668

项目代码 //通过code生成token      code不可反复使用,只能使用一次

token有缓存时间 到时间重新获取
onLoad: function () {
    this.getCode();
  },
  getCode: function () {
    let that = this;
    let getovertime = wx.getStorageSync("overtime");//拿到过期时间
    let nowtime = Date.parse(new Date()); //现在时间
        nowtime = nowtime/1000;
    if (getovertime < nowtime){ //过期
      console.log('过期了')
      wx.login({
        success: function (res) {
          app.globalData.code = res.code;//cede储存到全局
          wx.removeStorageSync('token')
          wx.setStorageSync('token', 'thisistoken')
          let overtime = nowtime + 3600;// 设置过期时间2小时
          wx.setStorageSync("overtime", overtime);
        }
      })
      that.index();
    }else{
      that.index();
    } 
  },
  index(){
    console.log('this is index')
  },



getCode(){
    let token = wx.getStorageSync('token');
    if(token){
    console.log("token存在.  进行校验.");
    this.Getindex();
    }else{
    console.log("token不存在,正在重新拿token..");
    wx.login({
      success: function (res) {
        console.log(res.code) //code
        //发送code
        BaseApi.save_update_openid({ 
          code: res.code
        }).then((res) => {
          console.log(res);
          if (res.data.status == 1) {
            let datas = res.data.data;
            wx.setStorageSync('open_id', datas.open_id)
            app.globalData.open_id = datas.open_id //设置全局
          }
        }, (err) => {

        })
      }
    })
    }
}
const app = getApp();
//页面一加载获取code
  getCode: function () {
    let that = this; 
    wx.login({
      success: function (res) {
        console.log(res.code) //code
        app.globalData.code = res.code;//cede储存到全局
        //发送code
        BaseApi.save_update_openid({ 
          code: res.code
        }).then((res) => {
          console.log(res);
          if (res.data.status == 1) {
            let datas = res.data.data;
            wx.setStorageSync('open_id', datas.open_id)
            app.globalData.open_id = datas.open_id //设置全局
          }
        }, (err) => {

        })
      }
    })
  },
App({
  globalData: {
    openid:'',
    'appid': "wx93d4137aeaafa1a4",
    'secret': "fb96f74d42872b0ed67312eccd4bf868",
  },
})
//user.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOpenid();
 }

  
})

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值