中国优质的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,传参数之前需要先申请对应scope权限,才能返回对应数据 authRequest.scopes = ['phone']; // 获取code需传如下permission 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 code = authorizationWithHuaweiIDCredential.authorizationCode; // 开发者处理code }); } catch (error) { hilog.error(0x0000, 'testTag', 'auth failed: %{public}s', JSON.stringify(error)); } }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }