#鸿蒙学习大百科#如何通过代码实现获取用户的手机号码?

如何通过代码实现获取用户的手机号码?

HarmonyOS
2024-10-23 09:42:01
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
花鸟吹雪
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)
  }
}
分享
微博
QQ
微信
回复
2024-10-23 17:42:23
相关问题
#鸿蒙学习大百科#什么是用户文件?
159浏览 • 0回复 待解决