华为账号一键登录开发笔记

一、准备工作   

        1、首先申请手机号相关权限

相关权限展示:

2、确定申请完成权限申请完成后,添加证书指纹,获取Client ID

3、代码中配置,打开DevEco Studio.

main目录下->module.json5文件,module下配置,如下:

二、代码开发

        1、相关协议

 privacyText: loginComponentManager.PrivacyText[] = [{
    text: '我已认真阅读并同意',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: '《用户使用协议》',
    tag: Index.USER_SERVICE_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: '和',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: '《隐私协议》',
    tag: Index.PRIVACY_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: '和',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: '《华为账号用户认证协议》',
    tag: Index.USER_AUTHENTICATION_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: '。',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }];

 2、同意协议获取手机号

注:如果华为账号没有登录情况下,需优先执行登录,才能获取到匿名手机号

 async getQuickLoginAnonymousPhone() {
    return new Promise<void>((resolve, reject) => {
      // 创建登录请求,并设置参数
      let loginRequest = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
      loginRequest.forceLogin = true;
      loginRequest.idTokenSignAlgorithm = authentication.IdTokenSignAlgorithm.PS256;
      loginRequest.state = util.generateRandomUUID();
      // 执行登录请求,并处理结果
      try {
        let controller = new authentication.AuthenticationController(getContext(this));
        controller.executeRequest(loginRequest, async (error: BusinessError<Object>, data) => {
          if (error) {
            console.log(JSON.stringify(error));
            reject(error)
            return;
          }
          let loginWithHuaweiIDResponse = data as authentication.LoginWithHuaweiIDResponse;
          let state = loginWithHuaweiIDResponse.state;
          if (state != undefined && loginRequest.state != state) {
            hilog.error(0x0000, 'testTag', `Failed to login. The state is different, response state: ${state}`);
            reject(new Error("state is different"))
            return;
          }
          hilog.info(0x0000, 'testTag', 'Succeeded in login. %{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

          //创建登录授权,获取匿名手机号
          const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
          authRequest.scopes = ['quickLoginAnonymousPhone'];
          authRequest.state = util.generateRandomUUID();
          authRequest.forceAuthorization = false;
          const controller = new authentication.AuthenticationController();
          try {
            console.log("controller之前", this.phoneNumber)
            const response: authentication.AuthorizationWithHuaweiIDResponse =
              await controller.executeRequest(authRequest)
            console.log("response", JSON.stringify(response))
            const unionID: string = response.data?.unionID as string;
            const openID: string = response.data?.openID!;
            const anonymousPhone = response.data?.extraInfo?.quickLoginAnonymousPhone as string;
            if (anonymousPhone) {
              console.log("controller之后的phoneNumber", this.phoneNumber);
              resolve();
            } else {
              reject(new Error('Failed to get anonymous phone number'));
            }
          } catch (e) {
            reject(e);
          }


        });
      } catch (error) {
        reject(error)
        console.log(JSON.stringify(error));
      }
    })
  }

三、执行登录

        1、使用华为控件 LoginWithHuaweiIDButton 进行登录
 

 LoginWithHuaweiIDButton({
          params: {
            // LoginWithHuaweiIDButton支持的样式
            style: loginComponentManager.Style.BUTTON_RED,
            // 账号登录按钮在登录过程中展示加载态
            extraStyle: {
              buttonStyle: new loginComponentManager.ButtonStyle().loadingStyle({
                show: true
              })
            },
            // LoginWithHuaweiIDButton的边框圆角半径
            borderRadius: 24,
            // LoginWithHuaweiIDButton支持的登录类型
            loginType: loginComponentManager.LoginType.QUICK_LOGIN,
            // LoginWithHuaweiIDButton支持按钮的样式跟随系统深浅色模式切换
            supportDarkMode: true,
            // verifyPhoneNumber:如果华为账号用户在过去90天内未进行短信验证,是否拉起Account Kit提供的短信验证码页面
            // verifyPhoneNumber: true
          },
          controller: this.controller
        })

2、构造LoginWithHuaweiIDButton组件的控制器
 

 controller: loginComponentManager.LoginWithHuaweiIDButtonController =
    new loginComponentManager.LoginWithHuaweiIDButtonController()
      .setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED)
      .onClickLoginWithHuaweiIDButton((error: BusinessError | undefined,
        response: loginComponentManager.HuaweiIDCredential) => {
        this.handleLoginWithHuaweiIDButton(error, response)
      })
      .onClickEvent((error: BusinessError, clickEvent: loginComponentManager.ClickEvent) => {
        if (error) {
          console.log(error.message);
          return;
        }
      });

  handleLoginWithHuaweiIDButton(error: BusinessError | undefined,
    response: loginComponentManager.HuaweiIDCredential) {
    if (error) {
      // hilog.error(this.domainId, this.logTag,
      //   `Failed to click LoginWithHuaweiIDButton. errCode is ${error.code}, errMessage is ${error.message}`);
      if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
        AlertDialog.show(
          {
            message: "网络未连接,请检查网络设置。",
            offset: { dx: 0, dy: -12 },
            alignment: DialogAlignment.Bottom,
            autoCancel: false,
            confirm: {
              value: "知道了",
              action: () => {
              }
            }
          }
        );
      } else if (error.code === ErrorCode.ERROR_CODE_AGREEMENT_STATUS_NOT_ACCEPTED) {
        // 未同意协议,弹出协议弹框,推荐使用该回调方式
        this.agreementDialog.open();
      } else if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
        // 华为账号未登录提示
        showToast("华为账号未登录,请重试");
      } else if (error.code === ErrorCode.ERROR_CODE_NOT_SUPPORTED) {
        // 不支持该scopes或permissions提示
        showToast("该scopes或permissions不支持");
      } else {
        // 其他提示系统或服务异常
        showToast('服务或网络异常,请稍后重试');
        // TODO: 其他错误码处理,请参考API中的错误码查看详细错误原因
      }
      return;
    }
    try {
      if (this.isSelected) {
        if (response) {
          // hilog.info(this.domainId, this.logTag, 'Succeeded in clicking LoginWithHuaweiIDButton.');
          // 开发者根据实际业务情况使用以下信息
          const authCode = response.authorizationCode;
          const openID = response.openID;
          const unionID = response.unionID;
          const idToken = response.idToken;
          //对接服务接口,进行登录认证

          
        }
      } else {
        //没有同意协议,打开弹框点击确定
      }
    } catch (err) {
      // hilog.error(this.domainId, this.logTag,
      //   `Failed to LoginWithHuaweiIDButton, errCode: ${err.code}, errMessage: ${err.message}`);
      AlertDialog.show(
        {
          message: '服务或网络异常,请稍后重试',
          offset: { dx: 0, dy: -12 },
          alignment: DialogAlignment.Bottom,
          autoCancel: false,
          confirm: {
            value: '知道了',
            action: () => {
            }
          }
        }
      );
    }
  }

完结

以上是华为账号一键登录执行流程,如有疑问欢迎提问
另附官网地址https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/account-api-huawei-id-button-V13

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值