中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
使用Account Kit 获取用户头像昵称
微信扫码分享
private getAvatarAndNickNameWithCallback(): void { hilog.info(0x0000, 'testTag', 'getAvatarAndNickNameWithCallback'); // 创建授权请求,并设置参数 let authRequest: authentication.AuthorizationWithHuaweiIDRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest(); // 获取头像昵称需传如下scope authRequest.scopes = ['profile']; // forceAuthorization参数用来控制是否拉起授权页面 authRequest.forceAuthorization = true; // 用于防跨站点请求伪造,推荐采用如下方式给state赋值 authRequest.state = util.generateRandomUUID(); // 执行授权请求 try { let controller: authentication.AuthenticationController = new authentication.AuthenticationController(getContext(this)); controller.executeRequest(authRequest).then((data: authentication.AuthenticationResponse) => { let authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse; let state: string = authorizationWithHuaweiIDResponse.state!; if (authRequest.state != state) { hilog.error(0x0000, 'testTag', 'Failed to authorize. The state is different'); this.result = 'cancel false: The state is different.'; return; } let authorizationWithHuaweiIDCredential: authentication.AuthorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!; let avatarUri: string = authorizationWithHuaweiIDCredential.avatarUri!; let nickName: string = authorizationWithHuaweiIDCredential.nickName!; this.result = 'avatarUri:' + avatarUri + ' nickName:' + nickName; }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `Failed to getAvatarAndNickNameWithCallback. BusinessError Code: ${err.code}, message: ${err.message}`); }) } catch (error) { hilog.error(0x0000, 'testTag', `Failed to getAvatarAndNickNameWithCallback. Code: ${error.code}, message: ${error.message}`); } }