微信小程序前端获取openid

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_38891150/article/details/85256076

页面

<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>

  <view>
    取得的openid为:{{openid}}
  </view>
</view>

js,这是核心代码而已

// 获取openid
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              console.log("存在code")
            }
          });
          var appid = "wwwwwwwwwww"        //这里是我的appid,需要改成你自己的
          var secret = "qqqqqqqqqqqqqqqqqqqqqqqq"    //密钥也要改成你自己的
          var openid = ""
          var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + res.code + '&grant_type=authorization_code';
          wx.request({
            url: l,
            data: {},
            method: 'GET', 
            success: function (res) {
              var obj = {};
              obj.openid = res.data.openid;
              console.log("取得的openid==" + res.data.openid);
              that.setData({
                openid: obj.openid
              })
              obj.expires_in = Date.now() + res.data.expires_in;
            }
          });
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    });

效果图:

 

js全部代码:

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    openid: '',
    message: '',
  },

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  
  onLoad: function () {
    var that = this
    console.log("林");
    console.log("-"+app.globalData.quanju);
    
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    // 获取openid
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.getUserInfo({
            success: function (res) {
              console.log("存在code")
            }
          });
          var appid = "wxc55158faad3e366a"
          var secret = "f38f654411e153673ff4a473f1ccefd0"
          var openid = ""
          var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + res.code + '&grant_type=authorization_code';
          wx.request({
            url: l,
            data: {},
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT  
            // header: {}, // 设置请求的 header  
            success: function (res) {
              var obj = {};
              obj.openid = res.data.openid;
              console.log("取得的openid==" + res.data.openid);
              
              that.setData({
                openid: obj.openid
              })

              obj.expires_in = Date.now() + res.data.expires_in;
              // console.log(obj);
              // wx.setStorageSync('user', obj);//存储openid  
            }
          });
        } else {
          console.log('获取用户登录态失败!' + res.errMsg)
        }
      }
    });


    //获取登录用户的code
    // wx.login({
    //   success(res){
    //     if(res.code){
    //       console.log("当前code存在")
    //       //发送code
    //       wx.request({
    //         url: 'http://localhost:8080/sendOpenid',
    //         data:{
    //           code:res.code
    //         }
    //       })
    //     }
    //     else{
    //       console.log('登录失败!' + res.errMsg)
    //     }
    //   }
    // })


  },
  
  getUserInfo: function(e) {
    console.log(e)
    console.log("---");
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

 

展开阅读全文

没有更多推荐了,返回首页