华为账号登录
//引入
import { authentication } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
@Entry
@Component
struct Index {
private loginWithCallBack(): void {
hilog.info(0x0000, 'testTag', 'loginWithCallBack');
// 创建登录请求,并设置参数
let loginRequest: authentication.LoginWithHuaweiIDRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
// 当用户未登录华为帐号时,是否强制拉起华为帐号登录界面
loginRequest.forceLogin = true;
// 用于防跨站点请求伪造,推荐采用如下方式给state赋值
loginRequest.state = util.generateRandomUUID();
// 执行登录请求
try {
let controller: authentication.AuthenticationController = new authentication.AuthenticationController(getContext(this));
controller.executeRequest(loginRequest).then((data: authentication.AuthenticationResponse) => {
let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
let state: string = loginWithHuaweiIDResponse.state!;
if (loginRequest.state != state) {
hilog.error(0x0000, 'testTag', 'login fail,The state is different');
this.result = 'login false: The state is different.';
return;
}
let loginWithHuaweiIDCredential: authentication.LoginWithHuaweiIDCredential = loginWithHuaweiIDResponse.data!;
let code: string = loginWithHuaweiIDCredential.authorizationCode!;
let idToken: string = loginWithHuaweiIDCredential.idToken!;
let openID: string = loginWithHuaweiIDCredential.openID;
let unionID: string = loginWithHuaweiIDCredential.unionID;
this.result = ' openID:' + openID + ' unionID:' + unionID;
// 获取code后需要将code传给应用服务器,调用华为帐号服务器接口换取Access Token,然后再获取用户其他信息。
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', 'login failed: %{public}s', JSON.stringify(err));
})
} catch (e) {
hilog.error(0x0000, 'testTag', 'login failed: %{public}s', JSON.stringify(e));
}
}
build() {
Column({ space: 0 }) {
// 登录
Button() {
Text($r('app.string.login'))
.fontColor('#FFFFFF')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontStyle(FontStyle.Normal)
}
.backgroundColor(Color.Black)
.type(ButtonType.Capsule)
.margin({
top: 80
})
.width('100%')
.height(40)
.onClick(() => {
this.loginWithCallBack();
})
}
.padding({
left: 16,
right: 16
})
.width('100%')
.height('100%')
}
}
注意项
"metadata": [
{
"name": "client_id",
"value": "110783297"
}
]