目的:
通过在自家App上点击“华为账号登录”按钮实现第三方登录
准备工作
1、获取Client ID
登录 AppGallery Connect 平台,路径为: 项目设置
=>常规
=>应用
=>OAuth 2.0客户端ID(凭据): Client ID
2、在入口module(模块)
的module.json5
文件的module节点内
,添加上如下配置:
"metadata": [
{
"name": "client_id",
"value": "刚才获取到的Client ID"
}
]
图示如下:
业务流程
[图片上传失败...(image-9c386c-1742778716637)]
代码
1、需要先导入相关的文件
import { LoginWithHuaweiIDButton, loginComponentManager } from '@kit.AccountKit';
import { BusinessError } from '@kit.BasicServicesKit';
2、在华为账号登录所在页面增加个类型为loginComponentManager.LoginWithHuaweiIDButtonController
的属性controller
,作用是监听到华为系统给的回调信息。
controller: loginComponentManager.LoginWithHuaweiIDButtonController =
new loginComponentManager.LoginWithHuaweiIDButtonController()
.onClickLoginWithHuaweiIDButton((error: BusinessError, response: loginComponentManager.HuaweiIDCredential) => {
if (error) {
hilog.error(0x0000, 'testTag',
`Failed to onClickLoginWithHuaweiIDButton. Code: ${error.code}, message: ${error.message}`);
return;
}
if (response) {
hilog.info(0x0000, 'testTag', 'Succeeded in getting response.');
const authCode = response.authorizationCode;
const openID = response.openID;
const unionID = response.unionID;
const idToken = response.idToken;
// 开发者处理authCode、openID、unionID、idToken
}
console.info('[华为账号登录--按钮登录]:' + JSON.stringify(response))
});
3、调用LoginWithHuaweiIDButton组件,展示华为账号登录按钮,用户点击华为账号登录按钮后,应用获取到UnionID
、Authorization Code
、OpenID
、ID Token
,将数据传给应用服务器。
Column() {
LoginWithHuaweiIDButton({
params: {
// LoginWithHuaweiIDButton支持的样式
style: loginComponentManager.Style.BUTTON_RED,
// 账号登录按钮在登录过程中展示加载态
extraStyle: {
buttonStyle: new loginComponentManager.ButtonStyle().loadingStyle({
show: true
})
},
// LoginWithHuaweiIDButton的边框圆角半径
borderRadius: 24,
// LoginWithHuaweiIDButton支持的登录类型
loginType: loginComponentManager.LoginType.ID,
// LoginWithHuaweiIDButton支持按钮的样式跟随系统深浅色模式切换
supportDarkMode: true,
// verifyPhoneNumber:如果华为账号用户在过去90天内未进行短信验证,是否拉起Account Kit提供的短信验证码页面
verifyPhoneNumber: true
},
controller: this.controller
})
}
.height(40)
其中,loginType参数所代表的含义参考如下: LoginType枚举值含义