Landing and authorization # applets

1. applet Log

Login Official Description

Applets can easily access user identity identification provided by micro-channel micro-channel official sign-on capabilities provided by the user to quickly build systems within the applet.

Login process timing

Description:

  1. Call wx.login () to obtain temporary registration certificate code , and the developers back to the server.
  2. Call code2Session interfaces, in exchange for the user to uniquely identify OpenID and session key session_key .

After the developer server may generate a custom login state according to the user identifier for identifying a user when the front end of the subsequent interactive service logic.

note:

  1. The session key session_keyis user data encrypted signature key. In order to apply their own data security, server developers should not be a session key issued to a small program, should not be provided outside the key .
  2. Temporary registration certificate code can only be used once

Brothers, is not very simple, a look will be? I know your answer below, but do not panic, we speak in detail each step

After the rear end of the applet executed wx.login callback function code can get on the map, then this program code to us rear end, the rear end to get the code, you can get request code2Session interfaces with openid and session_key, openid uniquely identifies the user in the micro channel, we can put the two values ​​(Val) kept up, and then returns a key (key) to the end of the applet, the applet request next time we rear end, to bring the key, we will be able to find this val, you can, so put the sign in the well.

1.1wx.login(Object object)

Call Interface for login credentials (code). Further exchange credentials by the login state of the user, including a user's unique identification (OpenID) and session key (session_key of), etc. The login. Encryption and decryption of user data communications need to rely on the completion of the session key. More detailed usage applet login .

parameter

Object object

Attributes Types of Defaults Mandatory Explanation Minimum version
timeout number no Timeout time in ms 1.9.90
success function no Interface call success callback function
fail function no Interface calls the failure callback function
complete function no Interface calls the end of the callback function (call succeeds, the failure will be executed)

object.success callback function

parameter

Object res

Attributes Types of Explanation
code string User login credentials (valid for five minutes). Developers need to call the server back-end developer code2Session , use code such as information exchange openid and session_key

Sample Code

wx.login({
  success(res) {
    if (res.code) {
      // 发起网络请求
      wx.request({
        url: 'https://test.com/onLogin',
        data: {
          code: res.code
        },
        success: function (res) {
              wx.setStorageSync('login_key', res.data.data.login_key);
        }
      })
    } else {
      console.log('登录失败!' + res.errMsg)
    }
  }
})

1.2code2Session

This interface shall call on the server side, a detailed description see server-side API .

Login credentials check. By wx.login () after the interface to obtain temporary registration certificate server code spread developers call this interface to complete the login process. More detailed usage applet login .

Request address

GET https://api.weixin.qq.com/sns/jscode2sessionappid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

Request parameter

Attributes Types of Defaults Mandatory Explanation
appid string Yes Applet appId
secret string Yes Applet appSecret
js_code string Yes Log in getting the code
grant_type string Yes Authorization type, where just fill authorization_code

return value

Object

Packet returned JSON

Attributes Types of Explanation
openid string Uniquely identifies the user
session_key string Session key
unionid string User a unique identifier of an open platform, will return while meeting UnionID issued conditions, see UnionID mechanism explained .
errcode number error code
errmsg string Error Messages

Errcode of legal values

value Explanation
-1 The system is busy at this time, please try again later developers
0 Request successful
40029 code invalid
45011 Frequency limit, each user 100 beats per minute

Finished Login above, we are not yet used in the above session_key? This is the authorized user when used, is used to decrypt the user data, but also decrypt? Yes, you heard it right, do not panic, here explain to you

2. The micro-channel to obtain the user authorization letter

Obtaining user information rear micro flow channels

Official micro letter: I forgot to tell you, session_key will expire, yes, yes that is so pit father.

My reply: I am the head of iron, I do not care session_key expired, what kind of consequences it?

Micro-letter official: I'm sorry, you do not iron head, you can not back-end processes user authorization data, and asked you gas is not gas?

My reply: Yes, you Niubi, I can receive you session_key expired, but you have to tell me how he is the judge expired, right? How to obtain a new session_key, right?

Official micro letter: I still have to come in accordance with the requirements? You look so pathetic, I tell you, it is out of date with wx.checkSession determine if expired login to rewrite it! Obtain a new code, in the back end to get a new request code2Session session_key

My reply: Yes, thank you sb

Session_key judge has not expired

2.1wx.checkSession(Object object)

Check the login state has expired.

Login user interfaces obtained by wx.login state has a certain timeliness. The more user recently used a small program, the more likely a user login state failure. On the other hand if you have been using applets, the user login state remains in effect. DETAILED aging logical channel maintained by the micro, transparent to the developer. Developers only need to call wx.checkSession interface detects the current user login state is valid.

After logging in state expired developer can then call wx.login get a new user login state. Description of the current call is successful session_key not expired, the call fails explanation session_key has expired. More detailed usage applet login .

parameter

Object object

Attributes Types of Defaults Mandatory Explanation
success function no Interface call success callback function
fail function no Interface calls the failure callback function
complete function no Interface calls the end of the callback function (call succeeds, the failure will be executed)

