@ohos.nfc.cardEmulation (Standard NFC Card Emulation)
The cardEmulation module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host Card Emulation (HCE).
HCE provides card emulation that does not depend on a secure element. It allows an application to emulate a card and communicate with an NFC card reader through the NFC service.
NOTE
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
HCE and AID Declaration
Before developing an application related to HCE, you must declare NFC-related attributes in the module.json5 file.
// Applicable to devices other than lite wearables
{
"module": {
// Other declared attributes
"abilities": [
{
// Other declared attributes
"skills": [
{
"actions": [
"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
]
}
],
"metadata": [
{
"name": "payment-aid",
"value": "your payment aid"
},
{
"name": "other-aid",
"value": "your other aid"
}
]
}
],
"requestPermissions": [
{
"name": "ohos.permission.NFC_CARD_EMULATION",
// Set reason to card_emulation_reason.
"reason": "$string:card_emulation_reason"
}
]
}
}
// Applicable to lite wearables
{
"module": {
// Other declared attributes
"abilities": [
{
// Other declared attributes
"metaData": {
"customizeData": [
{
"name": "paymentAid",
"value": "A0000000041012"
},
{
"name": "otherAid",
"value": "A0000000041010"
}
]
},
"skills": [
{
"entities": [
"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
],
"actions": [
"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
]
}
]
}
],
"reqPermissions": [
{
"name": "ohos.permission.NFC_CARD_EMULATION",
// Set reason to card_emulation_reason.
"reason": "$string:card_emulation_reason",
"usedScene":{
"ability":[
"FormAbility"
],
"when":"always"
}
},
{
"name": "ohos.permission.NFC_TAG",
// Set reason to card_emulation_reason.
"reason": "$string:card_emulation_reason",
"usedScene":{
"ability":[
"FormAbility"
],
"when":"always"
}
}
]
}
}
NOTE
- The actions field must contain ohos.nfc.cardemulation.action.HOST_APDU_SERVICE and cannot be changed.
- When declaring an AID (in compliance with ISO/IEC 7816-4), ensure that name is set to payment-aid or other-aid. Incorrect setting will cause a parsing failure.
- The name field of requestPermissions must be ohos.permission.NFC_CARD_EMULATION and cannot be changed.
- Lite wearables support only the FA Model, with attribute configurations and API invocation methods differing from those of other device types. Refer to the example code for detailed implementations.
Modules to Import
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
FeatureType(deprecated)
Enumerates the NFC card emulation types.
NOTE
This API is supported since API version 6 and deprecated since API version 9. Use hasHceCapability instead.
System capability: SystemCapability.Communication.NFC.CardEmulation
| Name | Value | Description |
|---|---|---|
| HCE | 0 | HCE. |
| UICC | 1 | Subscriber identity module (SIM) card emulation. |
| ESE | 2 | Embedded Secure Element (eSE) emulation. |
CardType9+
Enumerates the types of services used by the card emulation application.
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
| Name | Value | Description |
|---|---|---|
| PAYMENT | "payment" | Payment service. |
| OTHER | "other" | Other services. |
cardEmulation.isSupported(deprecated)
isSupported(feature: number): boolean
Checks whether a certain type of card emulation is supported.
NOTE
This API is supported since API version 6 and deprecated since API version 9. Use hasHceCapability instead.
System capability: SystemCapability.Communication.NFC.CardEmulation
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| feature | number | Yes | Card emulation type to check. For details, see FeatureType. |
Return value
| Type | Description |
|---|---|
| boolean | Returns true if the card emulation type is supported; returns false otherwise. |
Example
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
let isHceSupported: boolean = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
if (!isHceSupported) {
console.info('this device is not supported for HCE, ignore it.');
}
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
if (!isHceSupported) {
console.error('this device is not supported for HCE, ignore it.');
}
cardEmulation.hasHceCapability9+
hasHceCapability(): boolean
Checks whether the device supports HCE.
System capability: SystemCapability.Communication.NFC.CardEmulation
Required permissions: ohos.permission.NFC_CARD_EMULATION
Atomic service API: This API can be used in atomic services since API version 12.
Return value
| Type | Description |
|---|---|
| boolean | Returns true if HCE is supported; returns false otherwise. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 801 | Capability not supported. |
Example
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
let hasHceCap: boolean = cardEmulation.hasHceCapability();
if (!hasHceCap) {
console.error('this device hasHceCapability false, ignore it.');
}
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let hasHceCap = cardEmulation.hasHceCapability();
if (!hasHceCap) {
console.error('this device hasHceCapability false, ignore it.');
}
cardEmulation.isDefaultService9+
isDefaultService(elementName: ElementName, type: CardType): boolean
Checks whether an application is the default application of the specified service type.
System capability: SystemCapability.Communication.NFC.CardEmulation
Required permissions: ohos.permission.NFC_CARD_EMULATION
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| elementName | ElementName | Yes | Information about the page, on which the application declares the NFC card emulation capability. It must contain at least bundleName and abilityName and cannot be empty. |
| type | CardType | Yes | Card emulation service type. Currently, only the default payment application can be queried. |
Return value
| Type | Description |
|---|---|
| boolean | Returns true if the application is the default payment application; returns false otherwise. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | The parameter check failed. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameters types. 3. Parameter verification failed. |
| 801 | Capability not supported. |
Example
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
import { bundleManager, Want } from '@kit.AbilityKit';
// Initialize elementName, bundleName, and abilityName and set their values correctly based on the actual application information.
let elementName: bundleManager.ElementName = {
bundleName: "com.example.myapplication",
moduleName: "entry",
abilityName: "EntryAbility"
};
let isDefaultService: boolean = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT);
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let appName = "com.example.testquestionlite";
let isDefaultService = cardEmulation.isDefaultService(appName, cardEmulation.CardType.PAYMENT);
HceService8+
Provides APIs for implementing HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE.
startHCE(deprecated)
startHCE(aidList: string[]): boolean
Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
NOTE This API is supported since API version 8 and deprecated since API version 9. Use start instead.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| aidList | string[] | Yes | List of AIDs to register. |
Return value
| Type | Description |
|---|---|
| boolean | Returns true if HCE is started or has been started; returns false otherwise. |
ArkTS example
For details, see the example of on.
JS example
<!-- Applicable to lite wearables -->
<!-- xxx.hml -->
<div class="container">
<text class="title" style="font-size: {{fontSize}}; color: {{fontColor}};">
Test
</text>
<input type="button" value="startHCE" style="width: 240px; height: 50px; margin: 5px;" onclick="onClick"></input>
</div>
/* Applicable to lite wearables */
/* xxx.css */
.container {
display: flex;
flex-direction: column;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 100px;
text-align: center;
width: 200px;
height: 100px;
}
.button {
font-size: 30px;
text-align: center;
width: 200px;
height: 100px;
}
// Applicable to lite wearables
// xxx.js
import cardEmulation from '@ohos.nfc.cardEmulation';
export default {
data: {
fontSize: '30px',
fontColor: '#FF1AFF00',
},
onClick() {
var hceService = new cardEmulation.HceService();
hceService.startHCE([
"F0010203040506", "A0000000041010"
])
}
}
start9+
start(elementName: ElementName, aidList: string[]): void
Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| elementName | ElementName | Yes | Information about the page, on which the application declares the NFC card emulation capability. It must contain at least bundleName and abilityName and cannot be empty. |
| aidList | string[] | Yes | List of AIDs to register. This parameter can be left empty. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | The parameter check failed. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameters types. 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 3100301 | Card emulation running state is abnormal in service. |
stopHCE(deprecated)
stopHCE(): boolean
Stops HCE, including exiting the current application from the foreground, releasing the dynamically registered AID list, and canceling the subscription of hceCmd.
NOTE This API is supported since API version 8 and deprecated since API version 9. Use stop instead.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Return value
| Type | Description |
|---|---|
| boolean | true if HCE is stopped or disabled; false otherwise. |
ArkTS example
For details, see the example of on.
JS example
<!-- Applicable to lite wearables -->
<!-- xxx.hml -->
<div class="container">
<text class="title" style="font-size: {{fontSize}}; color: {{fontColor}};">
Test
</text>
<input type="button" value="stopHCE" style="width: 240px; height: 50px; margin: 5px;" onclick="onClick"></input>
</div>
/* Applicable to lite wearables */
/* xxx.css */
.container {
display: flex;
flex-direction: column;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 100px;
text-align: center;
width: 200px;
height: 100px;
}
.button {
font-size: 30px;
text-align: center;
width: 200px;
height: 100px;
}
// Applicable to lite wearables
// xxx.js
import cardEmulation from '@ohos.nfc.cardEmulation';
export default {
data: {
fontSize: '30px',
fontColor: '#FF1AFF00',
},
onClick() {
var hceService = new cardEmulation.HceService();
hceService.stopHCE();
}
}
stop9+
stop(elementName: ElementName): void
Stops HCE, including canceling the subscription of APDU data, exiting this application from the foreground, and releasing the dynamically registered AID list. The application needs to call this API in onDestroy of the HCE page.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| elementName | ElementName | Yes | Information about the page, on which the application declares the NFC card emulation capability. It must contain at least bundleName and abilityName and cannot be empty. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | The parameter check failed. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameters types. 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 3100301 | Card emulation running state is abnormal in service. |
on8+
on(type: 'hceCmd', callback: AsyncCallback<number[]>): void
Subscribes to events indicating receiving of APDUs from the peer card reader. The application needs to call this API in onCreate() of the HCE page. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. It has a fixed value of hceCmd. |
| callback | AsyncCallback<number[]> | Yes | Event callback used to return the data array that complies with the APDU. Each number is represented in hexadecimal notation, with values ranging from 0x00 to 0xFF. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | Invalid parameter. |
| 801 | Capability not supported. |
ArkTS example
// Applicable to devices other than lite wearables
import { hilog } from '@kit.PerformanceAnalysisKit';
import { cardEmulation } from '@kit.ConnectivityKit';
import { AsyncCallback } from '@kit.BasicServicesKit';
import { ElementName } from './bundleManager/ElementName'
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
let hceService: cardEmulation.HceService = new cardEmulation.HceService();
let element: ElementName;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, param: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onCreate');
element = {
bundleName: want.bundleName ?? '',
abilityName: want.abilityName ?? '',
moduleName: want.moduleName
}
const apduCallback: AsyncCallback<number[]> = (err, data) => {
// Implement data processing and handle exceptions.
console.info("got apdu data");
};
hceService.on('hceCmd', apduCallback);
}
onDestroy() {
hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onDestroy');
hceService.stop(element);
}
// Other functions in the lifecycle
}
JS example
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let appName = "com.example.testquestionlite";
export default {
data:{
fontSize: '30px',
fontColor: '#50609f',
hide: 'show',
headCon: appName,
paymentAid: ["A0000000041010", "A0000000041012"]
},
onCreate() {
console.info('onCreate');
},
onReady() {
cardEmulation.hasHceCapability();
cardEmulation.isDefaultService(appName, cardEmulation.CardType.PAYMENT);
cardEmulation.isDefaultService(appName, cardEmulation.CardType.OTHER);
let HceService = new cardEmulation.HceService();
HceService.start(appName, this.paymentAid);
HceService.on("hceCmd", (data) => {
console.info('data:' + data);
// Data to be sent by the application. The following data is for reference only.
let responseData = [0x1, 0x2];
HceService.transmit(responseData, () => {
console.info('sendResponse start');
});
console.info('sendResponse end');
});
},
onDestroy() {
}
// Other functions in the lifecycle
}
off18+
off(type: 'hceCmd', callback?: AsyncCallback<number[]>): void
Unsubscribes from events indicating receiving of APDUs from the peer card reader. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 18.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Event type. It has a fixed value of hceCmd. |
| callback | AsyncCallback<number[]> | No | Event callback. Each number is represented in hexadecimal notation, with values ranging from 0x00 to 0xFF. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 801 | Capability not supported. |
Example
// Applicable to devices other than lite wearables
import { hilog } from '@kit.PerformanceAnalysisKit';
import { cardEmulation } from '@kit.ConnectivityKit';
import { AsyncCallback } from '@kit.BasicServicesKit';
import { ElementName } from './bundleManager/ElementName'
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
let hceService: cardEmulation.HceService = new cardEmulation.HceService();
let element: ElementName;
const apduCallback: AsyncCallback<number[]> = (err, data) => {
// Implement data processing and handle exceptions.
console.info("AsyncCallback got apdu data");
};
export default class EntryAbility extends UIAbility {
onCreate(want: Want, param: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onCreate');
element = {
bundleName: want.bundleName ?? '',
abilityName: want.abilityName ?? '',
moduleName: want.moduleName
}
hceService.on('hceCmd', apduCallback);
}
onDestroy() {
hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onDestroy');
hceService.off('hceCmd', apduCallback);
hceService.stop(element);
}
// Other functions in the lifecycle
}
sendResponse(deprecated)
sendResponse(responseApdu: number[]): void
Sends a response to the peer card reader.
NOTE This API is supported since API version 8 and deprecated since API version 9. Use transmit instead.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from 0x00 to 0xFF. |
ArkTS example
For details, see the example of transmit.
JS example
<!-- Applicable to lite wearables -->
<!-- xxx.hml -->
<div class="container">
<text class="title" style="font-size: {{fontSize}}; color: {{fontColor}};">
Test
</text>
<input type="button" value="sendResponse" style="width: 240px; height: 50px; margin: 5px;" onclick="onClick"></input>
</div>
/* Applicable to lite wearables */
/* xxx.css */
.container {
display: flex;
flex-direction: column;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 100px;
text-align: center;
width: 200px;
height: 100px;
}
.button {
font-size: 30px;
text-align: center;
width: 200px;
height: 100px;
}
// Applicable to lite wearables
// xxx.js
import cardEmulation from '@ohos.nfc.cardEmulation';
export default {
data: {
fontSize: '30px',
fontColor: '#FF1AFF00',
},
onClick() {
var hceService = new cardEmulation.HceService();
hceService.on("hceCmd", (err, res) => {
if(err.data === 0) {
console.info('callback => Operation hceCmd succeeded. Data: ${JSON.stringify(res)}');
hceService.sendResponse([0x00,0xa4,0x04,0x00,
0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44,
0x46,0x30,0x31,0x00]);
} else {
console.info('callback => Operation hceCmd failed. Cause: ${JSON.stringify(err.data)}');
}
})
}
}
transmit9+
transmit(response: number[]): Promise<void>
Transmits an APDU to the peer card reader. This API uses a promise to return the result. The application calls this API only after receiving an APDU sent by the card reader via on.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| response | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from 0x00 to 0xFF. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | The parameter check failed. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameters types. 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 3100301 | Card emulation running state is abnormal in service. |
Example
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let hceService: cardEmulation.HceService = new cardEmulation.HceService();
// Data to be sent by the application. The following data is for reference only.
const responseData = [0x1, 0x2];
hceService.transmit(responseData).then(() => {
// Process the promise.
console.info("transmit Promise success.");
}).catch((err: BusinessError) => {
console.error("transmit Promise error:", err);
});
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let hceService = new cardEmulation.HceService();
// Data to be sent by the application. The following data is for reference only.
let responseData = [0x1, 0x2];
hceService.transmit(responseData).then(() => {
// Process the promise.
console.info("transmit Promise success.");
});
console.info("transmit Promise end.");
transmit9+
transmit(response: number[], callback: AsyncCallback<void>): void
Sends APDU data to the peer card reader. The application can call this API only after receiving an APDU sent by the card reader via on. This API uses an asynchronous callback to return the result.
Required permissions: ohos.permission.NFC_CARD_EMULATION
System capability: SystemCapability.Communication.NFC.CardEmulation
Atomic service API: This API can be used in atomic services since API version 12.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| response | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from 0x00 to 0xFF. |
| callback | AsyncCallback<void> | Yes | Callback used to return the operation result. If the operation is successful, err is undefined; otherwise, err is an error object. |
Error codes
For details about the error codes, see NFC Error Codes.
| ID | Error Message |
|---|---|
| 201 | Permission denied. |
| 401 | The parameter check failed. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameters types. 3. Parameter verification failed. |
| 801 | Capability not supported. |
| 3100301 | Card emulation running state is abnormal in service. |
Example
// Applicable to devices other than lite wearables
import { cardEmulation } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
let hceService: cardEmulation.HceService = new cardEmulation.HceService();
// Data to be sent by the application. The following data is for reference only.
try {
const responseData = [0x1, 0x2];
hceService.transmit(responseData, (err : BusinessError)=> {
if (err) {
console.error(`transmit AsyncCallback err Code: ${err.code}, message: ${err.message}`);
} else {
console.info("transmit AsyncCallback success.");
}
});
} catch (error) {
console.error(`transmit AsyncCallback catch Code: ${(error as BusinessError).code}, ` +
`message: ${(error as BusinessError).message}`);
}
// Applicable to lite wearables
import cardEmulation from '@ohos.nfc.cardEmulation';
let hceService = new cardEmulation.HceService();
// Data to be sent by the application. The following data is for reference only.
let responseData = [0x1, 0x2];
hceService.transmit(responseData, () => {
console.info("transmit Promise success.");
});
console.info("transmit Promise end.");