Mini Program Login & Authorization & Obtain User Information

a login

The timing diagram is as follows:

wx.login()

get js_code

Sample code:

App({

  onLaunch: function() {

    wx.login({

      success: function(res) {

        if (res.code) {

          //EVERYTHING

        } else {

          console.log('Failed to get user login status!' + res.errMsg)

        }

      }

    });

  }

})

code for session_key

interface address:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

Request parameters:

parameter Required illustrate
appid Yes Mini Program Unique ID
secret Yes applet app secret
js_code Yes code obtained when logging in
grant_type Yes Fill in as authorization_code

Return parameter:

parameter illustrate
openid User unique ID
session_key session key
unions The user's unique identifier on the open platform. This field returns only when certain conditions are met. For details, please refer to the description of the UnionID mechanism.


wx.checkSession

Check whether the current user login status is valid

wx.checkSession({

  success: function(){

    //session has not expired and is valid for this life cycle

  },

  fail: function(){

    //login status expired

    wx.login() //re-login

    ....

  }

})

Two authorization

Some interfaces can only be called after obtaining user authorization and consent. When this type of interface is called:

  • If the user has not accepted or rejected this permission, a pop-up window will ask the user, and the user can call the interface only after clicking agree;
  • If the user is authorized, the interface can be called directly;
  • If the user has refused authorization, the pop-up window will not appear in a short period of time, but directly enter the interface fail callback. Developers are requested to be compatible with scenarios where users refuse authorization.

Developers can use  wx.getSetting  to get the user's current authorization status.

wx.getSetting({

  success: (res) => {

    /*

     * res.authSetting = {

     *   "scope.userInfo": true,

     *   "scope.userLocation": true

     * }

     */

  }

})

Users can control the authorization status of the applet in the applet setting interface (upper right corner - about - upper right corner - settings).

The developer can call  wx.openSetting  to open the setting interface and guide the user to open the authorization.

wx.openSetting({

  success: (res) => {

    /*

     * res.authSetting = {

     *   "scope.userInfo": true,

     *   "scope.userLocation": true

     * }

     */

  }

})

Authorize

Initiate an authorization request to the user in advance. Immediately after the call, a pop-up window will ask the user whether he agrees to authorize the applet to use a certain function or obtain some data of the user, but the corresponding interface will not be actually called. If the user has agreed to the authorization before, the pop-up window will not appear, and success will be returned directly.

OBJECT parameter description:

parameter name Types of Required illustrate
scope String Yes The scope for which permissions need to be obtained, see the  scope list for details
success Function no Callback function for successful interface call
fail Function no Callback function for interface call failure
complete Function no The callback function of the end of the interface call (the call will be executed if it succeeds or fails)

Description of parameters returned by success:

parameter name Types of illustrate
errMsg String call result

// First check whether the user has authorized the scope "scope.record"

wx.getSetting({

    success(res) {

        if (!res.authSetting['scope.record']) {

            wx.authorize({

                scope: 'scope.record',

                success() {

                    // The user has agreed to the applet to use the recording function, and subsequent calls to the wx.startRecord interface will not pop up to ask

                    wx.startRecord()

                }

            })

        }

    }

})

 

scope Corresponding interface describe
scope.userInfo wx.getUserInfo User Info
scope.userLocation wx.getLocation, wx.chooseLocation Geographical location
scope.address wx.chooseAddress mailing address
scope.invoiceTitle wx.chooseInvoiceTitle Invoice
scope.werun wx.getWeRunData WeChat exercise steps
scope.record wx.startRecord recording function
scope.writePhotosAlbum wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum save into the album
scope.camera   camera

 

3. Obtain user information

1.wx.getUserInfo(OBJECT)

To obtain user information, you need to call  the wx.login  interface first when withCredentials is true.

User authorization is required  scope.userInfo

OBJECT parameter description:

