目录

loginComponentManager (HUAWEI ID Sign-in Component Management)

This module provides logic management for the HUAWEI ID sign-in components and assists HarmonyOS apps in integrating the components to implement the sign-in function.

Start version: 4.1.0(11)

Module Import

import { loginComponentManager } from '@kit.AccountKit';

LoginType

Defines HUAWEI ID sign-in types.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Value

Description

ID

0

The OpenID and UnionID are used to associate with a HUAWEI ID.

After a user successfully signs in, the corresponding data is returned.

The response data of this sign-in type contains the openID, unionID, authorizationCode, and idToken parameters.

PHONE_NUMBER

1

PhoneNumber is used to associate with a HUAWEI ID.

After a user successfully signs in, if the user has not authorized the mobile number for quick verification, the mobile number authorization screen is displayed. If the user has authorized the mobile number, the corresponding data is returned.

This sign-in type does not require real-time verification of the mobile number bound to the HUAWEI ID. The response data contains the openID, unionID, authorizationCode, and idToken parameters.

The app needs to use authorizationCode to request an access token from the Account Kit server, and then use the access token to obtain the mobile number from the Account Kit server.

REAL_TIME_PHONE_NUMBER

2

PhoneNumber is used to associate with a HUAWEI ID.

Each time a user successfully signs in, the real-time mobile number verification and authorization screen is displayed.

This sign-in type requires real-time verification of the mobile number bound to the HUAWEI ID. The response data contains the openID, unionID, authorizationCode, and idToken parameters.

The app needs to use authorizationCode to request an access token from the Account Kit server, and then use the access token to obtain the mobile number from the Account Kit server.

NOTE:

REAL_TIME_PHONE_NUMBER is not supported currently.

QUICK_LOGIN

3

PhoneNumber is used to associate with a HUAWEI ID.

This type does not support the LoginWithHuaweiIDButton component of the icon or image & text type.

If this sign-in type is used, the AuthorizationWithHuaweiIDRequest API is called to obtain the anonymous mobile number bound to the HUAWEI ID. If the anonymous mobile number is not obtained, use another sign-in type.

The response data of this sign-in type contains the openID, unionID, authorizationCode, and idToken parameters.

The app needs to use authorizationCode to request an access token from the Account Kit server, and then use the access token to obtain the mobile number from the Account Kit server.

Start version: 5.0.0(12)

AppInfo

Defines the app information displayed on the sign-in panel.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

appIcon

PixelMap | ResourceStr | DrawableDescriptor

No

No

App icon.

appName

ResourceStr

No

No

App name, with up to 19 characters. If the name contains more characters, "..." is displayed at the end.

appDescription

ResourceStr

No

Yes

Detailed app description, with up to 44 characters.

NOTE:
  • This parameter is mandatory in version 4.1.0(11).
  • This parameter is optional since version 5.0.0(12). You do not need to set this parameter only when the sign-in type is LoginType.QUICK_LOGIN.

TextType

Defines types of privacy text displayed on the sign-in panel.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Value

Description

PLAIN_TEXT

0

Plain text, which cannot be tapped.

RICH_TEXT

1

Rich text, which is displayed in blue and can be tapped.

PrivacyText

Defines the privacy text to be displayed when the sign-in panel or button is used.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

type

TextType

No

No

Type of the privacy text, including plain text and rich text.

text

ResourceStr

No

No

Privacy text content displayed on the sign-in panel.

tag

string

No

Yes

This parameter is mandatory when type is set to TextType.RICH_TEXT. When a user taps a text, the tag value will be returned to the app. The app can display different privacy content based on the user's tap behavior.

LoginIcon

Defines sign-in icons displayed in the optional sign-in area.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

icon

PixelMap | ResourceStr | DrawableDescriptor

No

No

Icons of other sign-in options displayed in the optional sign-in area. According to the visual specifications for HUAWEI ID sign-in, it is recommended that the icon be a round image with a radius of 18 vp.

tag

string

No

Yes

When a user taps an icon, the tag value will be returned to the app. The app can display other sign-in option screens based on the user's tap behavior.

OptionalLoginButtonAttr

Defines the optional sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

text

ResourceStr

No

No

Text description of the optional sign-in button.

OptionalLoginAreaAttr

Defines the optional sign-in area.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

iconArray

LoginIcon[]

No

No

Icons of other sign-in options passed by the app, displayed in the optional sign-in area. A maximum of five icons can be displayed.

LoginPanelParams

Defines the information displayed on the sign-in panel.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

appInfo

AppInfo

No

No

App information.

privacyText

PrivacyText[]

No

Yes

Privacy text content.

optionalLoginButtonAttr

OptionalLoginButtonAttr

No

Yes

Optional sign-in button.

loginType

LoginType

No

Yes

HUAWEI ID sign-in type. The default value is LoginType.ID.

For one-tap sign-in, use LoginType.QUICK_LOGIN.

anonymousPhoneNumber

string

No

Yes

Anonymous mobile number bound to the HUAWEI ID. This parameter is mandatory when the sign-in type is set to LoginType.QUICK_LOGIN.

Start version: 5.0.0(12)

verifyPhoneNumber

boolean

No

Yes

Indicates whether to display the SMS verification code screen provided by Account Kit if a HUAWEI ID user did not perform SMS verification in the past 90 days.

true: yes

false: no The app needs to check whether the mobile number is up-to-date.

Default value: true

Start version: 5.0.0(12)

optionalLoginAreaAttr

OptionalLoginAreaAttr

No

Yes

Parameter of the optional sign-in area.

If both optionalLoginButtonAttr and optionalLoginAreaAttr exist, optionalLoginAreaAttr is displayed first.

Start version: 5.0.0(12)

ClickEvent

Defines the event that a user taps the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Value

Description

HUAWEI_ID_LOGIN_BUTTON

0

Event that a user taps the HUAWEI ID sign-in button.

AgreementStatus

Defines the status of whether a user agrees to the agreement.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Value

Description

NOT_ACCEPTED

0

The user does not accept the agreements.

ACCEPTED

1

The user has accepted the agreements.

HuaweiIDCredential

Defines the response to a successful sign-in using a HUAWEI ID.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

unionID

string

Yes

No

UnionID, which represents the identity of a HUAWEI ID user when using different products of the same developer. The same user has the same UnionID for different apps of the same developer. For details about the format requirements, please refer to What are the length limits of OpenID and UnionID?.

openID

string

Yes

No

OpenID, which represents the identity of a HUAWEI ID user when using different types of products. The same user has different OpenIDs for different apps. For details about the format requirements, please refer to What are the length limits of OpenID and UnionID?.

authorizationCode

string

Yes

No

Authorization code. This temporary credential is valid for 5 minutes and can be used only once.

idToken

string

Yes

Yes

ID token. It is a character string in JWT format, containing user information.

Events

Common events are not supported. Only specific events are supported.

LoginPanelController

LoginPanel component controller, which is used to register tap events in the component.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

[h2]onClickLoginWithHuaweiIDButton

onClickLoginWithHuaweiIDButton(callback: AsyncCallback<HuaweiIDCredential>): LoginPanelController

Registers an event triggered to return the result of one-tap HUAWEI ID sign-in. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<HuaweiIDCredential>

Yes

Callback function.

If the HUAWEI ID sign-in is successful, err is undefined and data is the HuaweiIDCredential object. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

Error codes:

For details about the error codes, please refer to ArkTS Error Codes, Account Management Error Codes, and Universal Error Codes.

Error Code

Error Message

401

Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.

1001500001

Failed to check the fingerprint of the app bundle.

1001500002

This error code is reported when a request is already being processed.

1001500003

The scopes or permissions are not supported.

1001502001

The user has not logged in with HUAWEI ID.

1001502002

The application is not authorized.

1001502003

Invalid input parameter value.

1001502005

Network error.

1001502009

Internal error.

1001502012

The user canceled the authorization.

1001502014

The app does not have the required scopes or permissions.

12300001

System service works abnormally.

1005300001

The user did not accept the agreement.

[h2]onClickOptionalLoginButton

onClickOptionalLoginButton(callback: AsyncCallback<void>): LoginPanelController

Registers a tap event of the optional sign-in button. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<void>

Yes

Callback function.

If the operation for a user to tap the optional sign-in button is successful, err is undefined. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickOptionalLoginIcon

onClickOptionalLoginIcon(callback: AsyncCallback<string>): LoginPanelController

Registers a tap event of the optional sign-in icon. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<string>

Yes

Callback function.

If the operation for a user to tap LoginIcon is successful, err is undefined and data is the tag in LoginIcon. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickPrivacyText

onClickPrivacyText(callback: AsyncCallback<string>): LoginPanelController

Registers a tap event of privacy content in rich text format. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<string>

Yes

Callback function.

If the operation for a user to tap the privacy content in rich text format is successful, err is undefined and data is the tag in PrivacyText. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onChangeAgreementStatus

onChangeAgreementStatus(callback: AsyncCallback<AgreementStatus>): LoginPanelController

Registers a user service agreement status change event. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<AgreementStatus>

Yes

Callback function.

If the user successfully agrees to or cancels the agreement, err is undefined and data is the obtained AgreementStatus. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]setAgreementStatus

setAgreementStatus(agreementStatus: AgreementStatus): LoginPanelController

Sets the status of the user service agreement.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

agreementStatus

AgreementStatus

Yes

If you want to use your custom user service agreement screen, set agreementStatus to NOT_ACCEPTED. After the user agrees to the agreement, set agreementStatus to ACCEPTED.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]setShowAgreementForOptionalLogin

setShowAgreementForOptionalLogin(): LoginPanelController

Sets the display of the privacy statement dialog box when a user taps another sign-in option.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickEvent

onClickEvent(callback: AsyncCallback<ClickEvent>): LoginPanelController

Tap event related to the HUAWEI ID sign-in button. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<ClickEvent>

Yes

Callback function.

When a user taps the HUAWEI ID sign-in button, err is undefined, and data is the ClickEvent object obtained. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickCloseButton

onClickCloseButton(callback: AsyncCallback<void>): LoginPanelController

Registers a tap event of the close button or a swipe-back event. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<void>

Yes

Callback function.

If the tap on the close button or the swipe-back operation is successful, err is undefined. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginPanelController

LoginPanel component controller, which can be used to register tap events in the component or call methods provided by the component.

Example:

import { LoginPanel, loginComponentManager } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct PreviewLoginPanelPage {
  // Indicates whether to display the LoginPanel component.
  @State show: boolean = true;
  // Define the privacy text displayed in the LoginPanel component.
  privacyText: loginComponentManager.PrivacyText[] = [{
    text: 'I have read and agree to the',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: 'User Service Agreement',
    tag: 'User Service Agreement',
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: 'Privacy Policy',
    tag: 'Privacy Policy',
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: 'and',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: 'HUAWEI ID User Authentication Agreement',
    tag: 'HUAWEI ID User Authentication Agreement',
    type: loginComponentManager.TextType.RICH_TEXT
  }];
  // Define other sign-in icons displayed in the LoginPanel component.
  iconArray: loginComponentManager.LoginIcon[] = [{
    icon: $r('app.media.app_icon'),
    tag: 'Other sign-in options'
  }];
  // Construct the controller of LoginPanel.
  controller: loginComponentManager.LoginPanelController = new loginComponentManager.LoginPanelController()
    // When the sign-in type is not QUICK_LOGIN and no agreement is set, to display your custom agreement dialog box, set the agreement status to NOT_ACCEPTED.
    .setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED)
    // Display the privacy statement dialog box when a user taps another sign-in option.
    .setShowAgreementForOptionalLogin()
    .onClickLoginWithHuaweiIDButton((error: BusinessError, response: loginComponentManager.HuaweiIDCredential) => {
      hilog.info(0x0000, 'testTag', 'onClickLoginWithHuaweiIDButton');
      if (error) {
        this.dealAllError(error);
        return;
      }
      if (response) {
        // Send the obtained authorization code to the app server.
        const authorizationCode = response.authorizationCode;
        hilog.info(0x0000, 'testTag', 'Succeeded in getting response.');
        this.show = false;
        return;
      }
    })
    .onClickOptionalLoginButton(() => {
      hilog.info(0x0000, 'testTag', 'onClickOptionalLoginButton');
      this.show = false;
    })
    .onClickOptionalLoginIcon((error: BusinessError, tag: string) => {
      if (error) {
        this.dealAllError(error);
        return;
      }
      hilog.info(0x0000, 'testTag', 'onClickOptionalLoginIcon tag: %{public}s', tag);
      this.show = false;
    })
    .onClickPrivacyText((error: BusinessError, tag: string) => {
      if (error) {
        this.dealAllError(error);
        return;
      }
      // The app needs to implement the agreement redirection logic.
      hilog.info(0x0000, 'testTag', 'onClickPrivacyText tag: %{public}s', tag);
    })
    .onClickCloseButton(() => {
      hilog.info(0x0000, 'testTag', 'onClickCloseButton.');
      this.show = false;
    })
    .onChangeAgreementStatus((error: BusinessError, agreementStatus: loginComponentManager.AgreementStatus) => {
      if (error) {
        this.dealAllError(error);
        return;
      }
      hilog.info(0x0000, 'testTag', 'onChangeAgreementStatus agreementStatus: %{public}d', agreementStatus);
    })
    .onClickEvent((error: BusinessError, clickEvent: loginComponentManager.ClickEvent) => {
      if (error) {
        this.dealAllError(error);
        return;
      }
      hilog.info(0x0000, 'testTag', 'onClickEvent clickEvent: %{public}d', clickEvent);
    });

  // Handle the error.
  dealAllError(error: BusinessError): void {
    hilog.error(0x0000, 'testTag', 'Failed to login, errorCode=%{public}d, errorMsg=%{public}s', error.code,
      error.message);
  }

  build() {
    if (this.show) {
      Stack() {
        LoginPanel({
          show: this.show,
          params: {
            appInfo: {
              appIcon: $r('app.media.app_icon'),
              appName:'App name',
            },
            privacyText: this.privacyText,
            // Obtain the anonymous mobile number by referring to the Account Kit Development Guide.
            anonymousPhoneNumber: '139******99',
            // verifyPhoneNumber: indicates whether to display the SMS verification code screen provided by Account Kit if a HUAWEI ID user did not perform SMS verification in the past 90 days.
            verifyPhoneNumber: true,
            loginType: loginComponentManager.LoginType.QUICK_LOGIN,
            // If both optionalLoginAreaAttr and optionalLoginButtonAttr exist, optionalLoginAreaAttr is displayed first.
            optionalLoginAreaAttr: { iconArray: this.iconArray },
            optionalLoginButtonAttr: { text: 'Other sign-in options' }
          },
          controller: this.controller
        })
      }
      .height('100%')
      .width('100%')
    }
  }
}

