WeChat Mini Program API Login
wx.login(OBJECT)
Call the interface to obtain the login credentials (code) and then exchange the user login status information, including the user's unique identification (openid) and the session key (session_key) for this login. Encryption and decryption of user data communication needs to rely on the session key to complete.
OBJECT parameter description:
success Return parameter description:
Sample code:
//app.js App({ onLaunch: function() { wx.login({ success: function(res) { if (res.code) { //发起网络请求 wx.request({ url: 'https://test.com/onLogin', data: { code: res.code } }) } else { console.log('获取用户登录态失败!' + res.errMsg) } } }); } })
code in exchange for session_key
This is an HTTPS interface. The developer server uses login credential code to obtain session_key and openid. Where session_key is the key used to encrypt and sign user data. For its own application security, session_key should not be transmitted over the network.
Interface address:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
Request parameters:
Return parameters:
Parameters | Description |
---|---|
openid | Unique user identification |
session_key | Session key |
Return instructions:
//正常返回的JSON数据包 { "openid": "OPENID", "session_key": "SESSIONKEY" } //错误时返回JSON数据包(示例为Code无效) { "errcode": 40029, "errmsg": "invalid code" }
Login state maintenance
Acquired through wx.login()
After reaching the user login state, the login state needs to be maintained. Developers should note that they should not directly use fields such as session_key and openid as user identifiers or session identifiers , but should dispatch a session login state by themselves (please refer to the login sequence diagram). For sessions generated by developers themselves, their security should be ensured and long expiration times should not be set. After the session is dispatched to the mini program client, it can be stored in storage for subsequent communication.
Login sequence diagram
wx.checkSession(OBJECT)
Check login Whether the status has expired
Sample code:
wx.checkSession({ success: function(){ //登录态未过期 }, fail: function(){ //登录态过期 wx.login() } })
Bug & Tip
bug
:iOS/Android
6.3.30
, an exception will occur when calling wx.login in App.onLaunch;