Sample Code

wx.checkSession({
  success() {
    // session_key 未过期,并且在本生命周期一直有效
  },
  fail() {
    // session_key 已经失效,需要重新执行登录流程
    wx.login() // 重新登录
  }
})

Official micro letter: Do you want to get the information? Ha I tell you, if you want to get, then, to go through the user's consent.

My reply: sb, how do I know whether he had authorized it? If not authorized, how do I let him authorization?

** official micro letter: Hello, you can call wx.getSetting to determine whether the user authorization, if not authorized, you let him click on the button, invoking authorization page. * After a user clicks on consent, you can call wx.getUserInfo interface to obtain the data **

My reply: Damn, how much trouble?

Micro-letter official: I'm sorry, big brother, there is no way ah, we want to protect the user's information security ah

My reply: Oh

2.2wx.getSetting(Object object)

Infrastructure Library 1.2.0 started to support low version to be made compatible with the process .

Get the user's current settings. Applet has requested permission to the user through the return value will appear .

parameter

Object object

Attributes Types of Defaults Mandatory Explanation
success function no Interface call success callback function
fail function no Interface calls the failure callback function
complete function no Interface calls the end of the callback function (call succeeds, the failure will be executed)

object.success callback function

parameter

Object res

Attributes Types of Explanation
authSetting AuthSetting User authorization result

Sample Code

wx.getSetting({
  success(res) {
    console.log(res.authSetting)
    //部分结果,如果为true,则表示该用户对这项权限以及授权,如果没有授权,我们这需要通过button按钮让用户授权
    // res.authSetting = {
    //   "scope.userInfo": true,
    //   "scope.userLocation": true
    // }
  }
})

Precautions

  1. wx.authorize({scope: "scope.userInfo"}), The authorization does not pop up a window, use <button_open-type="getUserInfo">
  2. It requires authorization scope.userLocationmust when configured location Instructions for use .

Official micro letter: When you call the small end of the program when we wx.getUserInfo, we will return to the basic information you use.

My reply: What are the basic information, which is sensitive information? How I get the back end of it?

微信官方:比如openid这些,大佬,你又两种方法,第一:你可以将这些基本信息传到后端,第二: 你可以讲getUserInfo中的 iv,encryptedData传给后端解密,机密后就能获取到用户的敏感信息了

我的回复:好的,我后端怎么解密呢?用什么解密呢?

微信官方:你登入的时候不是,后端不是存了session_key吗?加上这些数据,就可以解密了

我的回复:哦

2.3wx.getUserInfo(Object object)

获取用户信息

调用前需要 用户授权 scope.userInfo。

获取用户信息。

参数

Object object

属性 类型 默认值 必填 说明
withCredentials boolean 是否带上登录态信息。当 withCredentials 为 true 时,要求此前有调用过 wx.login 且登录态尚未过期,此时返回的数据会包含 encryptedData, iv 等敏感信息;当 withCredentials 为 false 时,不要求有登录态,返回的数据不包含 encryptedData, iv 等敏感信息。
lang string en 显示用户信息的语言
success function 接口调用成功的回调函数
fail function 接口调用失败的回调函数
complete function 接口调用结束的回调函数(调用成功、失败都会执行)

object.lang 的合法值

说明
en 英文
zh_CN 简体中文
zh_TW 繁体中文

object.success 回调函数

参数

Object res

属性 类型 说明
userInfo UserInfo 用户信息对象,不包含 openid 等敏感信息
rawData string 不包括敏感信息的原始数据字符串,用于计算签名
signature string 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,详见 用户数据的签名验证和加解密
encryptedData string 包括敏感数据在内的完整用户信息的加密数据,详见 用户数据的签名验证和加解密
iv string 加密算法的初始向量,详见 用户数据的签名验证和加解密

接口调整说明

在用户未授权过的情况下调用此接口,将不再出现授权弹窗,会直接进入 fail 回调(详见《公告》)。在用户已授权的情况下调用此接口,可成功获取用户信息。

示例代码

// 必须是在用户已经授权的情况下调用
wx.getUserInfo({
  success(res) {
    const userInfo = res.userInfo
    const nickName = userInfo.nickName
    const avatarUrl = userInfo.avatarUrl
    const gender = userInfo.gender // 性别 0:未知、1:男、2:女
    const province = userInfo.province
    const city = userInfo.city
    const 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
  }
}

示例代码

<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button
  wx:if="{{canIUse}}"
  open-type="getUserInfo"
  bindgetuserinfo="bindGetUserInfo"
>
  授权登录
</button>
<view wx:else>请升级微信版本</view>

Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad() {
    // 查看是否授权
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
               wx.request({
                  url: url,
                  data: {
                    'iv': res.iv,
                    'encryptedData': res.encryptedData,
                    'login_key':登入标识
                  },
                  method: "POST",
                  header: {
                    'content-type': 'application/json' // 默认值
                  },
                  success: function (res) {
                    //解密后数据
                    console.log(res);
                  }
                });
            }
          })
        }
      }
    })
  },
  bindGetUserInfo(e) {
    console.log(e.detail.userInfo)
  }
})

