WeChat OAuth Login
WeChat-authorized web applications can directly use WeChat to log in to CloudBase, including two authorization types:
- WeChat Official Account (Official Account web page);
- WeChat Open Platform (general web applications, mobile applications, etc.).
Activation Process
1. Activate a Platform Account
First, a registered account for WeChat Official Account Platform / Open Platform is required. If you don't have one, please go to WeChat Official Account Platform or WeChat Open Platform to apply.
Then, in the admin console of the WeChat Official Account Platform/Open Platform, view the Developer ID (AppId) and Developer Password (AppSecret).
Taking WeChat Official Account Platform as an example, the "Development - Basic Configuration" section contains the following:
Developer Password (AppSecret) is highly confidential information. Each time you click the "Reset" button in the above figure, a new AppSecret will be generated.
2. Enable WeChat Login
On the Login Authorization Management Page in the Console, enable the corresponding platform login authorization.
Click the Enable button, then fill in the AppId and AppSecret in the corresponding fields of the pop-up window.
3. Add Security Domains (Optional)
Web applications must add their domain names to the Security Configuration Web security domain list; otherwise, they will be identified as unauthorized sources:
WeChat Login Process
Before using WeChat to log in to CloudBase, please first enable WeChat login in the console.
Step 1: Initializing the SDK
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "your-env-id"
});
Step 2: Using the SDK to Handle the Login Process
1. Create Provider
First, create a Provider instance and populate it with parameters:
const auth = app.auth();
const provider = auth.weixinAuthProvider({
appid: "...",
scope: "xxxx"
});
Parameters are described below:
Parameter Name | Type | Required | Description |
---|---|---|---|
appid | string | Yes | AppId for the WeChat Official Account Platform/Open Platform. |
scope | string | Yes | Webpage authorization type. The options include:
|
If a user logs in with snsapi_userinfo
or snsapi_login
and it is their first login, CloudBase will automatically fetch and synchronize the WeChat user's basic information.
If the user is not logging in for the first time, this behavior will not occur.
2. Using Provider for Login
First, call Provider.signInWithRedirect()
, and the user will be redirected to the WeChat OAuth authorization page:
provider.signInWithRedirect();
On the authorization page, the user needs to grant permission for the login action. Upon successful authorization, they will be returned to the current page.
Then call Provider.getRedirectResult()
to obtain the login result:
provider.getRedirectResult().then((loginState) => {
if (loginState) {
// Login successful!
}
});
For how to provide users with a better login experience, please refer to Best Practices.