微信小程序学习笔记(五)登录API、获取用户信息

版权声明:感谢转载,转载请注明出处。 https://blog.csdn.net/msllws/article/details/82881758

上一篇:微信小程序学习笔记(四)

【小程序登录】wx.login()

app.js:

App({
  onLaunch: function () {
    // 登录
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'https://www.msllws.top/delcode.php',
            data: {
              code: res.code
            }
          })
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    });
  }
})

初始化后得到了临时登录凭证code,使用wx.request()发送code,请求后台接口获取【会话密钥session_key】和【用户唯一标识openid】,满足UnionID下发条件时还可以获得【用户在开放平台的唯一标识符unionid】。

后台接收code的接口delcode.php:

<?php 
    $code = $_GET['code'];
    $appid = 'wx1aebd07bdcf596b8';
    $secret = '9ee8211007b81efd8c11d7d82d3b8658';
    $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
    $res = file_get_contents($url);

    //(省略业务逻辑:保存返回结果中的openid与用户userid关联......)

    echo $res;

 请求返回结果:

(unionid需要小程序绑定已认证的微信开放平台才可以获得)

【获取用户信息】wx.getUserInfo()

首先借助button来授权登录,login.wxml:

<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>

<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
<view wx:else>请升级微信版本</view>

login.js如下:

Page({
  data: {
    //判断getUserInfo是否在当前版本可用
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  }
})

首次点击button按钮提示微信授权,允许后调用bindGetUserInfo函数打印获得的用户信息

此时修改login.js如下,使用wx.getSetting()获得用户信息 

(调用wx.getUserInfo()之前需要调用wx.getSetting()获取用户当前的授权状态,返回结果中如果包含【scope.userInfo】,说明用户已对用户信息进行授权,可以直接调用wx.getUserInfo()获取用户信息)

Page({
  data: {
    //判断getUserInfo是否在当前版本可用
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,直接调用getUserInfo获取用户信息
          wx.getUserInfo({
            success: function (res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  }
})

重新编译,页面加载获得同上用户信息:

此时再点击button按钮不再提示授权确认信息。 


下一篇:微信小程序学习笔记(六)

猜你喜欢

转载自blog.csdn.net/msllws/article/details/82881758
今日推荐