LoginWithHuaweiIDButtonParams

Defines the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Type

Read-Only

Optional

Description

style

Style

No

No

Style of the LoginWithHuaweiIDButton component.

borderRadius

number

No

Yes

Rounded corner radius of the button border.

Unit: vp

NOTE:

If this attribute is not set, full-rounded corners are used by default for phones, tablets, and 2-in-1 devices.

iconRadius

number

No

Yes

Radius of a button of the icon type.

Default value: 24

Unit: vp

supportDarkMode

boolean

No

Yes

Indicates whether the button style changes along with the system dark and light color modes.

true: yes

false: no

Default value: true

loginType

LoginType

No

Yes

HUAWEI ID sign-in type. The default value is LoginType.ID.

For one-tap sign-in, use LoginType.QUICK_LOGIN.

textAndIconStyle

boolean

No

Yes

Indicates whether to display the HUAWEI ID sign-in button in the icon & text style.

true: yes

false: no (the button supports only the text style)

This parameter is valid only when loginType is not set to LoginType.QUICK_LOGIN and style is set to BUTTON_RED, BUTTON_WHITE, BUTTON_WHITE_OUTLINE, BUTTON_BLACK, or BUTTON_GRAY.

Start version: 5.0.0(12)

customButtonParams

CustomButtonParams

No

Yes

Style parameters of the BUTTON_CUSTOM button.

Start version: 5.0.0(12)

verifyPhoneNumber

boolean

No

Yes

Indicates whether to display the SMS verification code screen provided by Account Kit if a HUAWEI ID user did not perform SMS verification in the past 90 days.

true: yes

false: no The app needs to check whether the mobile number is up-to-date.

Default value: true

Start version: 5.0.0(12)

extraStyle

ExtraStyle

No

Yes

If your app wants to use the styles other than the fixed styles provided by HUAWEI ID, you can call this API to set the desired style.

Start version: 5.0.0(12)

loginButtonTextType

LoginButtonTextType

No

Yes

If loginType is set to LoginType.QUICK_LOGIN, this parameter can be passed to specify the button text type.

The default value is LoginButtonTextType.QUICK_LOGIN.

Start version: 5.0.0(12)

Style

Defines styles of the HUAWEI ID sign-in button.

If the HUAWEI ID sign-in button styles listed below cannot meet your requirements, please refer to this guide.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Name

Value

Description

BUTTON_RED

0

Button with white text and red background. The font size is adaptive to the width and height of the button, ranging from 9 to 16.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

BUTTON_WHITE

1

Button with black text and white background. The font size is adaptive to the width and height of the button, ranging from 9 to 16.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

BUTTON_WHITE_OUTLINE

2

Button with black text, white background, and a border. The font size is adaptive to the width and height of the button, ranging from 9 to 16.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

BUTTON_BLACK

3

Button with white text and black background. The font size is adaptive to the width and height of the button, ranging from 9 to 16.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

ICON_RED

4

White icon with the red background. This style is available only for the HUAWEI ID sign-in button.

Rules for the HUAWEI ID sign-in button

ICON_WHITE

5

Red icon with the white background. This style is available only for the HUAWEI ID sign-in button.

Rules for the HUAWEI ID sign-in button

ICON_WHITE_OUTLINE

6

Red icon with the white background and a border. This style is available only for the HUAWEI ID sign-in button.

Rules for the HUAWEI ID sign-in button

ICON_BLACK

7

White icon with the black background. This style is available only for the HUAWEI ID sign-in button.

Rules for the HUAWEI ID sign-in button

ICON_GRAY

8

Red icon with the gray background. This style is available only for the HUAWEI ID sign-in button.

Rules for the HUAWEI ID sign-in button

Start version: 5.0.0(12)

BUTTON_GRAY

9

Button with black text and gray background. The font size is adaptive to the width and height of the button, ranging from 9 to 16.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

Start version: 5.0.0(12)

BUTTON_CUSTOM

10

Button with custom effects including text color, background color, and rounded corner. The font size is adaptive to the width and height of the button, ranging from 9 to 16. You can use CustomButtonParams to set custom button parameters and adapt to the dark and light color modes.

Check the rules from the following links based on your development scenario.

Rules for the one-tap HUAWEI ID sign-in button

Rules for the HUAWEI ID sign-in button

NOTICE:

The button of this style can display plaintext only.

Start version: 5.0.0(12)

LoginButtonTextType

Enumerates the text displayed on the one-tap HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Value

Description

QUICK_LOGIN

0

The button text indicates one-tap sign-in with HUAWEI ID.

QUICK_REGISTRATION

1

The button text indicates one-tap registration with HUAWEI ID.

CustomButtonParams

Defines parameters of the BUTTON_CUSTOM button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

fontColor

FontColor

No

Yes

Text color of the LoginWithHuaweiIDButton button.

Default value: FontColor.WHITE

backgroundColor

ResourceColor

No

Yes

Background color of the LoginWithHuaweiIDButton button.

Default value: Red

FontColor

Defines text colors that can be used by the BUTTON_CUSTOM button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Value

Description

WHITE

0

White text of the HUAWEI ID sign-in button.

BLACK

1

Black text of the HUAWEI ID sign-in button.

ExtraStyle

Defines extended parameters of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

buttonStyle

ButtonStyle

No

Yes

Custom button style, for which you can dynamically set some attributes as needed.

customButtonStateStyles

StateStyles

No

Yes

Button state styles, which you can define as needed. This parameter is valid only for buttons of the BUTTON_CUSTOM type.

textAndIconButtonParams

TextAndIconButtonParams

No

Yes

For buttons set to an image & text style, this parameter allows you to adjust the spacing between the text and image.

iconButtonParams

IconButtonParams

No

Yes

For icon-only buttons, this parameter allows you to customize the icon's radius.

RadialGradient

Defines the radial gradient style for the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

center

[Length, Length]

No

No

Center of the radial gradient, that is, the coordinates relative to the upper left corner of the current component.

radius

number | string

No

No

Radius of the radial gradient.

Value range: [0, +∞)

If a value smaller than 0 is set, it will be treated as 0.

colors

Array<[ResourceColor, number]>

No

No

Array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.

repeating

boolean

No

Yes

Indicates whether the colors are repeated.

The default value is false.

SweepGradient

Defines the angular gradient style for the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

center

[Length, Length]

No

No

Center of the angular gradient, that is, the coordinates relative to the upper left corner of the current component.

start

number | string

No

Yes

Start point of the angular gradient.

The default value is 0.

If a value smaller than 0 is set, it will be treated as 0. If a value greater than 360 is set, it will be treated as 360.

When start, end, or rotation is specified with a string, the string must be a number or a number followed by one of the following units: deg, rad, grad, and turn. Valid value examples are "90", "90deg", and "1.57rad".

end

number | string

No

Yes

End point of the angular gradient.

The default value is 0.

