1# @ohos.nfc.cardEmulation (Standard NFC Card Emulation)
2
3The **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).
4HCE 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.
5
6> **NOTE**
7>
8> 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.
9
10## HCE and AID Declaration
11
12Before developing an application related to HCE, you must declare NFC-related attributes in the **module.json5** file.
13```json
14{
15  "module": {
16    // other declared attributes.
17    "abilities": [
18      {
19        // other declared attributes.
20        "skills": [
21          {
22            "actions": [
23              "ohos.nfc.cardemulation.action.HOST_APDU_SERVICE"
24            ]
25          }
26        ],
27        "metadata": [
28          {
29            "name": "payment-aid",
30            "value": "your payment aid"
31          },
32          {
33            "name": "other-aid",
34            "value": "your other aid"
35          }
36        ]
37      }
38    ],
39    "requestPermissions": [
40      {
41        "name": "ohos.permission.NFC_CARD_EMULATION",
42        // should add variable card_emulation_reason in string.json
43        "reason": "$string:card_emulation_reason",
44      }
45    ]
46  }
47}
48```
49> **NOTE**
50>- The **actions** field must contain **ohos.nfc.cardemulation.action.HOST_APDU_SERVICE** and cannot be changed.
51>- The **name** fields under **metadata** must be **payment-aid** or **other-aid** when application IDs (AIDs) are declared. Incorrect setting will cause a parsing failure.
52>- The **name** field of **requestPermissions** must be **ohos.permission.NFC_CARD_EMULATION** and cannot be changed.
53
54## Modules to Import
55
56```
57import { cardEmulation } from '@kit.ConnectivityKit';
58```
59
60## FeatureType<sup>(deprecated)</sup>
61
62Enumerates the NFC card emulation types.
63
64> **NOTE**
65> This API is supported since API version 6 and deprecated since API version 9. Use [hasHceCapability](#hashcecapability9) instead.
66
67**System capability**: SystemCapability.Communication.NFC.CardEmulation
68
69| Name  | Value   | Description      |
70| ---- | ---- | -------- |
71| HCE  | 0    | HCE.|
72| UICC | 1    | Subscriber identity module (SIM) card emulation.|
73| ESE  | 2    | embedded Secure Element (eSE) emulation. |
74
75## CardType<sup>9+</sup>
76
77Enumerates the types of services used by the card emulation application.
78
79**System capability**: SystemCapability.Communication.NFC.CardEmulation
80
81**Atomic service API**: This API can be used in atomic services since API version 12.
82
83| Name     | Value        | Description               |
84| ------- | --------- | ----------------- |
85| PAYMENT | "payment" | Payment service.|
86| OTHER   | "other"   | Other services.|
87
88## isSupported<sup>(deprecated)</sup>
89
90isSupported(feature: number): boolean
91
92Checks whether a certain type of card emulation is supported.
93
94> **NOTE**
95> This API is supported since API version 6 and deprecated since API version 9. Use [hasHceCapability](#hashcecapability9) instead.
96
97**System capability**: SystemCapability.Communication.NFC.CardEmulation
98
99**Parameters**
100
101| Name    | Type    | Mandatory  | Description                                      |
102| ------- | ------ | ---- | ---------------------------------------- |
103| feature | number | Yes   | Card emulation type to check. For details, see [FeatureType](#featuretypedeprecated).|
104
105**Return value**
106
107| **Type** | **Description**                                |
108| ------- | -------------------------------------- |
109| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
110
111**Example**
112
113```js
114import { cardEmulation } from '@kit.ConnectivityKit';
115
116let isHceSupported: boolean = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
117if (!isHceSupported) {
118    console.log('this device is not supported for HCE, ignore it.');
119}
120```
121
122## hasHceCapability<sup>9+</sup>
123
124hasHceCapability(): boolean
125
126Checks whether the device supports HCE.
127
128**System capability**: SystemCapability.Communication.NFC.CardEmulation
129
130**Required permissions**: ohos.permission.NFC_CARD_EMULATION
131
132**Atomic service API**: This API can be used in atomic services since API version 12.
133
134**Return value**
135
136| **Type** | **Description**                          |
137| ------- | -------------------------------- |
138| boolean | Returns **true** if HCE is supported; returns **false** otherwise.|
139
140**Error codes**
141
142For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
143
144| ID| Error Message |
145| -------- | ---------------------------- |
146|201 | Permission denied.                 |
147|801 | Capability not supported.          |
148
149**Example**
150
151```js
152import { cardEmulation } from '@kit.ConnectivityKit';
153
154let hasHceCap: boolean = cardEmulation.hasHceCapability();
155if (!hasHceCap) {
156    console.log('this device hasHceCapability false, ignore it.');
157}
158```
159
160## isDefaultService<sup>9+</sup>
161
162isDefaultService(elementName: ElementName, type: CardType): boolean
163
164Checks whether an application is the default application of the specified service type.
165
166**System capability**: SystemCapability.Communication.NFC.CardEmulation
167
168**Required permissions**: ohos.permission.NFC_CARD_EMULATION
169
170**Atomic service API**: This API can be used in atomic services since API version 12.
171
172**Parameters**
173
174| Name        | Type                                      | Mandatory  | Description                     |
175| ----------- | ---------------------------------------- | ---- |-------------------------|
176| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname) | Yes   | Information about the page, on which the application declares the NFC card emulation capability. It cannot be empty and must contain at least **bundleName** and **abilityName**.|
177| type        | [CardType](#cardtype9)                   | Yes   | Card emulation service type. Currently, only the default payment application can be queried.  |
178
179**Error codes**
180
181For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
182
183| ID| Error Message |
184| -------- | ---------------------------- |
185|201 | Permission denied.                 |
186|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
187|801 | Capability not supported.          |
188
189**Return value**
190
191| **Type** | **Description**                              |
192| ------- | ------------------------------------ |
193| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
194
195
196**Example**
197```js
198import { cardEmulation } from '@kit.ConnectivityKit';
199import { bundleManager, Want } from '@kit.AbilityKit';
200
201// Initialize elementName here. bundleName and abilityName are required.
202let want: Want = {
203  bundleName: "com.example.myapplication",
204  moduleName: "entry",
205  abilityName: "EntryAbility"
206};
207let elementName: bundleManager.ElementName = {
208  bundleName: "com.example.myapplication",
209  moduleName: "entry",
210  abilityName: "EntryAbility"
211};
212
213let isDefaultService: boolean = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT);
214// Do something according to the isDefaultService value.
215```
216
217
218## HceService<sup>8+</sup>
219
220Provides 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.
221
222### startHCE<sup>(deprecated)</sup>
223
224startHCE(aidList: string[]): boolean
225
226Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
227
228> **NOTE**
229> This API is supported since API version 8 and deprecated since API version 9. Use [start](#start9) instead.
230
231**Required permissions**: ohos.permission.NFC_CARD_EMULATION
232
233**System capability**: SystemCapability.Communication.NFC.CardEmulation
234
235**Parameters**
236
237| Name | Type    | Mandatory| Description                   |
238| ------- | -------- | ---- | ----------------------- |
239| aidList | string[] | Yes  | AID list to register.|
240
241**Return value**
242
243| **Type** | **Description**                                |
244| ------- | -------------------------------------- |
245| boolean | Returns **true** if HCE is started or has been started; returns **false** otherwise.|
246
247### start<sup>9+</sup>
248
249start(elementName: [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname), aidList: string[]): void
250
251Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
252
253**Required permissions**: ohos.permission.NFC_CARD_EMULATION
254
255**System capability**: SystemCapability.Communication.NFC.CardEmulation
256
257**Atomic service API**: This API can be used in atomic services since API version 12.
258
259**Parameters**
260
261| Name | Type    | Mandatory| Description                   |
262| ------- | -------- | ---- | ----------------------- |
263| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#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.|
264| aidList | string[] | Yes  | List of AIDs to register. This parameter can be left empty.|
265
266**Error codes**
267
268For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
269
270| ID| Error Message |
271| ------- | -------|
272|201 | Permission denied.                 |
273|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
274|801 | Capability not supported.          |
275| 3100301 | Card emulation running state is abnormal in service. |
276
277### stopHCE<sup>(deprecated)</sup>
278
279stopHCE(): boolean
280
281Stops HCE, including exiting the current application from the foreground, releasing the dynamically registered AID list, and canceling the subscription of **hceCmd**.
282
283> **NOTE**
284> This API is supported since API version 8 and deprecated since API version 9. Use [stop](#stop9) instead.
285
286**Required permissions**: ohos.permission.NFC_CARD_EMULATION
287
288**System capability**: SystemCapability.Communication.NFC.CardEmulation
289
290**Return value**
291
292| **Type** | **Description**                                |
293| ------- | -------------------------------------- |
294| boolean | Returns **true** is HCE is stopped; returns **false** otherwise.|
295
296**Example**
297
298For details, see the example of [on](#on8).
299
300### stop<sup>9+</sup>
301
302stop(elementName: [ElementName](../apis-ability-kit/js-apis-bundleManager-elementName.md#elementname)): void
303
304Stops 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.
305
306**Required permissions**: ohos.permission.NFC_CARD_EMULATION
307
308**System capability**: SystemCapability.Communication.NFC.CardEmulation
309
310**Atomic service API**: This API can be used in atomic services since API version 12.
311
312**Parameters**
313
314| Name | Type    | Mandatory| Description                   |
315| ------- | -------- | ---- | ----------------------- |
316| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#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.|
317
318**Error codes**
319
320For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
321
322| ID| Error Message |
323| ------- | -------|
324|201 | Permission denied.                 |
325|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
326|801 | Capability not supported.          |
327| 3100301 | Card emulation running state is abnormal in service. |
328
329### on<sup>8+</sup>
330
331on(type: 'hceCmd', callback: AsyncCallback\<number[]>): void
332
333Registers a callback to receive APDUs from the peer card reader. The application needs to call this API in **onCreate()** of the HCE page.
334
335**Required permissions**: ohos.permission.NFC_CARD_EMULATION
336
337**System capability**: SystemCapability.Communication.NFC.CardEmulation
338
339**Atomic service API**: This API can be used in atomic services since API version 12.
340
341**Parameters**
342
343| Name  | Type                   | Mandatory| Description                                        |
344| -------- | ----------------------- | ---- | -------------------------------------------- |
345| type     | string                  | Yes  | Callback type to register. It has a fixed value of **hceCmd**.                        |
346| callback | AsyncCallback\<number[]> | Yes  | Callback used to return the APDU, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
347
348**Example**
349```js
350import { hilog } from '@kit.PerformanceAnalysisKit';
351import { cardEmulation } from '@kit.ConnectivityKit';
352import { AsyncCallback } from '@kit.BasicServicesKit';
353import { ElementName } from './bundleManager/ElementName'
354import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
355
356let hceService: cardEmulation.HceService = new cardEmulation.HceService();
357let element: ElementName;
358
359export default class EntryAbility extends UIAbility {
360  onCreate(want: Want, param: AbilityConstant.LaunchParam) {
361    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onCreate');
362    element = {
363      bundleName: want.bundleName ?? '',
364      abilityName: want.abilityName ?? '',
365      moduleName: want.moduleName
366    }
367    const apduCallback: AsyncCallback<number[]> = (err, data) => {
368      //handle the data and err
369      console.log("got apdu data");
370    };
371    hceService.on('hceCmd', apduCallback);
372  }
373  onDestroy() {
374    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onDestroy');
375    hceService.stop(element)
376  }
377  // other life cycle method...
378}
379```
380
381
382### sendResponse<sup>(deprecated)</sup>
383
384sendResponse(responseApdu: number[]): void
385
386Sends a response to the peer card reader.
387
388> **NOTE**
389> This API is supported since API version 8 and deprecated since API version 9. Use [transmit](#transmit9) instead.
390
391**Required permissions**: ohos.permission.NFC_CARD_EMULATION
392
393**System capability**: SystemCapability.Communication.NFC.CardEmulation
394
395**Parameters**
396
397| Name      | Type    | Mandatory| Description                                              |
398| ------------ | -------- | ---- | -------------------------------------------------- |
399| responseApdu | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
400
401### transmit<sup>9+</sup>
402
403transmit(response: number[]): Promise\<void>
404
405Transmits 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](#on8).
406
407**Required permissions**: ohos.permission.NFC_CARD_EMULATION
408
409**System capability**: SystemCapability.Communication.NFC.CardEmulation
410
411**Atomic service API**: This API can be used in atomic services since API version 12.
412
413**Parameters**
414
415| Name      | Type    | Mandatory| Description                                              |
416| ------------ | -------- | ---- | -------------------------------------------------- |
417| response | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
418
419**Return value**
420
421| **Type** | **Description**                                |
422| ------- | -------------------------------------- |
423| Promise\<void> | Promise used to return the result.|
424
425**Error codes**
426
427For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
428
429| ID| Error Message |
430| ------- | -------|
431|201 | Permission denied.                 |
432|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
433|801 | Capability not supported.          |
434| 3100301 | Card emulation running state is abnormal in service. |
435
436**Example**
437```js
438import { cardEmulation } from '@kit.ConnectivityKit';
439import { BusinessError } from '@kit.BasicServicesKit';
440
441let hceService: cardEmulation.HceService = new cardEmulation.HceService();
442
443// the data app wanna send, just a example data
444const responseData = [0x1, 0x2];
445hceService.transmit(responseData).then(() => {
446  // handle the transmit promise
447  console.log("transmit Promise success.");
448}).catch((err: BusinessError) => {
449  console.log("transmit Promise error:", err);
450});
451```
452
453### transmit<sup>9+</sup>
454
455transmit(response: number[], callback: AsyncCallback\<void>): void
456
457Transmits an APDU to the peer card reader. This API uses an asynchronous callback to return the result. The application calls this API only after receiving an APDU sent by the card reader via [on](#on8).
458
459**Required permissions**: ohos.permission.NFC_CARD_EMULATION
460
461**System capability**: SystemCapability.Communication.NFC.CardEmulation
462
463**Atomic service API**: This API can be used in atomic services since API version 12.
464
465**Parameters**
466
467| Name | Type    | Mandatory| Description                   |
468| ------- | -------- | ---- | ----------------------- |
469| response | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
470| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
471
472**Error codes**
473
474For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
475
476| ID| Error Message |
477| ------- | -------|
478|201 | Permission denied.                 |
479|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
480|801 | Capability not supported.          |
481| 3100301 | Card emulation running state is abnormal in service. |
482
483**Example**
484```js
485import { cardEmulation } from '@kit.ConnectivityKit';
486import { BusinessError } from '@kit.BasicServicesKit';
487
488let hceService: cardEmulation.HceService = new cardEmulation.HceService();
489
490// the data app wanna send, just a example data
491try {
492  const responseData = [0x1, 0x2];
493
494  hceService.transmit(responseData, (err : BusinessError)=> {
495    if (err) {
496      console.error(`transmit AsyncCallback err Code: ${err.code}, message: ${err.message}`);
497    } else {
498      console.log("transmit AsyncCallback success.");
499    }
500  });
501} catch (error) {
502  console.error(`transmit AsyncCallback catch Code: ${(error as BusinessError).code}, ` +
503    `message: ${(error as BusinessError).message}`);
504}
505```
506