# Preparations

Website App Weixin Login is a Weixin OAuth2.0 authorized login system built based on the OAuth2.0 protocol standard. Before accessing Weixin OAuth2.0 Login, you must register a developer account on the Weixin Open Platform, own an approved website app, and obtain the corresponding AppID and AppSecret. You can start the access process after your application for Weixin Login is approved.

# Authorization process

Weixin OAuth2.0 authorization login allows Weixin users to use their Weixin IDs to securely log in to third-party apps and websites. After a Weixin user uses authorization login to log in to a third-party app that uses Weixin Oauth2.0, the third party can obtain the user's API calling credentials (access_tokens) and use these access_tokens to call APIs authorized by the Weixin Open Platform. This allows the third party to obtain the basic information of users and their authorization. Weixin Oauth2.0 authorization login currently supports authorization_code mode, which is applicable to server-side application authorization. The overall process of this mode is as follows:


1. When a third-party app initiates a Weixin login authorization request, after a Weixin user grants authorization to the third-party app, Weixin will lauch the app or redirect to the third-party website and carry the authorized temporary ticket code parameter.
2.  Add AppID, AppSecret, and other information via code, and exchange for access_token using the relevant API.
3. Use access_token to call the API to obtain the user's basic data and resources or help the user perform a basic operation.

Below is the sequence diagram of how to obtain Access_token:

Step 1: Request CODE

Before using website app authorization login, the third-party must ensure it has already obtained the relevant webpage authorization scope (scope=snsapi_login). You can open the following link on your PC: https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect If the system prompts "this link cannot be accessed", make sure the parameters have been entered correctly. For example, check that the redirect_uri domain name is consistent with the authorized domain name entered during review and the scope is snsapi_login.

Parameters

Parameter Required Description
appid Yes App's unique identifier
redirect_uri Yes Use urlEncode to process the link
response_type Yes Enter "code"
scope Yes App authorization scope. Multiple scopes are separated by a comma (,). Only enter snsapi_login for webpage apps.
state No Used to maintain the request and callback status. It is returned unchanged to the third party after the authorization request. This parameter can be used to prevent any cross-site request forgery (csrf) attack. It is recommended that the third party pass this parameter. It can be checked by setting it to a simple random number plus session.

Response Description

After the user allows authorization, the system will redirect to the website specified by the redirect_uri, carrying the code and state parameters.

redirect_uri?code=CODE&state=STATE

If the user rejects authorization, the system redirects with only the state parameter, not the code parameter.

redirect_uri?state=STATE

Request example

Log in to the website app of Yihaodian (Yhd.com). https://passport.yhd.com/wechat/login.do Then, the parameter state is generated and the user is redirected to https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect The Weixin user scans the QR code with Weixin and, after confirming login, the PC redirects to https://passport.yhd.com/wechat/callback.do?code=CODE&state=3d6be0a4035d839573b04816624a415e To meet the customized needs of websites, we also provide a second code retrieval method. We allow websites to embed Weixin login QR codes in their webpages. After users scan the code with Weixin to grant authorization, the code is returned to the website by JS. The main purpose of JS Weixin login is to give websites a way to allow users to complete login in the site, without having to redirect to Weixin and then return. This makes the Weixin login process smoother and increases the success rate. The process for embedding QR codes for Weixin login JS is as follows:

Step 1: Introduce the following JS file in the page (supports HTTPS):

http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js

Step 2: Instantiate the following JS object where you need to use Weixin login:

 var obj = new WxLogin({
 self_redirect:true,
 id:"login_container", 
 appid: "", 
 scope: "", 
 redirect_uri: "",
  state: "",
 style: "",
 href: ""
 });

Parameters

Parameter Required Description
self_redirect No true: After the user taps to confirm login, the system redirects to the redirect_uri within iframe. False (default): After the user taps to confirm login, the system redirects to the redirect_uri in the top window.
id Yes The container ID of the QR code displayed on the third-party page
appid Yes The unique identifier of the app, which is obtained after the app submitted for review on Weixin Open Platform is approved.
scope Yes App authorization scope. Multiple scopes are separated by a comma (,). Only enter snsapi_login for webpage apps.
redirect_uri Yes The redirect address, which must be encoded using UrlEncode.
state No Used to maintain the request and callback status. It is returned unchanged to the third party after the authorization request. This parameter can be used to prevent any cross-site request forgery (csrf) attack. It is recommended that the third party pass this parameter. It can be checked by setting it to a simple random number plus session.
style No The options are "black" and "white" and default is a black text description. For details, see the FAQs at the end of this document.
href No The custom style link. Third parties can replace the default style as needed. For details, see the FAQs at the end of this document.

Step 2: Obtain access_token using code

Obtain access_token using code.

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

Parameters

Parameter Required Description
appid Yes The unique identifier of the app, which is obtained after the app submitted for review on Weixin Open Platform is approved.
secret Yes The AppSecret of the app, which is obtained after the app submitted for review on Weixin Open Platform is approved.
code Yes Enter the code parameter obtained in Step 1
grant_type Yes Enter authorization_code

Response Description

Response for a successful request:

{ 
"access_token":"ACCESS_TOKEN", 
"expires_in":7200, 
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID", 
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

Parameters

Parameter Description
access_token API call credential
expires_in The time to expiration of the API call credential (access_token), in seconds.
refresh_token The access_token refreshed by the user
openid The unique identifier of the authorizing user
scope User authorization scope. Multiple scopes are separated by a comma (,)
unionid This field appears only when this website app has obtained this user's userinfo authorization.

Example of response for a failed request:

{"errcode":40029,"errmsg":"invalid code"}

Refresh the validity period of access_token

access_token is the credential used to call the authorized API. The validity period of access_token is short ( 2 hours). When it expires, you can use refresh_token to refresh it. There are two refresh results:

1. If access_token has expired, performing refresh_token will give you a new access_token with a new expiration time.
2. If access_token has not expired, performing refresh_token will not change access_token, but will extend the validity period. This is like renewing access_token.

refresh_token has a longer validity (30 days). Once the refresh_token expires, you must get authorization again.

Request method

After obtaining the code in Step 1, request the following link to perform refresh_token:

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

Parameters

Parameter Required Description
appid Yes App's unique identifier
grant_type Yes Enter refresh_token
refresh_token Yes Enter the refresh_token parameter obtained through access_token

Response Description

Response for a successful request:

{ 
"access_token":"ACCESS_TOKEN", 
"expires_in":7200, 
"refresh_token":"REFRESH_TOKEN", 
"openid":"OPENID", 
"scope":"SCOPE" 
}

Parameters

Parameter Description
access_token API call credential
expires_in The time to expiration of the API call credential (access_token), in seconds.
refresh_token The access_token refreshed by the user
openid The unique identifier of the authorizing user
scope User authorization scope. Multiple scopes are separated by a comma (,)

Example of response for a failed request:

{"errcode":40030,"errmsg":"invalid refresh_token"}

Notes:

1. Appsecret  is the key used to access the app. If it is leaked, it may lead to the disclosure of app data and app user data, and other high-risk consequences. If stored on clients, it is at risk of theft (i.e., by decompilation).
2. access_token  is the credential (equivalent to the user login status) by which users authorize third-party apps to initiate API calls. If stored on clients, it can be stolen and used to leak user data or maliciously make calls to Weixin APIs.
3. refresh_token  is a credential by which users authorize third-party apps. It has a longer validity period than the access_token and can only be obtained by refreshing access_token. If leaked, it entails the same risks as access_token .

It is recommended that secret and user data (e.g. access_token) be stored in the app cloud server and that the cloud server forward the API call request.

Step 3: Use access_token to call the API

After obtaining access_token, you can call the API provided the following:

1. access_token is valid and has not expired.
2. The Weixin user has authorized the corresponding API scope to a thirty-party app account.

The APIs that can be called for different scopes are shown below:

Authorization Scope API API Description
snsapi_base /sns/oauth2/access_token Gets obtain access_token, refresh_token, and authorized scope via code
snsapi_base /sns/oauth2/refresh_token Refreshes or renews access_token
snsapi_base /sns/auth Checks the validity of access_token
snsapi_userinfo /sns/userinfo Gets the user's personal information

snsapi_base is a basic API. If the app has permissions in other scopes, it has the snsapi_base permission by default. With snsapi_base, mobile webpages can directly redirect to third-party webpages with temporary authorization ticket (code), without having to request users to authorize on the authorization page. However, this may limit the user authorized scope to only snsapi_base, resulting in failure to get data and basic features that require user authorization. For the API call method, refer to the Guide for API Call of Weixin Authorization Relation.

FAQs

  1. What is a temporary code for authorization? A: The temporary code for authorization is used to get access_token by third parties. The code is only valid for 10 minutes and one code can only be used to retrieve one access_token at a time, which ensures the security of Weixin authorization login. Third parties can use the https and state parameters to further enhance the security of their own authorization login process.

  2. What is an authorization scope? A: The authorization scope represents the range of API permissions that the user grants to the third party. The third-party app must apply to the Weixin Open Platform for permissions included in the relevant scope. Then, it can have the user grant authorization as described in the usage documentation. After the user grants authorization and the app obtains the relevant access_token, it can call the APIs in the scope.

  3. What is the style field in the Weixin login JS code of embedded QR codes used for? A: The color scheme of a third-party page may be light or dark in tone. If the page has a light background, the style field should provide the value "black" (or be left blank as "black" is the default value). In this case, the Weixin authorization login text style is black and appears as below:

If the field is provided with "white", the descriptive text is displayed in white, which is suitable for dark background, as shown below:

  1. What is the href field in the Weixin login JS code of embedded QR codes used for? A: If the third party thinks that the default style provided by WeChat Team does not match its page style, they can provide their own style file to overwrite the default style. For example, if the third party thinks the default QR code is too big, they can provide the relevant css style file and enter its link URL in the href field.
.impowerBox .qrcode {width: 200px;}
.impowerBox .title {display: none;}
.impowerBox .info {width: 200px;}
.status_icon {display: none}
.impowerBox .status {text-align: center;} 

The result is shown below: