# Web authorization
If a user visits a third-party web page in the WeChat client, Service Account can obtain basic information of the user through the WeChat web page authorization mechanism to implement business logic.
# I. Required reading before development
The web authorization process is divided into four steps:
- Guide the user to the authorization page
- Get the code in the callback page
- Exchange code for user authorization access_token (unlike access_token)
- Access user basic information via user authorization access_token and openid (UnionID mechanism is supported)
Before completing the authorization process, you need to read the following information carefully and master the basic background knowledge.
# 1. Applicable account
Web page authorization is only supported by authenticated Service Account. Other types of accounts cannot perform the authorization process.
# 2. Web authorization callbacks domain names
Before WeChat Service Account requests user web page authorization,Developers need to first go to the "Settings & Development - Account Settings - Function Settings" configuration options in the public platform to modify the "Web Authorized Domain Name."
Please note that this is the domain name (e.g.
www.qq.com
),Instead of URL, so do not add http:// and other protocol headers;
www.qq.com www.qq.com www.qq.com
Configure the page below this domain name in the futurehttp://www.qq.com/music.html
, http://www.qq.com/login.html
can be licensed.Buthttp://pay.qq.com
、http://music.qq.com
、http://qq.com
Web page authentication was not possible.
If the Service Account login is authorized to a third-party developer to manage it, there is no need to do any settings, and the third party can implement the web page authorization instead of the service number.
# 3. UnionID mechanism
Web page authorization to obtain user basic information follows the UnionID mechanism.If a developer has a need to unify user accounts between multiple Service Account or service numbers and Mobile App, they need to go to the WeChat open platform (open.weixin.qq.com) to bind service numbers before they can use the UnionID mechanism to meet these needs.
If the developer has multiple Mobile App, Website App and public accounts,You can distinguish the uniqueness of a user by obtaining the unionid in the user's basic information, because the unionid is the same for different applications (mobile, web, and public accounts) under the same WeChat open platform.
Quick Notes Formula:
微信用户 + 服务号appid = openid
微信用户 + 开放平台账号 = unionid
As long as Service Account AppID does not change, openid does not change.As long as the open platform account tied to the service number does not change, the unionid will not change.
# II. Jump to authorization link
# Constructing links
Developers should structure authorization links according to the following rules:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
The parameters are explained as follows:
parameter | Do I have to? | Introductions |
---|---|---|
appid | yes | Unique identifier for Service Account |
redirect_uri | yes | Redirect callback link address after authorization, use urlEncode to process the link |
response_type | yes | Return type, please fill in code |
scope | yes | Apply the authorization scope, snsapi_base (does not pop up the approval page, but jumps directly to get only the user openid), snappi_userinfo (pops up the permission page, and can get nickname, gender, and location through openid). And, even in the absence of attention, the user's information can be obtained as long as the user is authorized. |
state | no | Redirect with the state parameter, the developer can fill in a zA-Z0-9 parameter value, up to 128 bytes |
#wechat_redirect | yes | You must bring this parameter with you whether you open the page directly or when you do a page 302 redirect |
forcePopup | no | Enforcing this authorization requires a user's pop-up confirmation; Defaults to false; Note that this parameter does not take effect if the user hits the silent authorization logic in a special situation |
There are currently two scopes for web authorizations, which are:snsapi_base
andsnsapi_userinfo
,The explanation is as follows:
- Snsapi_base : Used to get the openid of the user entering the page, and silently authorizes and automatically jumps to the callback page.(Will not pop up information confirmation box, can only get user openid and other information, can not get nickname avatar)
- Snsapi_userinfo : Used to get basic user information.However, this authorization requires the user's manual consent.(Since the user has agreed, it is not necessary to rely on the user to pay attention to Service Account, you can obtain the user's basic information after authorization)
# Examples of links
Example that scope issnsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect
Example with scopesnsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx807d86fb6b3d4fd2&redirect_uri=http%3A%2F%2Fdevelopers.weixin.qq.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
# Launch a jump
Service Account After configuring the "Web Page Authorization Domain Name," in the configured authorization domain name page, jump to the authorization link page constructed by yourself.Among the more common are:
<a href="url">登录</a>
location.href = "url"
In conjunction with the business, you can directly judge a jump when a user interacts or when the page is initialized.
# Note
When jumping over authorization links, you should be aware of the following:
- If the prompt "this link cannot be accessed," please check whether the parameter is filled incorrectly and whether you have the authorization scope permission corresponding to the scope parameter.
- Because the security level of the authorization operation is high, WeChat performs orthogonal matching checks on the approval link when initiating an authorization request, and if the parameters of the link are not in the correct order, the accessibility page will not be accessible
- The jump callback redirect_uri should use the https link to ensure the security of the authorization code.
# III. Obtaining user authorization
When you dosnsapi_base
authorization, the client acquiesces consent.
When you dosnsapi_userinfo
authorization, there are two situations:
Situation 1: For a user who is already aware of Service Account, if the user enters the web authorization page of the service from the session or custom menu of the service, the user is silently authorized at this time, without the user giving a pop-up consent.
Situation 2: In other situations other than scenario 1, the new version of the WeChat client does some processing when makingsnsapi_userinfo
authorization.
When you use User Interaction (click the button) to jump to the authorization link, WeChat will pull up a pop-up window to confirm, as shown below:
When you directly jump on the authorization link without the user making any interaction, the page is solidified with the word "click to access the full page." WeChat Business scenarios where you directly authorize the page when you open it are not recommended.
If the user agrees to authorize, the page will jump to the link shown in theredirect_uri
parameter withcode
andstate
redirect_uri/?code=CODE&state=STATE。
Parameter explaination:
- Code : In exchange for a ticket access_token-END]], the code on each user authorization band will be different. The code can only be used once and will automatically expire without 5 minutes of unused use.
- State : The state parameter content directly with the authorization link is used to prevent ultra vires.
Of course, if the parameters for the authorization link are incorrect, the user will see an error prompt. There are currently the following errors, and you will need to adjust them according to the instructions.
Return code | Introductions |
---|---|
10003 | The redirect_uri domain name is not consistent with the background configuration |
10004 | This Service Account is blocked |
10005 | This Service Account does not have permissions for these scopes |
10006 | You must pay attention to this test number. |
10009 | This is too often. Please try again later. |
10010 | Scope cannot be empty |
10011 | Redirect_uri cannot be empty |
10012 | AppID cannot be empty |
10013 | State cannot be empty |
10015 | Service Account Not authorized Third Party Platform, please check authorization status |
10016 | Appid that does not support WeChat open platform, please use Service Account Appid |
# 4. In exchange for user authorization Token
After the callback page gets the code, it should be passed to the back-end server, and the back-end service needs to access the corresponding interface in exchange for user information and authorization Token.
# 4.1 Access to user authorization information interface
In exchange for the code is the user authorization access_token, its scope of authority is limited to the user's information access, can not call other interfaces outside of this document.The range of token information returned by this interface is available as follows:
In the case ofsnsapi_base
, no interface can and does not need to be called.
Insnsapi_userinfo
, you can perform to obtain user information and to refresh.Token 、 Check Token Validity
GET https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
This interface frequency limit: 50000 / min , the amount can refer to Guidelines for increasing the calling frequency of web authorized interface
Note: Because the Service Account secret and the obtained access_token security level are very high, they must be stored only on the server.Subsequent steps such as refreshing access_token and obtaining user information through access_token must also be initiated from the server.
Request parameters
parameter | Do I have to? | Introductions |
---|---|---|
appid | yes | Unique identifier for Service Account |
secret | yes | Service Account of appsecret |
code | yes | Fill in the code parameter obtained by the |
grant_type | yes | Enter as authorization_code |
Return Parameters
parameter | describe |
---|---|
access_token | Web page authorization interface invocation credentials. Note: This access_token is different from the underlying supported access_token |
expires_in | access_token Interface Call Credential Timeout, in seconds |
refresh_token | User refresh access_token |
openid | User-unique identifier. Note that when a user accesses a web page with a service number without following Service Account, it also generates an OpenID that is unique to the user and the service number |
scope | User authorized domains, separated by comma (,) |
is_snapshotuser | Whether it is a snapshot page virtual account, returns only if the user is a snapshot page virtual account, value 1 |
unionid | Uniform user identification (for an application under a WeChat open platform account, the unionid of the same user is unique), returns only when the scope is "snsapi_userinfo." |
Return an example
正确时返回内容:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"is_snapshotuser": 1,
"unionid": "UNIONID"
}
错误时返回内容:
{"errcode":40029,"errmsg":"invalid code"}
# 4.2 Refresh Authorization Token
Becauseaccess_token
has a short period of validity, whenaccess_token
is overdue, you can userefresh_token.
refreshes. Therefresh_token
is valid for 30 days. Whenrenew_token
expires, the user is required to reauthorize.
GET https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
This interface frequency limit: 50000 / min , the amount can refer to Guidelines for increasing the calling frequency of web authorized interface
Request parameters
parameter | Do I have to? | Introductions |
---|---|---|
appid | yes | Unique identifier for Service Account |
grant_type | yes | Fill in refresh_token |
refresh_token | yes | Fill in the refresh_token return parameter obtained by the user authorization information interface |
Return Parameters
parameter | describe |
---|---|
access_token | Web page authorization interface invocation credentials. Note: This access_token is different from the underlying supported access_token |
expires_in | access_token Interface Call Credential Timeout, in seconds |
refresh_token | User refresh access_token |
openid | User unique identifier |
scope | User authorized domains, separated by comma (,) |
Return an example
正确时返回内容:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
错误时返回内容:
{"errcode":-1,"errmsg":"invalid Token"}
# 4.3 Verify token validity
You can use this interface to verify that the above authorization access_token is valid
GET https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
Request parameters
parameter | describe |
---|---|
access_token | Web page authorization interface invocation credentials. Note: This access_token is different from the underlying supported access_token |
openid | The unique identifier of the user |
Return instructions
正确时返回内容:
{ "errcode":0,"errmsg":"ok"}
错误时返回内容:
{"errcode":-1,"errmsg":"invalid Token"}
# V. Pulling out user information
If the web page authorization scope issnsapi_userinfo
,Then the user information can be pulled byaccess_token
andopenid
.
GET https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
This interface frequency limit: 50000 / min , the amount can refer to Guidelines for increasing the calling frequency of web authorized interface
Request parameters
parameter | describe |
---|---|
access_token | Web page authorization interface invocation credentials. Note: This access_token is different from the underlying supported access_token |
openid | The unique identifier of the user |
lang | Back to country language version, zh_CN simplified, zh_TW traditional, en English |
Return Parameters
parameter | describe |
---|---|
openid | The unique identifier of the user |
nickname | User nickname |
sex | User's gender, a value of 1 is male, avalue of 2 is female, and a value 0 is unknown |
province | Provinces in which the user's profile was filled |
city | Cities populated by the average user's profile |
country | Countries, such as China for CN |
headimgurl | User avatar. The last value represents the square avatar size (there are values 0, 46, 64, 96, 132, and 0 represents 640\ * 640 square avatar). This item is empty when the user does not have a avatar.If the user changes the avatar, the original avatar URL will become invalid. |
privilege | User privilege information, json array, such as WeChat |
unionid | This field appears only after the user has bound Service Account to WeChat open platform account. |
Return an example
正确时返回内容:
{
"openid": "OPENID",
"nickname": NICKNAME,
"sex": 1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY",
"headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
错误时返回内容:
{"errcode":40003,"errmsg":" invalid openid "}
# VI. Changes in authorized user information
The platform recommends that developers configure server message push listening to facilitate access to relevant change time information in the first place, by checking the message push and guidance document.
In the user authorized information scenario, there are the following events:
1、 Authorizing user data changes: When some user data is at risk,The platform cleans up user data and notifies Service Account developers who have been authorized in the last 30 days via a message push server. We recommend that developers be aware of the incidents and proactively update or clean users' avatar and nicknames in a timely manner to reduce risk.
2、 Authorized user data withdrawal: When a user withdraws authorized information, the platform will notify the Service Account developer via the message push server, and ask the developer to take care to delete the user information in a timely manner.
3、 Authorized users complete logging out: When authorized users complete log out, the platform will notify the Service Account developer through the message push server, Please fulfill the corresponding personal information protection obligations in accordance with the law and in a timely manner to protect the rights and interests of users.
# Example of event push:
XML format
<xml>
<ToUserName><![CDATA[gh_870882ca4b1]]></ToUserName>
<FromUserName><![CDATA[owAqB1v0ahK_Xlc7GshIDdf2yf7E]]></FromUserName>
<CreateTime>1626857200</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[user_authorization_revoke]]></Event>
<OpenID><![CDATA[owAqB1nqaOYYWl0Ng484G2z5NIwU]]></OpenID>
<AppID><![CDATA[wx13974bf780d3dc89]]></AppID>
<RevokeInfo><![CDATA[1]]></RevokeInfo>
</xml>
JSON format
{
"ToUserName": "gh_870882ca4b1",
"FromUserName": "oaKk346BaWE-eIn4oSRWbaM9vR7s",
"CreateTime": 1627359464,
"MsgType": "event",
"Event": "user_authorization_revoke",
"OpenID": "oaKk343WOktAaT2ygsX138BGblrg",
"AppID": "wx13974bf780d3dc89",
"RevokeInfo": "201",
}
# Event field definition
attribute | type | Introductions |
---|---|---|
ToUserName | string | UserName for Service Account |
FromUserName | string | Platform Push Service UserName |
MsgType | string | Default is: event |
Event | string | User_info_modified: user profile changes, user_authorization_revoke: user revocation, user_authorization_cancellation: user completes the cancellation; |
CreateTime | number | Sending Time |
OpenID | string | Authorized User OpenID |
AppID | string | AppID for Service Account |
RevokeInfo | string | User's withdrawn H5 authorization information, 201: address, 202: invoice information, 203: card information, 204: microphone, 205: nickname and profile picture, 206: location information, 207: selected picture or video |