If a value smaller than 0 is set, it will be treated as 0. If a value greater than 360 is set, it will be treated as 360.

When start, end, or rotation is specified with a string, the string must be a number or a number followed by one of the following units: deg, rad, grad, and turn. Valid value examples are "90", "90deg", and "1.57rad".

rotation

number | string

No

Yes

Rotation angle of the angle gradient.

The default value is 0.

If a value smaller than 0 is set, it will be treated as 0. If a value greater than 360 is set, it will be treated as 360.

When start, end, or rotation is specified with a string, the string must be a number or a number followed by one of the following units: deg, rad, grad, and turn. Valid value examples are "90", "90deg", and "1.57rad".

colors

Array<[ResourceColor, number]>

No

No

Array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.

repeating

boolean

No

Yes

Indicates whether the colors are repeated.

The default value is false.

ButtonStyle

Defines common attributes of the HUAWEI ID sign-in button. Use new loginComponentManager.ButtonStyle() to construct an instance.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

[h2]buttonSize

buttonSize(value: ButtonSize): ButtonStyle

Sets the width and height of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ButtonSize

Yes

When the button type is icon-only, its width and height are the same. The non-undefined minimum values of value.width and value.height are used. If both value.width and value.height are undefined, the value is twice that of iconRadius in LoginWithHuaweiIDButtonParams. If iconRadius is also undefined, the default value 48 vp is used.

When the button type is non-icon-only, set its width and height through value.width and value.height respectively. When value.width or value.height is undefined, the width or height of the button is the width or height of the parent layout.

NOTICE:

When setting the width and height of the button, make sure that the width and height of the parent layout must be greater than or equal to those of the button.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]fontSize

fontSize(value: Length): ButtonStyle

Sets the font size of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

Length

Yes

Font size of the text on the HUAWEI ID sign-in button that is an image & text button or a text-only button. According to the visual specifications for HUAWEI ID sign-in, the recommended value range is 30% to 50% of the button height.

If this parameter is not passed, the font size ranges from 9 vp to 16 vp and is adaptive to the button width.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]fontColor

fontColor(value: ResourceColor | FontColor): ButtonStyle

Sets the text color of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ResourceColor | FontColor

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the text color of the button. If the fontColor attribute of CustomButtonParams has been set, the value of this attribute is used preferentially.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]fontWeight

fontWeight(value: string | number | FontWeight): ButtonStyle

Sets the font weight of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

string | number | FontWeight

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the font weight of the button. The value of the number type is [100, 900]. The interval is 100. A larger value indicates a thicker font. When the value is without the range, 400 is used as the value. For the string type, only strings that represent a number, for example, 400, and the following enumerated values of FontWeight are supported: bold, bolder, lighter, regular, and medium.

The default value is FontWeight.Medium, and the corresponding number value is 500.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]fontFamily

fontFamily(value: ResourceStr): ButtonStyle

Sets the font family of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ResourceStr

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the font family of the button.

The default value is HarmonyOS Sans.

Currently, HarmonyOS Sans and custom font families are supported.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]backgroundColor

backgroundColor(value: ResourceColor): ButtonStyle

Sets the background color of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ResourceColor

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the background color of the button.

If the backgroundColor attribute of CustomButtonParams has been set, the value of this attribute is used preferentially.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]backgroundEffect

backgroundEffect(value: BackgroundEffectOptions): ButtonStyle

Sets the background attributes of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

BackgroundEffectOptions

Yes

When the button type is BUTTON_CUSTOM, this parameter can be used to set the background attributes of the button, including the saturation, brightness, and color.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]backgroundBrightness

backgroundBrightness(value: BackgroundBrightnessOptions): ButtonStyle

Sets the background brightness of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

BackgroundBrightnessOptions

Yes

When the button type is BUTTON_CUSTOM, this parameter can be used to set the background brightness of the button, including the brightness change rate and brightness increase degree.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]linearGradient

linearGradient(value: LinearGradient): ButtonStyle

Sets the linear gradient effect for the background color of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

LinearGradient

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the linear gradient effect for the background color of the button. For details, please refer to here.

NOTICE:

When this attribute is used, set the button's background color to transparent to avoid jagged edges, for example, backgroundColor(Color.Transparent).

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]sweepGradient

sweepGradient(value: SweepGradient): ButtonStyle

Sets the angular gradient effect for the background color of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

SweepGradient

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the angular gradient effect for the background color of the button.

NOTICE:

When this attribute is used, set the button's background color to transparent to avoid jagged edges, for example, backgroundColor(Color.Transparent).

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]radialGradient

radialGradient(value: RadialGradient): ButtonStyle

Sets the radial gradient effect for the background color of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

RadialGradient

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the radial gradient effect for the background color of the button.

NOTICE:

When this attribute is used, set the button's background color to transparent to avoid jagged edges, for example, backgroundColor(Color.Transparent).

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]shadow

shadow(value: ShadowOptions | ShadowStyle): ButtonStyle

Sets the shadow effect of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ShadowOptions | ShadowStyle

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the shadow effect of the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]opacity

opacity(value: number | Resource): ButtonStyle

Sets the opacity of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

number | Resource

Yes

Opacity of a component. The value ranges from 0 to 1. The value 1 means opaque, and 0 means completely transparent so that the component is hidden but is placed in the layout.

The default value is 1.

When the button type is BUTTON_CUSTOM, this parameter is used to set the opacity of the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]border

border(value: BorderOptions): ButtonStyle

Sets the border style of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

BorderOptions

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the border style of the button. For details, please refer to here.

NOTICE:

When setting an inner border, make sure to allocate enough space within the parent component to accommodate the button. The parent component's width and height should exceed the button's.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]borderImage

borderImage(value: BorderImageOption): ButtonStyle

Sets the image border style of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

BorderImageOption

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the image border style of the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]outline

outline(value: OutlineOptions): ButtonStyle

Sets the outline style of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

OutlineOptions

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the outline style of the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]hoverEffect

hoverEffect(value: HoverEffect): ButtonStyle

Sets the hover effect of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

HoverEffect

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the hover effect of the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]clickEffect

clickEffect(value: ClickEffect): ButtonStyle

Sets the effect of a tap on the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

ClickEffect

Yes

When the button type is BUTTON_CUSTOM, this parameter is used to set the effect of a tap on the button. For details, please refer to here.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

[h2]loadingStyle

loadingStyle(value: LoadingStyle): ButtonStyle

Sets whether to display the loading state of the HUAWEI ID sign-in button during sign-in.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

value

LoadingStyle

Yes

Indicates whether the button is in the loading state during sign-in.

By default, the loading status does not appear.

NOTICE:

The loading status is not supported for the icon-only button. Therefore, this parameter does not take effect for such a button.

Returns:

Type

Description

ButtonStyle

Common attributes of the HUAWEI ID sign-in button.

ButtonSize

Defines the dimensions of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

width

Length

No

Yes

Width of the HUAWEI ID sign-in button.

height

Length

No

Yes

Height of the HUAWEI ID sign-in button.

LoadingStyle

Defines whether to display the loading state of the HUAWEI ID sign-in button during sign-in.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

show

boolean

No

Yes

Indicates whether the button is in the loading state during sign-in.

The default value is false, indicating that the loading status does not appear.

TextAndIconButtonParams

Defines the spacing between the text and image when the HUAWEI ID sign-in button contains both text and image.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

textAndIconMargin

number

No

Yes

Spacing between the text and image on the HUAWEI ID sign-in button. The value ranges from 4 vp to 16 vp. The default value is 8 vp. If the value is smaller than 4 vp, it will be set to 4 vp. If it is greater than 16 vp, it will be set to 16 vp.

IconButtonParams

Defines the radius of the Huawei icon when the HUAWEI ID sign-in button is an icon-only button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

logoRadius

number

No

Yes

Radius of the Huawei icon on the HUAWEI ID sign-in button that is icon-only.

The default value is 14 vp, and the minimum value is 8 vp. The value range is 20% to 32% of the button height. If the value is smaller than 20%, it will be set to 20%. If it is greater than 32%, it will be set to 32%.

StateStyles

Defines state styles of the HUAWEI ID sign-in button.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Name

Type

Read-Only

Optional

Description

normal

ButtonStyle

No

Yes

Common style of the HUAWEI ID sign-in button in normal state.

pressed

ButtonStyle

No

Yes

Common style of the HUAWEI ID sign-in button in tapped state.

disabled

ButtonStyle

No

Yes

Common style of the HUAWEI ID sign-in button in unavailable state.

focused

ButtonStyle

No

Yes

Common style of the HUAWEI ID sign-in button in focused state.

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which is used to execute tap callbacks in the component.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

[h2]setAgreementStatus

setAgreementStatus(agreementStatus: AgreementStatus): LoginWithHuaweiIDButtonController

Sets the status of the user service agreement.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

agreementStatus

AgreementStatus

Yes

When the sign-in type is LoginType.QUICK_LOGIN, the agreement status must be set to ACCEPTED to complete HUAWEI ID sign-in.

When the sign-in type is not LoginType.QUICK_LOGIN, if HUAWEI ID sign-in is allowed only after the user accepts the agreement, set the agreement status to NOT_ACCEPTED first, and change the status to ACCEPTED after the agreement is accepted.

Returns:

Type

Description

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickEvent

onClickEvent(callback: AsyncCallback<ClickEvent>): LoginWithHuaweiIDButtonController

Tap event related to the HUAWEI ID sign-in button. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<ClickEvent>

Yes

Callback function.

When a user taps the HUAWEI ID sign-in button, err is undefined, and data is the ClickEvent object obtained. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]onClickLoginWithHuaweiIDButton

onClickLoginWithHuaweiIDButton(callback: AsyncCallback<HuaweiIDCredential>): LoginWithHuaweiIDButtonController

Registers an event triggered to return the result of one-tap HUAWEI ID sign-in. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 4.1.0(11)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<HuaweiIDCredential>

Yes

Callback function.

If the HUAWEI ID sign-in is successful, err is undefined and data is the HuaweiIDCredential object. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which can be used to register tap events in the component or call methods provided by the component.

Error codes:

For details about the error codes, please refer to ArkTS Error Codes, Account Management Error Codes, and Universal Error Codes.

Error Code

Error Message

401

Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.

1001500001

Failed to check the fingerprint of the app bundle.

1001500002

This error code is reported when a request is already being processed.

1001500003

The scopes or permissions are not supported.

1001502001

The user has not logged in with HUAWEI ID.

1001502002

The application is not authorized.

1001502003

Invalid input parameter value.

1001502005

Network error.

1001502009

Internal error.

1001502012

The user canceled the authorization.

1001502014

The app does not have the required scopes or permissions.

12300001

System service works abnormally.

1005300001

The user did not accept the agreement.

[h2]setEnabled

setEnabled(enabled: boolean): LoginWithHuaweiIDButtonController

Specifies whether the HUAWEI ID sign-in button can be tapped.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

enabled

boolean

Yes

Indicates whether a button can be tapped.

true (default value): The HUAWEI ID sign-in button is highlighted and can be tapped; false: The HUAWEI ID sign-in button is dimmed and cannot be tapped.

Returns:

Type

Description

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which can be used to register tap events in the component or call methods provided by the component.

[h2]continueLogin

continueLogin(callback: AsyncCallback<void>): LoginWithHuaweiIDButtonController

If a user does not accept the agreements, the agreement dialog box is displayed when the user taps the sign-in button. This API is called when the user taps the accept & sign-in button. This API returns the result asynchronously through a callback.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.AuthenticationServices.HuaweiID.UIComponent

Start version: 5.0.0(12)

Parameters:

Name

Type

Mandatory

Description

callback

AsyncCallback<void>

Yes

Callback function.

If the operation for a user to tap the accept & sign-in button is successful, err is undefined. Otherwise, an error object will be returned.

Returns:

Type

Description

LoginWithHuaweiIDButtonController

LoginWithHuaweiIDButton component controller, which can be used to register tap events in the component or call methods provided by the component.

Error codes:

For details about the error codes, please refer to ArkTS Error Codes.

Error Code

Error Message

1005300002

The user did not click the HUAWEI ID login button.

Example:
import { util } from '@kit.ArkTS';
import { authentication, loginComponentManager, LoginWithHuaweiIDButton } from '@kit.AccountKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction, router } from '@kit.ArkUI';

@Entry
@Component
struct QuickLoginButtonComponent {
  logTag: string = 'QuickLoginButtonComponent';
  domainId: number = 0x0000;
  // Anonymous mobile number.
  @State quickLoginAnonymousPhone: string = '';
  // Indicates whether the agreements are accepted.
  @State isSelected: boolean = false;
  // Link to the HUAWEI ID User Authentication Agreement. The link here is only an example. For maintainability and security reasons, it is recommended that the domain name be not hardcoded locally during actual development.
  private static USER_AUTHENTICATION_PROTOCOL: string =
    'https://privacy.consumer.huawei.com/legal/id/authentication-terms.htm?code=CN&language=zh-CN';
  private static USER_SERVICE_TAG = 'User Service Agreement';
  private static PRIVACY_TAG = 'Privacy Policy';
  private static USER_AUTHENTICATION_TAG = 'HUAWEI ID User Authentication Agreement';
  // Define the Privacy Policy, User Service Agreement, and HUAWEI ID User Authentication Agreement related to LoginWithHuaweiIDButton.
  privacyText: loginComponentManager.PrivacyText[] = [{
    text: 'I have read and agree to the',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: 'User Service Agreement',
    tag: QuickLoginButtonComponent.USER_SERVICE_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: 'Privacy Policy',
    tag: QuickLoginButtonComponent.PRIVACY_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: 'and',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }, {
    text: 'HUAWEI ID User Authentication Agreement',
    tag: QuickLoginButtonComponent.USER_AUTHENTICATION_TAG,
    type: loginComponentManager.TextType.RICH_TEXT
  }, {
    text: '.',
    type: loginComponentManager.TextType.PLAIN_TEXT
  }];
  // Construct the controller of LoginWithHuaweiIDButton.
  controller: loginComponentManager.LoginWithHuaweiIDButtonController =
    new loginComponentManager.LoginWithHuaweiIDButtonController()
      /**
       * For an app with a custom sign-in UI, if the user does not accept the agreements, set the agreement status to NOT_ACCEPTED.
       * Set the agreement status to ACCEPTED once the user accepts the agreements. The one-tap HUAWEI ID sign-in function is available only when the agreement status is ACCEPTED.
       */
      .setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED)
      .onClickLoginWithHuaweiIDButton((error: BusinessError | undefined,
        response: loginComponentManager.HuaweiIDCredential) => {
        this.handleLoginWithHuaweiIDButton(error, response);
      })
      .onClickEvent((error: BusinessError, clickEvent: loginComponentManager.ClickEvent) => {
        if (error) {
          hilog.error(this.domainId, this.logTag,
            `Failed to click. errCode is ${error.code}, errMessage is ${error.message}`);
          return;
        }
        hilog.info(this.domainId, this.logTag, `onClickEvent clickEvent: ${clickEvent}`);
      });
  agreementDialog: CustomDialogController = new CustomDialogController({
    builder: AgreementDialog({
      privacyText: this.privacyText,
      cancel: () => {
        this.agreementDialog.close();
        this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED);
      },
      confirm: () => {
        this.agreementDialog.close();
        this.isSelected = true;
        this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.ACCEPTED);
        // Call this method to complete accepting the agreements and signing in at the same time, with no need to tap the sign-in button again.
        this.controller.continueLogin((error: BusinessError) => {
          if (error) {
            hilog.error(this.domainId, this.logTag,
              `Failed to login with agreementDialog. errCode is ${error.code}, errMessage is ${error.message}`);
          } else {
            hilog.info(this.domainId, this.logTag,
              'Succeeded in clicking agreementDialog continueLogin.');
          }
        });
      },
      clickHyperlinkText: () => {
        this.agreementDialog.close();
        this.jumpToPrivacyWebView();
      }
    }),
    autoCancel: false,
    alignment: DialogAlignment.Center,
  });

  // Pass the data required for page rendering, such as the anonymous mobile number.
  aboutToAppear(): void {
    this.getQuickLoginAnonymousPhone();
  }

  // Toast message.
  showToast(resource: string) {
    try {
      promptAction.showToast({
        message: resource,
        duration: 2000
      });
    } catch (error) {
      const message = (error as BusinessError).message
      const code = (error as BusinessError).code
      hilog.error(this.domainId, this.logTag, `showToast args  errCode is ${code}, errMessage is ${message}`);
    }
  }

  // Redirect to the HUAWEI ID User Authentication Agreement page. This page needs to be configured in the main_pages.json file of the project.
  jumpToPrivacyWebView() {
    router.pushUrl({
      // Add the ohos.permission.INTERNET permission to module.json5.
      url: 'pages/WebPage',
      params: {
        isFromDialog: true,
        url: QuickLoginButtonComponent.USER_AUTHENTICATION_PROTOCOL,
      }
    }, (err) => {
      if (err) {
        hilog.error(this.domainId, this.logTag,
          `Failed to jumpToPrivacyWebView, errCode is ${err.code}, errMessage is ${err.message}`);
      }
    });
  }

  handleLoginWithHuaweiIDButton(error: BusinessError | undefined,
    response: loginComponentManager.HuaweiIDCredential) {
    if (error) {
      hilog.error(this.domainId, this.logTag,
        `Failed to login with LoginWithHuaweiIDButton. errCode is ${error.code}, errMessage is ${error.message}`);
      if (error.code === ErrorCode.ERROR_CODE_NETWORK_ERROR) {
        AlertDialog.show(
          {
            message: "No Internet connection. Check your network settings.",
            offset: { dx: 0, dy: -12 },
            alignment: DialogAlignment.Bottom,
            autoCancel: false,
            confirm: {
              value: "OK",
              action: () => {
              }
            }
          }
        );
      } else if (error.code === ErrorCode.ERROR_CODE_AGREEMENT_STATUS_NOT_ACCEPTED) {
        // If the agreements are not accepted, a dialog box that asks you to accept the agreements and sign in will be displayed. This callback way is recommended.
        this.agreementDialog.open();
      } else if (error.code === ErrorCode.ERROR_CODE_LOGIN_OUT) {
        // Message displayed when no HUAWEI ID is signed in.
        this.showToast("HUAWEI ID not signed in. Try again.")
      } else if (error.code === ErrorCode.ERROR_CODE_NOT_SUPPORTED) {
        // Message displayed when the scope or permission is not supported.
        this.showToast("Unsupported scope or permission.");
      } else if (error.code === ErrorCode.ERROR_CODE_PARAMETER_ERROR) {
        // Parameter error message.
        this.showToast ("Parameter error.");
      } else {
        // Messages displayed upon other exceptions.
        this.showToast('Service or network exception. Try again later.');
      }
      return;
    }
    try {
      if (this.isSelected) {
        if (response) {
          hilog.info(this.domainId, this.logTag, 'Succeeded in clicking LoginWithHuaweiIDButton.');
          // Use the information below as needed.
          const authCode = response.authorizationCode;
          const openID = response.openID;
          const unionID = response.unionID;
          const idToken = response.idToken;
        }
      } else {
        this.agreementDialog.open();
      }
    } catch (err) {
      hilog.error(this.domainId, this.logTag,
        `Failed to login with LoginWithHuaweiIDButton, errCode: ${err.code}, errMessage: ${err.message}`);
      AlertDialog.show(
        {
          message: 'Service or network exception. Try again later.',
          offset: { dx: 0, dy: -12 },
          alignment: DialogAlignment.Bottom,
          autoCancel: false,
          confirm: {
            value: 'OK',
            action: () => {
            }
          }
        }
      );
    }
  }

  // Handle the error.
  dealAllError(error: BusinessError): void {
    hilog.error(this.domainId, this.logTag,
      `Failed to get quickLoginAnonymousPhone, errorCode is ${error.code}, errorMessage is ${error.message}`);
  }

  getQuickLoginAnonymousPhone() {
    // Create an authorization request and set parameters.
    const authRequest = new authentication.HuaweiIDProvider().createAuthorizationWithHuaweiIDRequest();
    /**
     * To obtain an anonymous mobile number, the quickLoginAnonymousPhone scope must be passed.
     * To obtain the anonymous mobile number, make sure that your app has got the quickLoginMobilePhone scope first.
     */
    authRequest.scopes = ['quickLoginAnonymousPhone'];
    // Used to prevent cross-site request forgery.
    authRequest.state = util.generateRandomUUID();
    // In the one-tap HUAWEI ID sign-in scenario, this parameter must be set to false.
    authRequest.forceAuthorization = false;
    const controller = new authentication.AuthenticationController();
    try {
      controller.executeRequest(authRequest).then((response: authentication.AuthorizationWithHuaweiIDResponse) => {
      // The UnionID, OpenID, and anonymous mobile number are obtained.
        const unionID = response.data?.unionID;
        const openID = response.data?.openID;
        const anonymousPhone = response.data?.extraInfo?.quickLoginAnonymousPhone as string;
        if (anonymousPhone) {
          hilog.info(this.domainId, this.logTag, 'Succeeded in authentication.');
          this.quickLoginAnonymousPhone = anonymousPhone;
          return;
        }
        hilog.info(this.domainId, this.logTag, 'Succeeded in authentication. AnonymousPhone is empty.');
        // If the anonymous mobile number fails to be obtained, the custom sign-in screen of the app will appear.
      }).catch((error: BusinessError) => {
        this.dealAllError(error);
      })
    } catch (error) {
      this.dealAllError(error);
    }
  }

  build() {
    Scroll() {
      Column() {
        Column() {
          Column() {
            Image($r('app.media.app_icon'))
              .width(48)
              .height(48)
              .draggable(false)
              .copyOption(CopyOptions.None)
              .onComplete(() => {
                hilog.info(this.domainId, this.logTag, 'appIcon loading success.');
              })
              .onError(() => {
                hilog.error(this.domainId, this.logTag, 'appIcon loading fail.');
              })

            Text($r('app.string.app_name'))
              .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
              .fontWeight(FontWeight.Medium)
              .fontWeight(FontWeight.Bold)
              .maxFontSize($r('sys.float.ohos_id_text_size_headline8'))
              .minFontSize($r('sys.float.ohos_id_text_size_body1'))
              .maxLines(1)
              .fontColor($r('sys.color.ohos_id_color_text_primary'))
              .constraintSize({ maxWidth: '100%' })
              .margin({
                top: 12,
              })

            Text('App description')
              .fontSize($r('sys.float.ohos_id_text_size_body2'))
              .fontColor($r('sys.color.ohos_id_color_text_secondary'))
              .fontFamily($r('sys.string.ohos_id_text_font_family_regular'))
              .fontWeight(FontWeight.Regular)
              .constraintSize({ maxWidth: '100%' })
              .margin({
                top: 8,
              })
          }.margin({
            top: 100
          })

          Column() {
            Text(this.quickLoginAnonymousPhone)
              .fontSize(36)
              .fontColor($r('sys.color.ohos_id_color_text_primary'))
              .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
              .fontWeight(FontWeight.Bold)
              .lineHeight(48)
              .textAlign(TextAlign.Center)
              .maxLines(1)
              .constraintSize({ maxWidth: '100%', minHeight: 48 })

            Text('Mobile number bound to a HUAWEI ID')
              .fontSize($r('sys.float.ohos_id_text_size_body2'))
              .fontColor($r('sys.color.ohos_id_color_text_secondary'))
              .fontFamily($r('sys.string.ohos_id_text_font_family_regular'))
              .fontWeight(FontWeight.Regular)
              .lineHeight(19)
              .textAlign(TextAlign.Center)
              .maxLines(1)
              .constraintSize({ maxWidth: '100%' })
              .margin({
                top: 8
              })
          }.margin({
            top: 64
          })

          Column() {
            LoginWithHuaweiIDButton({
              params: {
                // Styles supported by LoginWithHuaweiIDButton.
                style: loginComponentManager.Style.BUTTON_RED,
                // The one-tap HUAWEI ID sign-in button is in loading state during user sign-in.
                extraStyle: {
                  buttonStyle: new loginComponentManager.ButtonStyle().loadingStyle({
                    show: true
                  })
                },
                // Rounded corner radius of LoginWithHuaweiIDButton.
                borderRadius: 24,
                // Sign-in types supported by LoginWithHuaweiIDButton.
                loginType: loginComponentManager.LoginType.QUICK_LOGIN,
                // The button style of LoginWithHuaweiIDButton supports switching along with the change between light and dark modes of the device system.
                supportDarkMode: true,
                // verifyPhoneNumber: indicates whether to display the SMS verification code screen provided by Account Kit if a HUAWEI ID user did not perform SMS verification in the past 90 days.
                verifyPhoneNumber: true
              },
              controller: this.controller
            })
          }
          .height(40)
          .margin({
            top: 56
          })

          Column() {
            Button({
              type: ButtonType.Capsule,
              stateEffect: true
            }) {
              Text('Other sign-in options')
                .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
                .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
                .fontWeight(FontWeight.Medium)
                .fontSize($r('sys.float.ohos_id_text_size_button1'))
                .focusable(true)
                .focusOnTouch(true)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
                .maxLines(1)
                .padding({ left: 8, right: 8 })
            }
            .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
            .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
            .fontWeight(FontWeight.Medium)
            .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
            .focusable(true)
            .focusOnTouch(true)
            .constraintSize({ minHeight: 40 })
            .width('100%')
            .onClick(() => {
              hilog.info(this.domainId, this.logTag, 'click optionalLoginButton.');
            })
          }.margin({ top: 16 })
        }.width('100%')

        Row() {
          Row() {
            Checkbox({ name: 'privacyCheckbox', group: 'privacyCheckboxGroup' })
              .width(24)
              .height(24)
              .focusable(true)
              .focusOnTouch(true)
              .margin({ top: 0 })
              .select(this.isSelected)
              .onChange((value: boolean) => {
                if (value) {
                  this.isSelected = true;
                  this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.ACCEPTED);
                } else {
                  this.isSelected = false;
                  this.controller.setAgreementStatus(loginComponentManager.AgreementStatus.NOT_ACCEPTED);
                }
                hilog.info(this.domainId, this.logTag, `agreementChecked: ${value}`);
              })
          }

          Row() {
            Text() {
              ForEach(this.privacyText, (item: loginComponentManager.PrivacyText) => {
                if (item?.type === loginComponentManager.TextType.PLAIN_TEXT && item?.text) {
                  Span(item?.text)
                    .fontColor($r('sys.color.ohos_id_color_text_secondary'))
                    .fontFamily($r('sys.string.ohos_id_text_font_family_regular'))
                    .fontWeight(FontWeight.Regular)
                    .fontSize($r('sys.float.ohos_id_text_size_body3'))
                } else if (item?.type === loginComponentManager.TextType.RICH_TEXT && item?.text) {
                  Span(item?.text)
                    .fontColor($r('sys.color.ohos_id_color_text_primary_activated'))
                    .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
                    .fontWeight(FontWeight.Medium)
                    .fontSize($r('sys.float.ohos_id_text_size_body3'))
                    .focusable(true)
                    .focusOnTouch(true)
                    .onClick(() => {
                      // The app needs to implement the agreement redirection logic based on item.tag.
                      hilog.info(this.domainId, this.logTag, `click privacy text tag: ${item.tag}`);
                      // HUAWEI ID User Authentication Agreement
                      if (item.tag === QuickLoginButtonComponent.USER_AUTHENTICATION_TAG) {
                        this.jumpToPrivacyWebView();
                      }
                    })
                }
              }, (item: loginComponentManager.PrivacyText) => item.text.toString())
            }
            .width('100%')
          }
          .margin({ left: 12 })
          .layoutWeight(1)
          .constraintSize({ minHeight: 24 })
        }
        .alignItems(VerticalAlign.Top)
        .margin({
          bottom: 44
        })
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .constraintSize({ minHeight: '100%' })
      .margin({
        left: 16,
        right: 16
      })
    }
    .width('100%')
    .height('100%')
  }
}

@CustomDialog
export struct AgreementDialog {
  logTag: string = 'AgreementDialog';
  domainId: number = 0x0000;
  dialogController?: CustomDialogController;
  cancel: () => void = () => {
  };
  confirm: () => void = () => {
  };
  clickHyperlinkText: () => void = () => {
  };
  privacyText: loginComponentManager.PrivacyText[] = [];
  private static USER_AUTHENTICATION_TAG = 'HUAWEI ID User Authentication Agreement';

  build() {
    Column() {
      Row() {
        Text('User Service Agreement and Privacy Policy')
          .id('loginPanel_agreement_dialog_privacy_title')
          .maxFontSize($r('sys.float.ohos_id_text_size_headline8'))
          .minFontSize($r('sys.float.ohos_id_text_size_body1'))
          .fontColor($r('sys.color.ohos_id_color_text_primary'))
          .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
          .fontWeight(FontWeight.Bold)
          .textAlign(TextAlign.Center)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
          .maxLines(2)
      }
      .alignItems(VerticalAlign.Center)
      .constraintSize({ minHeight: 56, maxWidth: 400 })
      .margin({
        left: $r('sys.float.ohos_id_max_padding_start'),
        right: $r('sys.float.ohos_id_max_padding_start')
      })

      Row() {
        Text() {
          ForEach(this.privacyText, (item: loginComponentManager.PrivacyText) => {
            if (item?.type === loginComponentManager.TextType.PLAIN_TEXT && item?.text) {
              Span(item?.text)
                .fontSize($r('sys.float.ohos_id_text_size_body1'))
                .fontColor($r('sys.color.ohos_id_color_text_primary'))
                .fontFamily($r('sys.string.ohos_id_text_font_family_regular'))
                .fontWeight(FontWeight.Regular)
            } else if (item?.type === loginComponentManager.TextType.RICH_TEXT && item?.text) {
              Span(item?.text)
                .fontSize($r('sys.float.ohos_id_text_size_body1'))
                .fontColor('#CE0E2D')
                .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
                .fontWeight(FontWeight.Medium)
                .focusable(true)
                .focusOnTouch(true)
                .onClick(() => {
                      // The app needs to implement the agreement redirection logic based on item.tag.
                  hilog.info(this.domainId, this.logTag, `click privacy text tag: ${item.tag}`);
                      // HUAWEI ID User Authentication Agreement
                  if (item.tag === AgreementDialog.USER_AUTHENTICATION_TAG) {
                    hilog.info(this.domainId, this.logTag, 'AgreementDialog click.');
                    this.clickHyperlinkText();
                  }
                })
            }
          }, (item: loginComponentManager.PrivacyText) => item.text.toString())
        }
        .width('100%')
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .maxLines(10)
        .textAlign(TextAlign.Start)
        .focusable(true)
        .focusOnTouch(true)
        .padding({ left: 24, right: 24 })
      }.width('100%')

      Flex({
        direction: FlexDirection.Row
      }) {
        Button('Cancel',
          { type: ButtonType.Capsule, stateEffect: true })
          .id('loginPanel_agreement_cancel_btn')
          .fontColor($r('sys.color.ohos_id_color_text_primary'))
          .fontSize($r('sys.float.ohos_id_text_size_button1'))
          .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
          .backgroundColor(Color.Transparent)
          .fontWeight(FontWeight.Medium)
          .focusable(true)
          .focusOnTouch(true)
          .constraintSize({ minHeight: 40, maxWidth: 400 })
          .width('50%')
          .onClick(() => {
            hilog.info(this.domainId, this.logTag, 'AgreementDialog cancel.');
            this.cancel();
          })

        Button('Accept & sign in',
          { type: ButtonType.Capsule, stateEffect: true })
          .id('loginPanel_agreement_dialog_huawei_id_login_btn')
          .fontColor(Color.White)
          .backgroundColor('#CE0E2D')
          .fontSize($r('sys.float.ohos_id_text_size_button1'))
          .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
          .fontWeight(FontWeight.Medium)
          .focusable(true)
          .focusOnTouch(true)
          .constraintSize({ minHeight: 40, maxWidth: 400 })
          .width('50%')
          .onClick(() => {
            hilog.info(this.domainId, this.logTag, 'AgreementDialog confirm.');
            this.confirm();
          })
      }
      .margin({
        top: 8,
        left: $r('sys.float.ohos_id_elements_margin_horizontal_l'),
        right: $r('sys.float.ohos_id_elements_margin_horizontal_l'),
        bottom: 16
      })
    }.backgroundColor($r('sys.color.ohos_id_color_dialog_default_bg'))
    .padding({
      left: 16,
      right: 16
    })
  }
}

