【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)
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}`);
}
接口即可正常返回预期报文。