叫你解密大法

2.4开放数据校验与解密

小程序可以通过各种前端接口获取微信提供的开放数据。考虑到开发者服务器也需要获取这些开放数据,微信会对这些数据做签名和加密处理。开发者后台拿到开放数据后可以对数据进行校验签名和解密,来保证数据不被篡改。

img

签名校验以及数据加解密涉及用户的会话密钥 session_key。 开发者应该事先通过 wx.login 登录流程获取会话密钥 session_key 并保存在服务器。为了数据不被篡改,开发者不应该把 session_key 传到小程序客户端等服务器外的环境。

数据签名校验

为了确保开放接口返回用户数据的安全性,微信会对明文数据进行签名。开发者可以根据业务需要对数据包进行签名校验,确保数据的完整性。

  1. 通过调用接口(如 wx.getUserInfo)获取数据时,接口会同时返回 rawData、signature,其中 signature = sha1( rawData + session_key )
  2. 开发者将 signature、rawData 发送到开发者服务器进行校验。服务器利用用户对应的 session_key 使用相同的算法计算出签名 signature2 ,比对 signature 与 signature2 即可校验数据的完整性。

如 wx.getUserInfo的数据校验:

接口返回的rawData:

{
  "nickName": "Band",
  "gender": 1,
  "language": "zh_CN",
  "city": "Guangzhou",
  "province": "Guangdong",
  "country": "CN",
  "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0"
}

用户的 session-key:

HyVFkGl5F5OQWJZZaNzBBg==

用于签名的字符串为:

{"nickName":"Band","gender":1,"language":"zh_CN","city":"Guangzhou","province":"Guangdong","country":"CN","avatarUrl":"http://wx.qlogo.cn/mmopen/vi_32/1vZvI39NWFQ9XM4LtQpFrQJ1xlgZxx3w7bQxKARol6503Iuswjjn6nIGBiaycAjAtpujxyzYsrztuuICqIM5ibXQ/0"}HyVFkGl5F5OQWJZZaNzBBg==

使用sha1得到的结果为

75e81ceda165f4ffa64f4068af58c64b8f54b88c

加密数据解密算法

接口如果涉及敏感数据(如wx.getUserInfo当中的 openId 和 unionId),接口的明文内容将不包含这些敏感数据。开发者如需要获取敏感数据,需要对接口返回的加密数据(encryptedData) 进行对称解密。 解密算法如下:

  1. 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
  2. 对称解密的目标密文为 Base64_Decode(encryptedData)。
  3. 对称解密秘钥 aeskey = Base64_Decode(session_key), aeskey 是16字节。
  4. 对称解密算法初始向量 为Base64_Decode(iv),其中iv由数据接口返回。

微信官方提供了多种编程语言的示例代码(点击下载)。每种语言类型的接口名字均一致。调用方式可以参照示例。

另外,为了应用能校验数据的有效性,会在敏感数据加上数据水印( watermark )

watermark参数说明:

参数 类型 说明
appid String 敏感数据归属 appId,开发者可校验此参数与自身 appId 是否一致
timestamp Int 敏感数据获取的时间戳, 开发者可以用于数据时效性校验

如接口 wx.getUserInfo 敏感数据当中的 watermark:

{
  "openId": "OPENID",
  "nickName": "NICKNAME",
  "gender": GENDER,
  "city": "CITY",
  "province": "PROVINCE",
  "country": "COUNTRY",
  "avatarUrl": "AVATARURL",
  "unionId": "UNIONID",
  "watermark": {
    "appid": "APPID",
    "timestamp": TIMESTAMP
  }
}

注:

  1. 解密后得到的json数据根据需求可能会增加新的字段,旧字段不会改变和删减,开发者需要预留足够的空间

会话密钥 session_key 有效性

开发者如果遇到因为 session_key 不正确而校验签名失败或解密失败,请关注下面几个与 session_key 有关的注意事项。

  1. wx.login 调用时,用户的 session_key 可能会被更新而致使旧 session_key 失效(刷新机制存在最短周期,如果同一个用户短时间内多次调用 wx.login,并非每次调用都导致 session_key 刷新)。开发者应该在明确需要重新登录时才调用 wx.login,及时通过 code2Session 接口更新服务器存储的 session_key。
  2. 微信不会把 session_key 的有效期告知开发者。我们会根据用户使用小程序的行为对 session_key 进行续期。用户越频繁使用小程序,session_key 有效期越长。
  3. 开发者在 session_key 失效时,可以通过重新执行登录流程获取有效的 session_key。使用接口 wx.checkSession可以校验 session_key 是否有效,从而避免小程序反复执行登录流程。
  4. 当开发者在实现自定义登录态时,可以考虑以 session_key 有效期作为自身登录态有效期,也可以实现自定义的时效性策略。

Guess you like

Origin www.cnblogs.com/zhuyuanying123--/p/11580344.html