export enum ErrorCode {
  // The HUAWEI ID is not signed in.
  ERROR_CODE_LOGIN_OUT = 1001502001,
  // This HUAWEI ID does not support one-tap sign-in as it is a child account or not registered in the Chinese mainland.
  ERROR_CODE_NOT_SUPPORTED = 1001500003,
  // Network error.
  ERROR_CODE_NETWORK_ERROR = 1001502005,
  // The user does not accept the agreements.
  ERROR_CODE_AGREEMENT_STATUS_NOT_ACCEPTED = 1005300001,
  // Parameter error.
  ERROR_CODE_PARAMETER_ERROR = 401
}

import { webview } from '@kit.ArkWeb';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { router } from '@kit.ArkUI';

// Screen for showing the HUAWEI ID User Authentication Agreement.
@Entry
@Component
struct WebPage {
  @State webUrl?: string = '';
  @State progress: number = 0;
  logTag: string = 'WebPage';
  domainId: number = 0x0000;
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Column() {
      Column() {
        Button({ type: ButtonType.Normal }) {
          Image($r('sys.media.ohos_ic_compnent_titlebar_back'))
            .backgroundColor(Color.Transparent)
            .borderRadius(20)
            .width(24)
            .height(24)
            .draggable(false)
            .autoResize(false)
            .focusable(true)
            .fillColor($r('sys.color.ohos_id_color_titlebar_icon'))
            .matchTextDirection(true)
        }
        .alignSelf(ItemAlign.Start)
        .backgroundColor($r('sys.color.ohos_id_color_button_normal'))
        .borderRadius(20)
        .width(40)
        .height(40)
        .onClick(() => {
          router.back();
        })
      }
      .height(56)
      .width('100%')
      .justifyContent(FlexAlign.Center)

      Progress({ value: this.progress, type: ProgressType.Linear })
        .width('100%')
        .visibility(this.progress <= 99 ? Visibility.Visible : Visibility.None)

      Web({ src: this.webUrl ?? '', controller: this.controller })
        .backgroundColor(Color.Transparent)
        .onProgressChange((event) => {
          hilog.info(this.domainId, this.logTag,
            'onProgressChange: ', (event ? event.newProgress : -1));
          this.progress = event ? event.newProgress : 0;
        })
        .darkMode(WebDarkMode.Auto)
        .forceDarkAccess(true)
        .onLoadIntercept((event) => {
          hilog.info(this.domainId, this.logTag, 'onLoadIntercept');
          return false;
        })
        .onErrorReceive((event) => {
          if (event) {
            hilog.error(this.domainId, this.logTag, `onErrorReceive,errorInfo: ${event?.error?.getErrorInfo()}`);
          }
        })
    }
    .alignItems(HorizontalAlign.Start)
    .padding({ left: 12, right: 12 })
    .width('100%')
    .height('100%')
  }

  aboutToAppear(): void {
    hilog.info(0x0000, 'testTag', 'aboutToAppear');
    const params = router.getParams() as Record<string, string>;
    this.webUrl = params.url ?? '';
    hilog.info(0x0000, 'testTag', `webUrl: ${this.webUrl}`);
  }

  aboutToDisappear(): void {
    hilog.info(0x0000, 'testTag', 'aboutToDisappear');
    if (this.webUrl) {
      this.controller.stop();
    }
  }
}