怎么获取华为账号绑定的手机号?参考https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/account-phone-unionid-login-V5,使用以下源码可以获取到UnionID、OpenID但是无法获取手机号。
import ArkUI from 'arkui';
@Entry
@Component
struct MyComponent {
@State listItems: ListView.Item[] = [];
build(private authDebug() {
// 创建授权请求,并设置参数。
let authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
// 获取匿名手机号需传quickLoginAnonymousPhone这个scope,传参之前需要先申请“华为账号一键登录”权限
//(权限名称为:quickLoginMobilePhone),后续才能获取匿名手机号数据;
// 获取UnionID、OpenID需传openid这个scope,这个scope不需要申请权限。
authRequest.scopes = ['quickLoginAnonymousPhone','openid'];
// 用于防跨站点请求伪造。
authRequest.state = util.generateRandomUUID();
// 一键登录场景该参数只能设置为false。
authRequest.forceAuthorization = false;
let controller = new authentication.AuthenticationController();
try {
controller.executeRequest(authRequest).then((response: authentication.AuthorizationWithHuaweiIDResponse) => {
// 获取到UnionID、OpenID、匿名手机号
let unionID = response.data?.unionID;
let openID = response.data?.openID;
let anonymousPhone = response.data?.extraInfo?.quickLoginAnonymousPhone;
hilog.info(0x0000, 'testTag', 'unionID:' + unionID + ' openID:' + openID + ' anonymousPhone:' + anonymousPhone);
if (anonymousPhone) {
hilog.info(0x0000, 'testTag', 'Succeeded in authentication');
// 将匿名手机号传给第3步使用
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in authentication. AnonymousPhone is empty');
// 未获取到匿名手机号需要跳转到应用自定义的登录页面。
}).catch((error: BusinessError) => {
this.dealAllError(error);
})
} catch (error) {
this.dealAllError(error);
}
}
// 错误处理
private dealAllError(error: BusinessError): void {
hilog.error(0x0000, 'testTag', `Failed to auth. Code: ${error.code}, message: ${error.message}`);
}) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
ListView({
itemCount: this.listItems.length,
scrollToIndex: 3, // 假设你想跳转到第四个ListItem,索引从0开始
renderItem: (item: ListView.Item) => {
ListItem({
onSelected: () => {
// 处理点击事件
}
}) {
Text(item.title)
}
}
})
.height(200)
.width('100%')
.margin(20)
.onListViewReady((listView) => {
for (let i = 0; i < 10; i++) {
this.listItems.push({ title: 'Item ' + (i + 1), index: i });
}
})
}
}
}
华为账号一键登录 需要先申请“华为账号一键登录”Scope权限。https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/account-config-permissions-V5\#section132012717318