parameter name Types of Required illustrate Minimum version
withCredentials Boolean no Whether to bring login information 1.1.0
lang String no Specify the language for returning user information, zh_CN Simplified Chinese, zh_TW Traditional Chinese, en English. Default is en. 1.3.0
success Function no Callback function for successful interface call  
fail Function no Callback function for interface call failure  
complete Function no The callback function of the end of the interface call (the call will be executed if it succeeds or fails)  

Note: When withCredentials is true, it is required that wx.login has been called before and the login status has not expired, and the returned data will contain sensitive information such as encryptedData, iv; when withCredentials is false, no login status is required, and the returned The data does not contain encryptedData, iv and other sensitive information.

Description of parameters returned by success:

parameter Types of illustrate
userInfo OBJECT User information object, does not contain sensitive information such as openid
rawData String Raw data string excluding sensitive information, used to calculate the signature.
signature String Use sha1 ( rawData + sessionkey ) to get a string for verifying user information, refer to the document  signature .
encryptedData String Encrypted data with full user information including sensitive data
iv String Initial vector for encryption algorithm

UserInfo parameter description:

parameter Types of illustrate
nickName String User's Nickname
avatarUrl String User avatar, the last value represents the size of the square avatar (there are optional values ​​of 0, 46, 64, 96, 132, and 0 represents a 640*640 square avatar). This item is empty when the user has no avatar. If the user changes the avatar, the original avatar URL will be invalid.
gender String The gender of the user, a value of 1 is male, a value of 2 is female, and a value of 0 is unknown
city String User's city
province String User's province
country String User country
language String User's language, Simplified Chinese is zh_CN

Sample code:

wx.getUserInfo({

success: function(res) {

var userInfo = res.userInfo

var nickName = userInfo.nickName

var avatarUrl = userInfo.avatarUrl

var gender = userInfo.gender //性别 0:未知、1:男、2:女

var province = userInfo.province

var city = userInfo.city

var country = userInfo.country

}

})

 

encryptedData 解密后为以下 json 结构

{

    "openId": "OPENID",

    "nickName": "NICKNAME",

    "gender": GENDER,

    "city": "CITY",

    "province": "PROVINCE",

    "country": "COUNTRY",

    "avatarUrl": "AVATARURL",

    "unionId": "UNIONID",

    "watermark":

    {

        "appid":"APPID",

    "timestamp":TIMESTAMP

    }

}

2.getPhoneNumber(OBJECT)

获取微信用户绑定的手机号,需先调用login接口。

因为需要用户主动触发才能发起获取手机号接口,所以该功能不由 API 来调用,需用 <button> 组件的点击来触发。

注意:目前该接口针对非个人开发者,且完成了认证的小程序开放。需谨慎使用,若用户举报较多或被发现在不必要场景下使用,微信有权永久回收该小程序的该接口权限。

需要将 <button> 组件 open-type 的值设置为 getPhoneNumber,当用户点击并同意之后,可以通过 bindgetphonenumber 事件回调获取到微信服务器返回的加密数据, 然后在第三方服务端结合 session_key 以及 app_id 进行解密获取手机号。

 

在回调中调用 wx.login 登录,可能会刷新登录态。此时服务器使用 code 换取的 sessionKey 不是加密时使用的 sessionKey,导致解密失败。建议开发者提前进行 login;或者在回调中先使用 checkSession 进行登录态检查,避免 login 刷新登录态。

 

代码示例:

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> </butto>

Page({

getPhoneNumber: function(e) {

console.log(e.detail.errMsg)

console.log(e.detail.iv)

console.log(e.detail.encryptedData)

}

})

参数 类型 说明
encryptedData String 包括敏感数据在内的完整用户信息的加密数据
iv String 加密算法的初始向量

 

encryptedData 解密后为以下 json 结构

{

"phoneNumber": "13580006666",

"purePhoneNumber": "13580006666",

"countryCode": "86",

"watermark":

{

"appid":"APPID",

"timestamp":TIMESTAMP

}

}

参数 类型 说明
phoneNumber String 用户绑定的手机号(国外手机号会有区号)
purePhoneNumber String 没有区号的手机号
countryCode String 区号

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325318051&siteId=291194637