#鸿蒙学习大百科#如何通过API接入华为账号登录?

如何通过API接入华为账号登录?

HarmonyOS
2024-10-23 09:23:08
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
耗子煨汁r
import { authentication } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { util } from '@kit.ArkTS';
// 创建登录请求,并设置参数
let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
// 当用户未登录华为帐号时,是否强制拉起华为帐号登录界面
loginRequest.forceLogin = true;
loginRequest.state = util.generateRandomUUID();
@Entry
@Component
struct Index {
  build() {
    Column() {
      Button("登录").onClick(() => {
        // 执行登录请求
        try {
          let controller = new authentication.AuthenticationController(getContext(this));
          controller.executeRequest(loginRequest, (err, data) => {
            if (err) {
              hilog.error(0x0000, 'testTag', 'login fail, error: %{public}s', JSON.stringify(err));
              return;
            }
            let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
            let state = loginWithHuaweiIDResponse.state;
            if (state != undefined && loginRequest.state != state) {
              hilog.error(0x0000, 'testTag', 'login fail,The state is different: %{public}s',
                JSON.stringify(loginWithHuaweiIDResponse));
              return;
            }
            hilog.info(0x0000, 'testTag', 'login success, %{public}s', JSON.stringify(loginWithHuaweiIDResponse));

            let loginWithHuaweiIDCredential = loginWithHuaweiIDResponse.data!;
            let code = loginWithHuaweiIDCredential.authorizationCode;
            let idToken = loginWithHuaweiIDCredential.idToken;
            let openID = loginWithHuaweiIDCredential.openID;
            let unionID = loginWithHuaweiIDCredential.unionID;
            // 开发者处理code, idToken, openID, unionID
          });
        } catch (error) {
          hilog.error(0x0000, 'testTag', 'login failed: %{public}s', JSON.stringify(error));
        }
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
分享
微博
QQ
微信
回复
2024-10-23 16:25:12
相关问题