Preparations

Mobile App Login via Weixin 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 mobile app, and obtain the corresponding AppID and AppSecret. You can start the access process after your application for Weixin Login is approved.

1. Users can only log in to mobile apps via Weixin using the native login method and need to install the Weixin app.

2. For Android apps, it is recommended to always display the Weixin Login button. When the Weixin app is not installed on the user's mobile phone, guide the user through downloading and installing the Weixin app.

3. For iOS apps, considering the related regulations stipulated in the App Store Review Guidelines, it is recommended that when accessing Weixin Login, developers check whether the Weixin app has been installed (using the isWXAppInstalled function in the SDK). For users who do not install the Weixin app, the Weixin Login button is hidden and only other login methods (e.g. mobile number registration and login and guest login) are provided.

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 launch 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

Mobile App Weixin Authorized Login

The developer must access the SDK provided by the Weixin Open Platform to initiate an authorized login request. After accessing the SDK and getting the related authorization scope, the developer's mobile app will locally launch the Weixin app for authorized login on the platform. After confirmation by the Weixin user, Weixin will launch the developer's mobile app and carry the temporary code for authorization.

Example of the access code of authorized login to an app on the iOS platform (refer to the iOS Access Guide):


-(void)sendAuthRequest
{
	// Build a SendAuthReq structure
	SendAuthReq* req =[[[SendAuthReq alloc]init]autorelease];
	req.scope = @"snsapi_userinfo";
	req.state = @"123";
	// The third party sends a SendAuthReq message structure to the Weixin platform.
	[WXApi sendReq:req];
}

Example of the access code of authorized login to an app on the Android platform (refer to the Android Access Guide):

{
	// Send oauth request
	Final SendAuth.Req req = new SendAuth.Req();
	req.scope = "snsapi_userinfo";
	req.state = "wechat_sdk_demo_test";
	api.sendReq(req);
}

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.
scope Yes App authorization scope. To obtain the user's personal information, enter snsapi_userinfo.
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 recommend that the third party pass this parameter. It can be checked by setting it to a simple random number plus session.

Response Example:

appid: wxd477edab60670232
scope: snsapi_userinfo
state: wechat_sdk_demo

Launching Weixin to Open the Authorized Login Page:

Response Description

After the user taps "Authorize", the Weixin app is launched and redirects to an authorization interface. The user taps "Allow" or "Cancel" on this interface. The SDK returns data to the caller via SendAuth Resp.

Return value Description
ErrCode ERR_OK = 0 (agreed by user) ERR_AUTH_DENIED = -4 (authorization rejected by user) ERR_USER_CANCEL = -2 (canceled by user)
code The code that the user used to exchange for access_token. This is effective only when ErrCode is 0.
state The unique identifier used to identify the request sent by the third-party app. This value is passed by the third-party app when calling sendReq and returned by Weixin. The length of the state string shall not exceed 1 KB.
lang Current language of the Weixin app
country Information on the current country of the Weixin user

Step 2: Obtain access_token using code

After obtaining the code in Step 1, request the following link to obtain an access_token:

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"
}
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 mobile 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"
}
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"}

Note:


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 Appsecret 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. The access_token is valid and does not expire.
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 |
| /sns/oauth2/refresh_token | Refreshes or renews access_token |
| /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](/doc/oplatform/Mobile_App/WeChat_Login/Authorized_API_call_UnionID.html).


**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 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. Is a fee charged for Mobile App Login via Weixin on the Open Platform?**


A: "Weixin Login" allows the huge user value of Weixin to be shared with third-party websites, while also providing more convenient services and better contents for Weixin users, thus achieving a 'win-win' for both users and third-parties. Currently, no fee is charged.