This module provides basic game service capabilities of Game Service Kit, including game sign-in, HUAWEI ID identity verification, and anti-addiction for minors. This allows you to focus on the service capabilities of your game.
Model restriction: APIs of this module can be used only in the stage model.
Since: 4.0.0(10)
Player information class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| gamePlayerId | string | No | No | Game player ID. gamePlayerId cannot be empty in the interconnection scene. The value can contain a maximum of 256 characters. |
| teamPlayerId | string | No | No | Team player ID. teamPlayerId cannot be empty in the association scene. The value can contain a maximum of 256 characters. |
| idCompatibleType | number | No | No | ID compatibility type. 0: gamePlayerId is incompatible with openId and playerId, or teamPlayerId is incompatible with unionId. 1: gamePlayerId is compatible with playerId. For games running HarmonyOS 4 or earlier, playerId is used as the player ID. For games running HarmonyOS 5.0 or later, playerId is used as gamePlayerId. 2: gamePlayerId is compatible with openId. For games running HarmonyOS 4 or earlier, openId is used as the player ID. For games running HarmonyOS 5.0 or later, openId is used as gamePlayerId. 4: teamPlayerId is compatible with unionId. For games running HarmonyOS 5.0 or later, unionId is used as teamPlayerId. |
| level | number | No | No | Player level. This parameter is reserved. Currently, the fixed value 0 is returned. |
| playableTime | number | No | No | Playable duration of a player, in minutes. This parameter is reserved. Currently, the fixed value -1 is returned. Note: If the value -1 is returned, the current player is an adult and the play duration is not limited. If a value greater than or equal to 0 is returned, the current player is a minor and the return value is the current playable duration of the minor. |
| loginIdType | number | No | No | Type of the account ID used by a player to sign in to a game. 1: gamePlayerId, indicating the game player ID. 2: teamPlayerId, indicating the team player ID. Since: 5.0.0(12) |
Player role information class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
The requirements for the values of gamePlayerId, teamPlayerId, and thirdOpenId are as follows:
In the interconnection scene, teamPlayerId and thirdOpenId must be empty, and gamePlayerId must be passed.
In the binding scene, gamePlayerId must be empty, and teamPlayerId and thirdOpenId must be passed.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| roleId | string | No | No | Player role ID. Do not set it to an empty string ("") or null. If the game does not have a role system, set this parameter to '0'. The value can contain a maximum of 128 characters. |
| roleName | string | No | No | Player role name. Do not set it to an empty string ("") or null. If the game does not have a role system, set this parameter to 'default'. The value can contain a maximum of 128 characters. |
| serverId | string | No | Yes | Player zone server ID. The value can contain a maximum of 128 characters. |
| serverName | string | No | Yes | Player zone server name. The value can contain a maximum of 128 characters. |
| gamePlayerId | string | No | Yes | Game player ID. The value can contain a maximum of 256 characters. |
| teamPlayerId | string | No | Yes | Team player ID. This parameter can be passed when the official game account is associated with teamPlayerId. The value can contain a maximum of 256 characters. |
| thirdOpenId | string | No | Yes | Official game account ID. The value can contain a maximum of 128 characters. Since: 5.0.0(12) |
Account compliance information class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
The isRealName, isAdult, and ageRange parameters are not required for HUAWEI ID compliance verification.
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| thirdOpenId | string | No | No | Official game account ID. If there is no official game account ID, set this parameter to an empty string (""). The value can contain a maximum of 128 characters. |
| isRealName | boolean | No | Yes | Indicates whether a player has passed identity verification. - true: yes - false: no |
| isAdult | boolean | No | Yes | Indicates whether a player who has completed identity verification is identified as an adult. - true: yes - false: no |
| ageRange | ThirdUserAgeRange | No | Yes | Age range of a player. |
Parameters for multi-provider sign-in.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| thirdAccountInfos | Array<ThirdAccountInfo> | No | No | Official game account information which is displayed in the multi-provider sign-in panel. The name of each account must be unique. Note: If only quick sign-in using a HUAWEI ID is required, set this parameter to an empty array. |
| showLoginDialog | boolean | No | No | Indicates whether to forcibly display the multi-provider sign-in panel for players to choose to sign in again. - true: When the unionLogin API is called, the multi-provider sign-in panel is forcibly displayed. For account switching or other operations, set this parameter to true. - false: When the unionLogin API is called, the player's last choice is used by default, and the multi-provider sign-in panel is not forcibly displayed. The default value is false. |
| loginPanelType | LoginPanelType | No | Yes | Multi-provider sign-in panel type. - ICON - BUTTON The default value is ICON. |
Official game account information.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| accountIcon | Resource | No | No | Official game account icon resource information. The total icon size cannot exceed 35 KB. Currently, only the resource object generated by $r("app.media.name") is supported, while the resource object generated by $rawfile('filename') is not supported. |
| accountName | string | No | No | Display name of the official game account in the multi-provider sign-in panel. You are advised to pass a specific name such as Sign in with xx account or Sign in with xx pass (for example, Sign in with Let's play account), rather than using ambiguous names like Sign in with official account. If the game has multiple language versions, you need to determine the current language and provide the corresponding account name. When LoginPanelType is set to BUTTON, accountName is used as the button text. It is recommended that the value contain a maximum of 19 characters. If the value exceeds 19 characters, the excess part will be displayed as an ellipsis. |
| accountIdentifier | string | No | Yes | Unique identifier of the current account. It is used to identify the account and determine the account selected by the player from the sign-in result. You are advised to pass an identifier related to the current account, for example, youyou_account. The default value is undefined. The value can contain a maximum of 32 characters. Since: 6.0.2(22) |
| isOnTop | boolean | No | Yes | This parameter is valid only when LoginPanelType is set to ICON. This parameter indicates whether the current account is pinned to the top in the multi-provider sign-in panel. - true: yes - false: no The default value is false. NOTE - Only the first account with isOnTop set to true will be pinned to the top, and it will be displayed as a button (with button text set to the value of accountName). Non-pinned accounts are displayed as icons. - In the BUTTON- or ICON-type sign-in panel, the HUAWEI ID that is pinned to the top by Huawei side has a higher priority. Since: 6.0.2(22) |
Association information class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| thirdOpenId | string | No | No | Official game account ID. |
| bindType | BindType | No | No | Type of the association with the official game account. |
Account association enumeration class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Value | Description |
|---|---|---|
| CP_ACCOUNT_LEVEL | 0 | Developer level. |
| APP_LEVEL | 1 | Game level. |
Multi-provider sign-in result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| accountName | string | No | No | Account name. - If the player signs in to the game with a HUAWEI ID, hw_account is returned. - If the player signs in to the game with an official game account provided by you, the passed ThirdAccountInfo.accountName is returned. - If an exception occurs during the sign-in, official_account is returned. official_account indicates that no specific account name can be returned. It is recommended that the player select one of the game accounts provided by you for sign-in. It is recommended that the value contain a maximum of 19 characters. If the value exceeds 19 characters, the excess part will be displayed as an ellipsis. |
| needBinding | boolean | No | No | Indicates whether a player ID needs to be associated with an official game account. - true: association scene, where a player ID needs to be associated with an official game account. - false: interconnection scene, where a player ID does not need to be associated with an official game account. The game server needs to adapt to the sign-in scene selected by the player: - In the interconnection scene, the policy for the server must be consistent with that for HarmonyOS channel packages. - In the association scene or when an official game account is used for sign-in, the policy for the server must be consistent with that for official game packages. |
| boundPlayerInfo | BoundPlayerInfo | No | No | Official game account information associated with PlayerId. |
| localPlayer | GSKLocalPlayer | No | No | Player information. |
| accountIdentifier | string | No | Yes | Unique identifier of the current account, which is used to determine the account selected by the player. - If the player signs in to the game with a HUAWEI ID, hw_account is returned. - If the player signs in to the game with an official game account provided by you, the passed ThirdAccountInfo.accountIdentifier is returned. - If an exception occurs during the sign-in, official_account is returned. official_account indicates that no specific account name can be returned. It is recommended that the player select one of the game accounts provided by you for sign-in. The value can contain a maximum of 32 characters. Since: 6.0.2(22) |
Player change result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| event | PlayerChangedEvent | No | No | Player change event. |
| resultInfo | string | No | No | Information about the current event, which is a JSON string. The value can contain a maximum of 1,024 characters. |
Player change event enumeration class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Value | Description |
|---|---|---|
| SWITCH_GAME_ACCOUNT | 0 | The player switches the game account. |
Age information enumeration class of the official game account.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Value | Description |
|---|---|---|
| AGE_RANGE_8 | 1 | The player is under the age of 8, with identity verification passed. |
| AGE_RANGE_16 | 2 | The player's age is greater than or equal to 8 and less than 16, with identity verification passed. |
| AGE_RANGE_18 | 3 | The player's age is greater than or equal to 16 and less than 18, with identity verification passed. |
| AGE_RANGE_ADULT | 4 | The player's age is greater than or equal to 18, with identity verification passed. |
Sign-in panel enumeration class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
| Name | Value | Description |
|---|---|---|
| ICON | 0 | - The multi-provider sign-in panel supports the following sign-in options: HUAWEI ID and up to three official game accounts. - You can set the isOnTop parameter for an official game account to pin it to the top. |
| BUTTON | 1 | - The sign-in panel provides two sign-in options: HUAWEI ID and official game account, both displayed as buttons. - You do not need to set the isOnTop parameter. The official game account is on the top by default. |
Error code enumeration class.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.1.0(11)
For details about the error codes, please refer to ArkTS API Error Codes.
| Name | Value | Description |
|---|---|---|
| INTERNAL_ERROR | 1002000001 | Internal system error. |
| NETWORK_ERROR | 1002000002 | Network connection error. |
| GET_HWID_INFO_FAILED | 1002000003 | No HUAWEI ID information is found. |
| REALNAME_CANCELED_OR_NOT_REALNAME | 1002000004 | Identity verification is required but the player cancels it or identity verification has not been performed. |
| COUNTRY_OR_REGION_NOT_SUPPORTED | 1002000005 | Only HUAWEI IDs with both the service area and registration location within the Chinese mainland are supported. |
| ANTI_ADDICTION_ERROR | 1002000006 | The player is a minor and the current time is not within the permitted game duration. Since: 5.0.0(12) |
| PRODUCT_BELONG_REGION_ERROR | 1002000007 | The product's associated app is not available in the specified country/region. |
| HWID_IN_BLOCKLIST | 1002000008 | The HUAWEI ID is in the blocklist. |
| GAME_ACCOUNT_UNAVAILABLE | 1002000009 | Third-party game accounts are not supported currently. Since: 5.0.0(12) |
| PLAYER_ID_INVALID | 1002000010 | teamPlayerId does not match the current player. Since: 5.0.0(12) |
| AGREEMENT_NOT_AGREED | 1002000011 | The player does not agree to the privacy agreement. Since: 5.0.0(12) |
| OPEN_ID_OR_PLAYER_ID_BOUND | 1002000012 | The official game account has been associated with teamPlayerId. Since: 5.0.0(12) |
| OPEN_ID_AND_PLAYER_ID_NOT_BOUND | 1002000013 | The official game account is not associated with teamPlayerId. Since: 5.0.0(12) |
| CURRENT_API_NOT_AVAILABLE_FOR_GAME | 1002000014 | This API is not available for this game. Since: 5.0.0(12) |
| CURRENT_PLAYER_INFO_INVALID | 1002000015 | The player information is invalid. Since: 5.0.0(12) |
| UNION_LOGIN_CANCELED | 1002000016 | The player cancels multi-provider sign-in. Since: 5.0.0(12) |
| ILLEGAL_APPLICATION | 1002000017 | Invalid app. Since: 5.0.0(12) |
| NOT_MINI_GAME_ERROR | 1002000018 | This API is available only for mini games. Since: 6.0.1(21) |
| PARAM_ERROR | 1002000019 | Invalid parameter. Since: 6.0.1(21) |
| USER_CANCELED | 1002000020 | The current operation is canceled by the user. Since: 6.0.1(21) |
| CALLS_FREQUENT | 1002000021 | Excessive API call frequency. Since: 6.0.1(21) |
| PAY_PRODUCT_INVALID | 1002000050 | Invalid product information. Since: 6.0.1(21) |
| PAY_PRODUCT_OWNED | 1002000051 | The purchase failed because the user already owns the product. Since: 6.0.1(21) |
| PAY_PRODUCT_NOT_OWNED | 1002000052 | Failed to deliver the product because the user has not paid for it. Since: 6.0.1(21) |
| PAY_PRODUCT_CONSUMED | 1002000053 | The product has been delivered. No more delivery is needed. Since: 6.0.1(21) |
| PAY_ACCOUNT_REGION_UNSUPPORTED | 1002000054 | The country or region to which the signed-in HUAWEI ID belongs is not supported by IAP Kit. Since: 6.0.1(21) |
| PAY_DEAL_REJECTED | 1002000056 | The user transaction is rejected. Since: 6.0.1(21) |
init(context: common.UIAbilityContext): Promise<void>
Initializes Game Service Kit when the game is launched. This API must be called before other APIs are called. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. Note: UIAbilityContext must strictly inherit from UIAbility. The optimal time to obtain the context is after the game UI has been successfully loaded in the onWindowStageCreate lifecycle. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example:
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { gamePlayer } from '@kit.GameServiceKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/index', () => {
try {
gamePlayer.init(this.context).then(() => {
hilog.info(0x0000, 'testTag', `Succeeded in initializing.`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to init. Code: ${err.code}, message: ${err.message}`);
}
});
}
} init(context: common.UIAbilityContext, callback: AsyncCallback<void>): void
Initializes Game Service Kit when the game is launched. This API must be called before other APIs are called. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. Note: UIAbilityContext must strictly inherit from UIAbility. The optimal time to obtain the context is after the game UI has been successfully loaded in the onWindowStageCreate lifecycle. |
| callback | AsyncCallback<void> | Yes | Callback function. If the initialization is successful, err is undefined. Otherwise, err is an error object. |
Example:
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { gamePlayer } from '@kit.GameServiceKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/index', () => {
try {
gamePlayer.init(this.context, () => {
hilog.info(0x0000, 'testTag', `Succeeded in initializing.`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to init. Code: ${err.code}, message: ${err.message}`);
}
});
}
} unionLogin(context: common.UIAbilityContext, loginParam: UnionLoginParam): Promise<UnionLoginResult>
Enables multi-provider sign-in with a HUAWEI ID or an official game account. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| loginParam | UnionLoginParam | Yes | Parameters for multi-provider sign-in. |
Return value
| Type | Description |
|---|---|
| Promise<UnionLoginResult> | Promise used to return the multi-provider sign-in result object. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000004 | User cancels real name authentication or not real name. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000008 | The HUAWEI ID is in the blocklist. |
| 1002000011 | Agreement not agreed. |
| 1002000014 | This interface is not available for this game. |
| 1002000016 | Union login canceled by user. |
| 1002000017 | Illegal application identity. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct UnionLogin {
build() {
Row() {
Button('unionLogin')
.onClick(() => {
this.callUnionLogin();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callUnionLogin() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let thirdAccountInfo1: gamePlayer.ThirdAccountInfo = {
'accountName': 'testName1', // Display name of the game's official account sign-in option on the multi-provider sign-in panel. It is recommended that you provide a specific name such as "Sign in with xx account" or "Sign in with xx pass" (for example, "Sign in with Let's play account"), rather than using ambiguous names like "Sign in with official account". If the game supports multiple languages, determine the current language and pass the corresponding localized account name.
'accountIcon': $r('app.media.icon'), // Icon resource information of the official game account. The total icon size cannot exceed 35 KB.
'accountIdentifier': 'testIdentifier1', // Unique identifier of the current account. It is used to identify the account and determine the account selected by the player during sign-in result processing.
'isOnTop': true // Whether the current account is pinned to the top. Only the first account with isOnTop set to true will be pinned to the top.
};
let request: gamePlayer.UnionLoginParam = {
showLoginDialog: true, // Whether to display the multi-provider sign-in panel. The value true indicates that the panel is forcibly displayed. The value false indicates that the sign-in method selected by the player last time is preferentially used and the multi-provider sign-in panel is not forcibly displayed. If the player is signing in for the first time or has reinstalled the game, the sign-in panel will be displayed.
thirdAccountInfos: [
thirdAccountInfo1 // If the game does not have an official package or official account system, pass an empty array.
]
};
try {
gamePlayer.unionLogin(context, request).then((result: gamePlayer.UnionLoginResult) => {
hilog.info(0x0000, 'testTag', `Succeeded in logging in: ${result?.accountName}`);
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to login. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to login. Code: ${err.code}, message: ${err.message}`);
}
}
} getLocalPlayer(context: common.UIAbilityContext): Promise<GSKLocalPlayer>
Obtains the player information. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
Return value
| Type | Description |
|---|---|
| Promise<GSKLocalPlayer> | Promise used to return the player information. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000004 | User cancels real name authentication or not real name. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000006 | User is underage and has no playable time. Applicable versions: 5.0.0(12)+ |
| 1002000011 | Agreement not agreed. Applicable versions: 5.0.0(12)+ |
| 1002000014 | This interface is not available for this game. Applicable versions: 5.0.0(12)+ |
| 1002000017 | Illegal application identity. Applicable versions: 5.0.0(12)+ |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct GetLocalPlayer {
build() {
Row() {
Button('getLocalPlayer')
.onClick(() => {
this.callGetLocalPlayer();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callGetLocalPlayer() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
try {
gamePlayer.getLocalPlayer(context).then((result) => {
hilog.info(0x0000, 'testTag', `Succeeded in getting: ${result?.gamePlayerId}`);
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to get. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to get. Code: ${err.code}, message: ${err.message}`);
}
}
} getLocalPlayer(context: common.UIAbilityContext, callback: AsyncCallback<GSKLocalPlayer>): void
Obtains the player information. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| callback | AsyncCallback<GSKLocalPlayer> | Yes | Callback function. If the player information is successfully obtained, err is undefined and data is the obtained GSKLocalPlayer object. Otherwise, data is an error object. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000004 | User cancels real name authentication or not real name. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000006 | User is underage and has no playable time. Applicable versions: 5.0.0(12)+ |
| 1002000011 | Agreement not agreed. Applicable versions: 5.0.0(12)+ |
| 1002000014 | This interface is not available for this game. Applicable versions: 5.0.0(12)+ |
| 1002000017 | Illegal application identity. Applicable versions: 5.0.0(12)+ |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct GetLocalPlayer {
build() {
Row() {
Button('getLocalPlayer')
.onClick(() => {
this.callGetLocalPlayer();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callGetLocalPlayer() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
try {
gamePlayer.getLocalPlayer(context, (error, result) => {
if (error) {
hilog.error(0x0000, 'testTag', `Failed to get. Code: ${error.code}, message: ${error.message}`);
return;
}
hilog.info(0x0000, 'testTag', `Succeeded in getting: ${result?.gamePlayerId}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to get. Code: ${err.code}, message: ${err.message}`);
}
}
} bindPlayer(context: common.UIAbilityContext, thirdOpenId: string, teamPlayerId: string): Promise<void>
Associates the teamPlayerId corresponding to the player's HUAWEI ID to the player's official game account. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| thirdOpenId | string | Yes | Official game account ID. The value can contain a maximum of 128 characters. |
| teamPlayerId | string | Yes | teamPlayerId corresponding to the player's HUAWEI ID. The value can contain a maximum of 128 characters. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000010 | The playerId is not current player. |
| 1002000011 | Agreement not agreed. |
| 1002000012 | The thirdOpenId or teamPlayerId has been bound. |
| 1002000017 | Illegal application identity. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct BindPlayer {
build() {
Row() {
Button('bindPlayer')
.onClick(() => {
this.callBindPlayer();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callBindPlayer() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let thirdOpenId = '123xxxx';
let teamPlayerId = '456xxx';
try {
gamePlayer.bindPlayer(context, thirdOpenId, teamPlayerId).then(() => {
hilog.info(0x0000, 'testTag', `Succeeded in binding.`);
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to bind. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to bind. Code: ${err.code}, message: ${err.message}`);
}
}
} unbindPlayer(context: common.UIAbilityContext, thirdOpenId: string, teamPlayerId: string): Promise<void>
Disassociates the teamPlayerId corresponding to the player's HUAWEI ID from the player's official game account. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| thirdOpenId | string | Yes | Official game account ID. |
| teamPlayerId | string | Yes | teamPlayerId corresponding to the player's HUAWEI ID. The value can contain a maximum of 256 characters. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000010 | The playerId is not current player. |
| 1002000011 | Agreement not agreed. |
| 1002000013 | The thirdOpenId and teamPlayerId are not bound. |
| 1002000017 | Illegal application identity. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct UnbindPlayer {
build() {
Row() {
Button('unbindPlayer')
.onClick(() => {
this.callUnbindPlayer();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callUnbindPlayer() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let thirdOpenId = '123xxxx';
let teamPlayerId = '456xxx';
try {
gamePlayer.unbindPlayer(context, thirdOpenId, teamPlayerId).then(() => {
hilog.info(0x0000, 'testTag', `Succeeded in unbinding.`);
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to unbind. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to unbind. Code: ${err.code}, message: ${err.message}`);
}
}
} verifyLocalPlayer(context: common.UIAbilityContext, thirdUserInfo: ThirdUserInfo): Promise<void>
Verifies compliance for the HUAWEI ID used to sign in to the device, including identity verification and anti-addiction information. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| thirdUserInfo | ThirdUserInfo | Yes | Player compliance information maintained by the game itself. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to Universal Error Codes and ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000004 | User cancels real name authentication or not real name. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000006 | User is underage and has no playable time. |
| 1002000008 | The HUAWEI ID is in the blocklist. |
| 1002000011 | Agreement not agreed. |
| 1002000015 | The current player information is invalid. Execute the login process again to obtain the player information. |
| 1002000017 | Illegal application identity. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct VerifyLocalPlayer {
build() {
Row() {
Button('verifyLocalPlayer')
.onClick(() => {
this.callVerifyLocalPlayer();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callVerifyLocalPlayer() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
// thirdUserInfo indicates the player compliance information. It is required if the player signs in to the game using an official game account. You do not need to pass this information if the player signs in with their HUAWEI ID.
let request: gamePlayer.ThirdUserInfo = {
thirdOpenId: '123xxxx', // Official game account ID. Leave this parameter empty when HUAWEI ID sign-in is used.
isRealName: true // Indicates whether the player has completed identity verification. The value true indicates yes and the value false indicates no. This parameter is not required when HUAWEI ID sign-in is used.
};
try {
gamePlayer.verifyLocalPlayer(context, request).then(() => {
hilog.info(0x0000, 'testTag', `Succeeded in verifying.`);
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to verify. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to verify. Code: ${err.code}, message: ${err.message}`);
}
}
} savePlayerRole(context: common.UIAbilityContext, request: GSKPlayerRole): Promise<void>
Saves the role information to the Huawei game server. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| request | GSKPlayerRole | Yes | Request for reporting role information after a player selects a role and a zone server. If the game does not have a role system, set roleId to '0' and roleName to 'default'. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct SavePlayerRole {
build() {
Row() {
Button('savePlayerRole')
.onClick(() => {
this.callSavePlayerRole();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callSavePlayerRole() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let request: gamePlayer.GSKPlayerRole = {
roleId: '123', // Player role ID. If the game does not have a role system, set this parameter to '0'. The value cannot be "" or null.
roleName: 'Jason', // Player role name. If the game does not have a role system, set this parameter to 'default'. The value cannot be "" or null.
serverId: '456',
serverName: 'Zhangshan',
gamePlayerId: '789' // Pass the actually obtained value of gamePlayerId.
};
try {
gamePlayer.savePlayerRole(context, request).then(() => {
hilog.info(0x0000, 'testTag', `Succeeded in saving.`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to save. Code: ${err.code}, message: ${err.message}`);
}
}
} savePlayerRole(context: common.UIAbilityContext, request: GSKPlayerRole, callback: AsyncCallback<void>): void
Saves the role information to the Huawei game server. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.UIAbilityContext | Yes | Context. |
| request | GSKPlayerRole | Yes | Request for reporting role information after a player selects a role and a zone server. If the game does not have a role system, set roleId to '0' and roleName to 'default'. |
| callback | AsyncCallback<void> | Yes | Callback function. If the role information is successfully saved, err is undefined. Otherwise, err is an error object. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct SavePlayerRole {
build() {
Row() {
Button('savePlayerRole')
.onClick(() => {
this.callSavePlayerRole();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callSavePlayerRole() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let request: gamePlayer.GSKPlayerRole = {
roleId: '123', // Player role ID. If the game does not have a role system, set this parameter to '0'. The value cannot be "" or null.
roleName: 'Jason', // Player role name. If the game does not have a role system, set this parameter to 'default'. The value cannot be "" or null.
serverId: '456',
serverName: 'Zhangshan',
gamePlayerId: '789' // Pass the actually obtained value of gamePlayerId.
};
try {
gamePlayer.savePlayerRole(context, request, () => {
hilog.info(0x0000, 'testTag', `Succeeded in saving.`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to save. Code: ${err.code}, message: ${err.message}`);
}
}
} on(type: 'playerChanged', callback: Callback<PlayerChangedResult>): void
Listens for player change events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the event to listen for. The value is fixed at playerChanged. |
| callback | Callback<PlayerChangedResult> | Yes | Callback used to return the player change result. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
let playerChangedEventCallback = (result: gamePlayer.PlayerChangedResult): void => {
if (result.event === gamePlayer.PlayerChangedEvent.SWITCH_GAME_ACCOUNT) {
// ...
// The game account has been switched. After the local cache is cleared, call the unionLogin API again.
}
};
// Call the on API to register the playerChanged event listener.
try {
gamePlayer.on('playerChanged', playerChangedEventCallback);
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to register. Code: ${err.code}, message: ${err.message}`);
} off(type: 'playerChanged', callback?: Callback<PlayerChangedResult>): void
Cancels listening for player change events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 5.0.0(12)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the event for which listening is canceled. The value is fixed at playerChanged. |
| callback | Callback<PlayerChangedResult> | No | Callback used to return the player change result. If this parameter is specified, the corresponding callback subscription will be canceled. If this parameter is empty, all callback subscriptions for the playerChanged event will be canceled. |
Error codes:
For details about the error codes, please refer to Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
Example 1:
import { gamePlayer } from '@kit.GameServiceKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
try {
gamePlayer.off('playerChanged');
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to unregister. Code: ${err.code}, message: ${err.message}`);
} Example 2:
import { gamePlayer } from '@kit.GameServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
let playerChangedEventCallback = (result: gamePlayer.PlayerChangedResult): void => {
if (result.event === gamePlayer.PlayerChangedEvent.SWITCH_GAME_ACCOUNT) {
// ...
// The game account has been switched. After the local cache is cleared, call the unionLogin API again.
}
};
try {
// The playerChangedEventCallback parameter is the second parameter of gamePlayer.on('playerChanged', playerChangedEventCallback).
gamePlayer.off('playerChanged', playerChangedEventCallback);
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to unregister. Code: ${err.code}, message: ${err.message}`);
} Mini game sign-in information.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| gameAppId | string | No | No | App ID of a mini game. The app ID of a mini game is automatically generated when you create a mini game in AppGallery Connect. For details, please refer to Creating an App ID for a Mini Game. The value contains a maximum of 64 characters. |
| extraData | string | No | Yes | Additional information, which must be a JSON string. Extra fields can be included as key-value pairs within this JSON string. For example: let extraData = "{"key1":"value1","key2":"value2"}"; |
Mini game player information.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| playerId | string | No | No | Player account ID. The value can contain a maximum of 256 characters. |
| isAdult | boolean | No | No | Indicates whether a player who has completed identity verification is identified as an adult. - true: yes - false: no |
| playerLevel | number | No | No | Account level of the current player. The value range is [1, 15]. |
| playerSign | string | No | No | Player sign-in signature. |
| signTs | string | No | No | Timestamp of the player sign-in signature. |
| extraData | string | No | Yes | Additional information, which must be a JSON string. Extra fields can be included as key-value pairs within this JSON string. For example: let extraData = "{"key1":"value1","key2":"value2"}"; |
on(type: 'miniGameAddictionPrevented', callback: Callback<string>): void
Registers a listener for mini game anti-addiction events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the event to listen for. The value is fixed at miniGameAddictionPrevented. |
| callback | Callback<string> | Yes | Callback used to return the registration result of the mini-game anti-addiction event. |
Error codes:
For details about the error codes, please refer to ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 1002000018 | This API is only provided for HarmonyOS mini games. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
let miniGameAddictionPreventedCallback = (result: string): void => {
// Exit the mini game.
hilog.info(0x0000, 'testTag', `Callback miniGameAddictionPrevented result: ${result}`);
};
// Call the on API to register a listener for mini game anti-addiction events.
try {
gamePlayer.on('miniGameAddictionPrevented', miniGameAddictionPreventedCallback);
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to register. Code: ${err.code}, message: ${err.message}`);
} off(type: 'miniGameAddictionPrevented', callback?: Callback<string>): void
Unregisters the listener for mini game anti-addiction events. This API uses an asynchronous callback to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Type of the event to listen for. The value is fixed at miniGameAddictionPrevented. |
| callback | Callback<string> | No | Callback used to return the result of unregistering the listener for mini game anti-addiction events. If this parameter is specified, the corresponding callback subscription will be canceled. If this parameter is empty, all callback subscriptions for the miniGameAddictionPrevented event will be canceled. |
Error codes:
For details about the error codes, please refer to ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 1002000018 | This API is only provided for HarmonyOS mini games. |
Example 1:
import { gamePlayer } from '@kit.GameServiceKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
try {
gamePlayer.off('miniGameAddictionPrevented');
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to unregister. Code: ${err.code}, message: ${err.message}`);
} Example 2:
import { gamePlayer } from '@kit.GameServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
let miniGameAddictionPreventedCallback = (result: string): void => {
// Exit the mini game.
hilog.info(0x0000, 'testTag', `Callback miniGameAddictionPrevented result: ${result}`);
};
try {
// The miniGameAddictionPreventedCallback parameter is the second input parameter of gamePlayer.on('miniGameAddictionPrevented', miniGameAddictionPreventedCallback).
gamePlayer.off('miniGameAddictionPrevented', miniGameAddictionPreventedCallback);
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to unregister. Code: ${err.code}, message: ${err.message}`);
} miniGameLogin(context: common.Context, loginParam: MiniGameLoginParam): Promise<MiniGamePlayer>
Signs in to a mini game. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.Context | Yes | Context. |
| loginParam | MiniGameLoginParam | Yes | Mini game sign-in information. |
Return value
| Type | Description |
|---|---|
| Promise<MiniGamePlayer> | Promise used to return the player information. |
Error codes:
For details about the error codes, please refer to ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000004 | User cancels real name authentication or not real name. |
| 1002000005 | The country or region of the signed-in Huawei ID does not support. |
| 1002000006 | User is underage and has no playable time. |
| 1002000008 | The HUAWEI ID is in the blocklist. |
| 1002000011 | Agreement not agreed. |
| 1002000018 | This API is only provided for HarmonyOS mini games. |
| 1002000019 | Parameter error. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct MiniGameLogin {
build() {
Row() {
Button('miniGameLogin')
.onClick(() => {
this.callMiniGameLogin();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callMiniGameLogin() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let request: gamePlayer.MiniGameLoginParam = {
'gameAppId': '123xxx', // Mini game's app ID.
'extraData': 'xxx' // Additional information, which must be in JSON string format.
};
try {
gamePlayer.miniGameLogin(context, request).then((result: gamePlayer.MiniGamePlayer) => {
if (result?.playerId) {
hilog.info(0x0000, 'testTag', `Succeeded in logging in. PlayerLevel: ${result.playerLevel}`);
} else {
hilog.error(0x0000, 'testTag', `Failed to login.`);
}
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to login. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to login. Code: ${err.code}, message: ${err.message}`);
}
}
} miniGamePay(context: common.Context, parameter: PurchaseParameter): Promise<CreatePurchaseResult>
Provides the mini game payment function. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 6.0.1(21)
Parameters
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | common.Context | Yes | Context. |
| parameter | PurchaseParameter | Yes | Parameters for purchasing a product. |
Return value
| Type | Description |
|---|---|
| Promise<CreatePurchaseResult> | Promise used to return the product purchase result. |
Error codes:
For details about the error codes, please refer to ArkTS API Error Codes.
| ID | Error Message |
|---|---|
| 1002000001 | System internal error. |
| 1002000002 | Network connection error. |
| 1002000003 | The HUAWEI ID is not signed in or not authorized. |
| 1002000007 | The application to which the product belongs is not listed in the specified country. |
| 1002000018 | This API is only provided for HarmonyOS mini games. |
| 1002000019 | Parameter error. |
| 1002000020 | The operation was canceled by the user. |
| 1002000021 | Too frequent API calls. |
| 1002000050 | Invalid product information. |
| 1002000051 | Failed to purchase a product because the user already owns the product. |
| 1002000052 | The purchase cannot be finished because the user has not paid for it. |
| 1002000053 | The purchase has been finished and cannot be finished again. |
| 1002000054 | The country or region of the signed-in HUAWEI ID does not support IAP. |
| 1002000056 | The user is not allowed to make purchase. |
Example:
import { gamePlayer } from '@kit.GameServiceKit';
import { common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct MiniGamePay {
build() {
Row() {
Button('miniGamePay')
.onClick(() => {
this.callMiniGamePay();
})
.width('100%')
}
.margin(16)
.height('100%')
.justifyContent(FlexAlign.Center)
}
private callMiniGamePay() {
let context = this.getUIContext()?.getHostContext() as common.UIAbilityContext;
let request: gamePlayer.PurchaseParameter = {
productId: 'testProduct01', // ID of the product to be paid for.
productType: 0, // Product type to be queried.
developerPayload: 'test developer payload string.', // Information that you can retain, which contains 0 to 256 characters. If this parameter contains a value, it will be returned to the app unchanged in the payment-success callback result.
reservedInfo: '{"key1":"value1","key2":"value2"}' // Additional product information in JSON string format passed in key-value pairs.
};
try {
gamePlayer.miniGamePay(context, request).then((result: gamePlayer.CreatePurchaseResult) => {
if (JSON.parse(result?.purchaseData).resultCode == 0) {
hilog.info(0x0000, 'testTag', `Succeeded in paying. Purchase result: ${result.purchaseData}`);
} else {
hilog.error(0x0000, 'testTag', `Failed to pay. resultCode: ${JSON.parse(result?.purchaseData).resultCode}`);
}
}).catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag', `Failed to pay. Code: ${error.code}, message: ${error.message}`);
});
} catch (error) {
let err = error as BusinessError;
hilog.error(0x0000, 'testTag', `Failed to pay. Code: ${err.code}, message: ${err.message}`);
}
}
} Product purchase parameter, intended for IAP Kit and mini games only.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| productId | string | No | No | ID of the product to purchase. Each product ID must be unique in an app. The product IDs come from the product information you have configured in AppGallery Connect. For details, please refer to Configuring Products. |
| productType | ProductType | No | No | Type of the product to query. |
| developerPayload | string | No | Yes | Information that you can retain, which contains 0 to 256 characters. If this parameter contains a value, it will be returned to the app unchanged in the payment-success callback result. |
| reservedInfo | string | No | Yes | Additional product information in JSON string format passed in key-value pairs. For example: let reservedInfo = "{"key1":"value1","key2":"value2"}"; Note: This parameter is reserved for you to pass additional information. You can choose to set it or not. |
Product type, intended for IAP Kit and mini games only.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
| Name | Value | Description |
|---|---|---|
| CONSUMABLE | 0 | Consumable. |
| NONCONSUMABLE | 1 | Non-consumable. |
| AUTORENEWABLE | 2 | Auto-renewable subscription. Since: 5.0.0(12) |
Product purchase result, which can be used only by IAP Kit.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.0.0(10)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| inAppPurchaseData | string | No | No | JSON string of purchase data. |
| signature | string | No | No | Signature string generated after the paymentData string is signed using the IAP private key. |
| signatureAlgorithm | string | No | No | Signing algorithm. The value is fixed at SHA256WithRSA/PSS. |
Product purchase result, intended for IAP Kit and mini games only.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Game.GameService.GamePlayer
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| purchaseData | string | No | No | JSON string containing the purchase result. |