小程序接口学习—开发接口

一、登录

https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html

1、步骤

(1)调用接口wx.login(OBJECT)获取登录凭证(code)。

(2)再将code传递给第三方服务器,第三方服务器请求微信服务器https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

(3)成功微信服务器返回openid(用户唯一标识),session_key(会话密钥),unionid(用户在开放平台的唯一标识符),失败微信服务器{ "errcode": 40029,"errmsg": "invalid code"}

(4)登陆状态验证:这里的session是第三方服务器生产的。

wx.checkSession({
  success: function(){
    //session 未过期,并且在本生命周期一直有效
  },
  fail: function(){
    //登录态过期
    wx.login() //重新登录
    ....
  }
})

二、提前向用户发起授权请求


// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
wx.getSetting
({success(res) {
        if (!res.authSetting['scope.record']) {
            wx.authorize({
                scope: 'scope.record',
                success() {
                    // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
                    wx.startRecord()
                }
            })
        }
    }
})

三、获取用户信息

    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo;
              console.log(res.userInfo);
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

猜你喜欢

转载自my.oschina.net/u/2427561/blog/1606382