1.獲取 authorizationCode:
2.利用 authorizationCode 獲取 accessToken:文檔中心
3.獲取手機:文檔中心
4.獲取昵稱頭像:文檔中心
首先創建 request
若要獲取手機號,scope必填?phone,permissions 必填?serviceauthcode,否則第 3 步將無法返回預期的字段,第 3 步與第 4 步調用接口一致,報文返回結果根據 scope 進行返回。
// 創建授權請求,并設置參數
const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
authRequest.scopes = ['phone']; // 元服務不支持profile,需傳其他支持的scope。默認返回UnionID、OpenID
authRequest.permissions = ['serviceauthcode'];
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID(); // 建議使用generateRandomUUID生成state
authRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;
?若要獲取昵稱,頭像,scope必填?phone,permissions 必填?serviceauthcode。
// 創建授權請求,并設置參數
const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
authRequest.scopes = ['profile']; // 元服務不支持profile,需傳其他支持的scope。默認返回UnionID、OpenID
authRequest.permissions = ['serviceauthcode'];
authRequest.forceAuthorization = true;
authRequest.state = util.generateRandomUUID(); // 建議使用generateRandomUUID生成state
authRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;
根據接口調用返回的 authorizationCode,去調用 RESET公共API:
https://account.cloud.huawei.com/rest.php?nsp_svc=GOpen.User.getInfo |
接口文檔:?文檔中心
// 執行授權請求,并處理結果
try {const controller = new authentication.AuthenticationController(getContext(this));controller.executeRequest(authRequest, (error: BusinessError<Object>, data) => {if (error) {this.dealAllError(error);return;}const authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse;const state = authorizationWithHuaweiIDResponse.state;if (state && authRequest.state !== state) {hilog.error(0x0000, 'testTag', `Failed to authorize. The state is different, response state: ${state}`);return;}hilog.info(0x0000, 'testTag', 'Succeeded in authentication.');const authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!;const avatarUri = authorizationWithHuaweiIDCredential.avatarUri; // 元服務不支持該字段const nickName = authorizationWithHuaweiIDCredential.nickName; // 元服務不支持該字段const idToken = authorizationWithHuaweiIDCredential.idToken;const openID = authorizationWithHuaweiIDCredential.openID;const unionID = authorizationWithHuaweiIDCredential.unionID;const code = authorizationWithHuaweiIDCredential.authorizationCode;// 開發者處理avatarUri, nickName, idToken, openID, unionID, code});
} catch (error) {this.dealAllError(error);
}// 錯誤處理
dealAllError(error: BusinessError<Object>): void {hilog.error(0x0000, 'testTag', `Failed to auth. Code: ${error.code}, message: ${error.message}`);
}
接口即可正常返回預期報文。