zoukankan      html  css  js  c++  java
  • 微信小程序获取当前用户的openid

    获取openid看了些网上的文章没获取到也许是我get到找到了一篇借鉴然后自己也搞出来了

    首先要去小程序接口文档看以下这几个接口

    function wx.setStorageSync(key: string): void

    将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。

    wx.request({})

    function wx.setStorageSync(key: string): void //此接口可以设置openid到缓存中

    将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。

    现在来上代码........................

    首先创建一个环境单击按钮获取当前用户的openid

    test.wxml

    <text>{{openid}}</text>
    <button type="default" bindtap="open">获取openid</button>

    js点击事件获取当前用户的openid

    test.js

    Page({
    
      /**
       * 页面的初始数据
       */
      data: {
        openid:''
      },
      open:function(){
        wx.login({
          success:function(res){
            var that = this;
            var header = {
              'content-type':'application/x-www-form-urlencoded',
              'token': wx.getStorageSync('token')//读取cookie 拿到登录之后异步保存的token值
            };
            if (res.code) {
              console.log(res.code);
              wx.request({//getOpenid
                url: 'https://api.weixin.qq.com/sns/jscode2session',
                  data: {
                    appid: '***************', //AppID
                    secret: '*******************',//secret密钥
                    grant_type: 'authorization_code',
                    js_code: res.code
                  },
               method: 'GET',
              header: header,
                success: function (res) {
                  var openid = res.data.openid; //登录之后返回的openid
                  // this.setData({
                  //   openid: res.data.openid
                  // });
                  console.log(openid+'我的openid')
                  wx.setStorageSync('openid', openid) //储存openid
                  if (openid != null & openid != undefined) {
                    wx.getUserInfo({
                      success: function (res) {
                      
                      },
                      fail: function (res) {
                        //console.info('用户拒绝授权');
                      }
                    });  
                  }else{
                    console.info('获取用户openid失败');
                  }
                },
                fail: function (res) {
                  console.info('获取用户openid失败');
                  console.log(error);
                }
              })
            }
          }
        })
      }
    })
    

      效果只能在真机调试或者电脑模式下才能看出来,注意预览是看不出来的

  • 相关阅读:
    逼哥
    作业
    malloc的底层实现
    docker基本使用
    对mudo中noncopyable类的理解
    整理
    替换war包中的文件
    SpringMVC(1):SpringMVC入门
    MySQL(5):安装MySQL
    MySQL(4):卸载MySQL
  • 原文地址:https://www.cnblogs.com/wolf-shuai/p/12773565.html
Copyright © 2011-2022 走看看