中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
客户端如何获取用户的头像、昵称等信息?
微信扫码分享
import { authentication } from '@kit.AccountKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { util } from '@kit.ArkTS'; // 创建授权请求,并设置参数 let authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest(); // 获取头像昵称需要传如下scope authRequest.scopes = ['profile']; // 若开发者需要进行服务端开发,则需传如下permission获取authorizationCode authRequest.permissions = ['serviceauthcode']; // 用户是否需要登录授权,该值为true且用户未登录或未授权时,会拉起用户登录或授权页面 authRequest.forceAuthorization = true; authRequest.state = util.generateRandomUUID(); @Entry @Component struct Index { build() { Column() { Button("获取用户信息").onClick(() => { // 执行授权请求 try { let controller = new authentication.AuthenticationController(getContext(this)); controller.executeRequest(authRequest, (err, data) => { if (err) { hilog.error(0x0000, 'testTag', 'auth fail,error: %{public}s', JSON.stringify(err)); return; } let authorizationWithHuaweiIDResponse = data as authentication.AuthorizationWithHuaweiIDResponse; let state = authorizationWithHuaweiIDResponse.state; if (state != undefined && authRequest.state != state) { hilog.error(0x0000, 'testTag', 'auth fail,The state is different: %{public}s', JSON.stringify(authorizationWithHuaweiIDResponse)); return; } hilog.info(0x0000, 'testTag', 'auth success: %{public}s', JSON.stringify(authorizationWithHuaweiIDResponse)); let authorizationWithHuaweiIDCredential = authorizationWithHuaweiIDResponse.data!; let avatarUri = authorizationWithHuaweiIDCredential.avatarUri;//用户头像 let nickName = authorizationWithHuaweiIDCredential.nickName;//用户昵称 let authorizationCode = authorizationWithHuaweiIDCredential.authorizationCode; // 开发者处理avatarUri, nickName, authorizationCode hilog.error(0x0000,'testTag',"avatarUri:"+avatarUri?.toString()) hilog.error(0x0000,'testTag',"nickName:"+nickName?.toString()) }); } catch (error) { hilog.error(0x0000, 'testTag', 'auth failed: %{public}s', JSON.stringify(error)); } }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }