• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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        // Set reason to card_emulation_reason.
43        "reason": "$string:card_emulation_reason",
44      }
45    ]
46  }
47}
48```
49> **NOTE**
50>1. The **actions** field must contain **ohos.nfc.cardemulation.action.HOST_APDU_SERVICE** and cannot be changed.
51>2. 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>3. 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>
66> This API is supported since API version 6 and deprecated since API version 9. Use [hasHceCapability](#cardemulationhashcecapability9) instead.
67
68**System capability**: SystemCapability.Communication.NFC.CardEmulation
69
70| Name  | Value   | Description      |
71| ---- | ---- | -------- |
72| HCE  | 0    | HCE.|
73| UICC | 1    | Subscriber identity module (SIM) card emulation.|
74| ESE  | 2    | embedded Secure Element (eSE) emulation. |
75
76## CardType<sup>9+</sup>
77
78Enumerates the types of services used by the card emulation application.
79
80**System capability**: SystemCapability.Communication.NFC.CardEmulation
81
82**Atomic service API**: This API can be used in atomic services since API version 12.
83
84| Name     | Value        | Description               |
85| ------- | --------- | ----------------- |
86| PAYMENT | "payment" | Payment service.|
87| OTHER   | "other"   | Other services.|
88
89## cardEmulation.isSupported<sup>(deprecated)</sup>
90
91isSupported(feature: number): boolean
92
93Checks whether a certain type of card emulation is supported.
94
95> **NOTE**
96>
97> This API is supported since API version 6 and deprecated since API version 9. Use [hasHceCapability](#cardemulationhashcecapability9) instead.
98
99**System capability**: SystemCapability.Communication.NFC.CardEmulation
100
101**Parameters**
102
103| Name    | Type    | Mandatory  | Description                                      |
104| ------- | ------ | ---- | ---------------------------------------- |
105| feature | number | Yes   | Card emulation type to check. For details, see [FeatureType](#featuretypedeprecated).|
106
107**Return value**
108
109| **Type** | **Description**                                |
110| ------- | -------------------------------------- |
111| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
112
113**Example**
114
115```js
116import { cardEmulation } from '@kit.ConnectivityKit';
117
118let isHceSupported: boolean = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
119if (!isHceSupported) {
120    console.log('this device is not supported for HCE, ignore it.');
121}
122```
123
124## cardEmulation.hasHceCapability<sup>9+</sup>
125
126hasHceCapability(): boolean
127
128Checks whether the device supports HCE.
129
130**System capability**: SystemCapability.Communication.NFC.CardEmulation
131
132**Required permissions**: ohos.permission.NFC_CARD_EMULATION
133
134**Atomic service API**: This API can be used in atomic services since API version 12.
135
136**Return value**
137
138| **Type** | **Description**                          |
139| ------- | -------------------------------- |
140| boolean | Returns **true** if HCE is supported; returns **false** otherwise.|
141
142**Error codes**
143
144For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
145
146| ID| Error Message |
147| -------- | ---------------------------- |
148|201 | Permission denied.                 |
149|801 | Capability not supported.          |
150
151**Example**
152
153```js
154import { cardEmulation } from '@kit.ConnectivityKit';
155
156let hasHceCap: boolean = cardEmulation.hasHceCapability();
157if (!hasHceCap) {
158    console.log('this device hasHceCapability false, ignore it.');
159}
160```
161
162## cardEmulation.isDefaultService<sup>9+</sup>
163
164isDefaultService(elementName: ElementName, type: CardType): boolean
165
166Checks whether an application is the default application of the specified service type.
167
168**System capability**: SystemCapability.Communication.NFC.CardEmulation
169
170**Required permissions**: ohos.permission.NFC_CARD_EMULATION
171
172**Atomic service API**: This API can be used in atomic services since API version 12.
173
174**Parameters**
175
176| Name        | Type                                      | Mandatory  | Description                     |
177| ----------- | ---------------------------------------- | ---- |-------------------------|
178| elementName | [ElementName](../apis-ability-kit/js-apis-bundleManager-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.|
179| type        | [CardType](#cardtype9)                   | Yes   | Card emulation service type. Currently, only the default payment application can be queried.  |
180
181**Error codes**
182
183For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
184
185| ID| Error Message |
186| -------- | ---------------------------- |
187|201 | Permission denied.                 |
188|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
189|801 | Capability not supported.          |
190
191**Return value**
192
193| **Type** | **Description**                              |
194| ------- | ------------------------------------ |
195| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
196
197
198**Example**
199```js
200import { cardEmulation } from '@kit.ConnectivityKit';
201import { bundleManager, Want } from '@kit.AbilityKit';
202
203// Initialize elementName, bundleName, and abilityName and set their values correctly based on the actual application information.
204let elementName: bundleManager.ElementName = {
205  bundleName: "com.example.myapplication",
206  moduleName: "entry",
207  abilityName: "EntryAbility"
208};
209
210let isDefaultService: boolean = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT);
211```
212
213## HceService<sup>8+</sup>
214
215Provides 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.
216
217### startHCE<sup>(deprecated)</sup>
218
219startHCE(aidList: string[]): boolean
220
221Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
222
223> **NOTE**
224> This API is supported since API version 8 and deprecated since API version 9. Use [start](#start9) instead.
225
226**Required permissions**: ohos.permission.NFC_CARD_EMULATION
227
228**System capability**: SystemCapability.Communication.NFC.CardEmulation
229
230**Parameters**
231
232| Name | Type    | Mandatory| Description                   |
233| ------- | -------- | ---- | ----------------------- |
234| aidList | string[] | Yes  | AID list to register.|
235
236**Return value**
237
238| **Type** | **Description**                                |
239| ------- | -------------------------------------- |
240| boolean | Returns **true** if HCE is started or has been started; returns **false** otherwise.|
241
242### start<sup>9+</sup>
243
244start(elementName: [ElementName](../apis-ability-kit/js-apis-bundleManager-elementName.md#elementname), aidList: string[]): void
245
246Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list.
247
248**Required permissions**: ohos.permission.NFC_CARD_EMULATION
249
250**System capability**: SystemCapability.Communication.NFC.CardEmulation
251
252**Atomic service API**: This API can be used in atomic services since API version 12.
253
254**Parameters**
255
256| Name | Type    | Mandatory| Description                   |
257| ------- | -------- | ---- | ----------------------- |
258| elementName | [ElementName](../apis-ability-kit/js-apis-bundleManager-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.|
259| aidList | string[] | Yes  | List of AIDs to register. This parameter can be left empty.|
260
261**Error codes**
262
263For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
264
265| ID| Error Message |
266| ------- | -------|
267|201 | Permission denied.                 |
268|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
269|801 | Capability not supported.          |
270| 3100301 | Card emulation running state is abnormal in service. |
271
272### stopHCE<sup>(deprecated)</sup>
273
274stopHCE(): boolean
275
276Stops HCE, including exiting the current application from the foreground, releasing the dynamically registered AID list, and canceling the subscription of **hceCmd**.
277
278> **NOTE**
279> This API is supported since API version 8 and deprecated since API version 9. Use [stop](#stop9) instead.
280
281**Required permissions**: ohos.permission.NFC_CARD_EMULATION
282
283**System capability**: SystemCapability.Communication.NFC.CardEmulation
284
285**Return value**
286
287| **Type** | **Description**                                |
288| ------- | -------------------------------------- |
289| boolean | Returns **true** is HCE is stopped; returns **false** otherwise.|
290
291**Example**
292
293For details, see the example of [on](#on8).
294
295### stop<sup>9+</sup>
296
297stop(elementName: [ElementName](../apis-ability-kit/js-apis-bundleManager-elementName.md#elementname)): void
298
299Stops 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.
300
301**Required permissions**: ohos.permission.NFC_CARD_EMULATION
302
303**System capability**: SystemCapability.Communication.NFC.CardEmulation
304
305**Atomic service API**: This API can be used in atomic services since API version 12.
306
307**Parameters**
308
309| Name | Type    | Mandatory| Description                   |
310| ------- | -------- | ---- | ----------------------- |
311| elementName | [ElementName](../apis-ability-kit/js-apis-bundleManager-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.|
312
313**Error codes**
314
315For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
316
317| ID| Error Message |
318| ------- | -------|
319|201 | Permission denied.                 |
320|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
321|801 | Capability not supported.          |
322| 3100301 | Card emulation running state is abnormal in service. |
323
324### on<sup>8+</sup>
325
326on(type: 'hceCmd', callback: AsyncCallback\<number[]>): void
327
328Subscribes to events indicating receiving of APDUs from the peer card reader. The application needs to call this API in **onCreate()** of the HCE page.
329
330**Required permissions**: ohos.permission.NFC_CARD_EMULATION
331
332**System capability**: SystemCapability.Communication.NFC.CardEmulation
333
334**Atomic service API**: This API can be used in atomic services since API version 12.
335
336**Parameters**
337
338| Name  | Type                   | Mandatory| Description                                        |
339| -------- | ----------------------- | ---- | -------------------------------------------- |
340| type     | string                  | Yes  | Event type. It has a fixed value of **hceCmd**.                        |
341| callback | AsyncCallback\<number[]> | Yes  | Event callback, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
342
343**Error codes**
344
345For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
346
347| ID| Error Message |
348| ------- | -------|
349|201 | Permission denied.                 |
350|401 | Invalid parameter.                 |
351|801 | Capability not supported.          |
352
353**Example**
354```js
355import { hilog } from '@kit.PerformanceAnalysisKit';
356import { cardEmulation } from '@kit.ConnectivityKit';
357import { AsyncCallback } from '@kit.BasicServicesKit';
358import { ElementName } from './bundleManager/ElementName'
359import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
360
361let hceService: cardEmulation.HceService = new cardEmulation.HceService();
362let element: ElementName;
363
364export default class EntryAbility extends UIAbility {
365  onCreate(want: Want, param: AbilityConstant.LaunchParam) {
366    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onCreate');
367    element = {
368      bundleName: want.bundleName ?? '',
369      abilityName: want.abilityName ?? '',
370      moduleName: want.moduleName
371    }
372    const apduCallback: AsyncCallback<number[]> = (err, data) => {
373      // Implement data processing and handle exceptions.
374      console.log("got apdu data");
375    };
376    hceService.on('hceCmd', apduCallback);
377  }
378  onDestroy() {
379    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onDestroy');
380    hceService.stop(element);
381  }
382  // Implement other lifecycle functions as demanded.
383}
384```
385
386### off<sup>18+</sup>
387
388off(type: 'hceCmd', callback?: AsyncCallback\<number[]>): void
389
390Unsubscribes from events indicating receiving of APDUs from the peer card reader.
391
392**Required permissions**: ohos.permission.NFC_CARD_EMULATION
393
394**System capability**: SystemCapability.Communication.NFC.CardEmulation
395
396**Atomic service API**: This API can be used in atomic services since API version 18.
397
398**Parameters**
399
400| Name  | Type                   | Mandatory| Description                                        |
401| -------- | ----------------------- | ---- | -------------------------------------------- |
402| type     | string                  | Yes  | Event type. It has a fixed value of **hceCmd**.                        |
403| callback | AsyncCallback\<number[]> | No  | Event callback.|
404
405**Error codes**
406
407For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
408
409| ID| Error Message |
410| ------- | -------|
411|201 | Permission denied.                 |
412|401 | Invalid parameter.                 |
413|801 | Capability not supported.          |
414
415**Example**
416```js
417import { hilog } from '@kit.PerformanceAnalysisKit';
418import { cardEmulation } from '@kit.ConnectivityKit';
419import { AsyncCallback } from '@kit.BasicServicesKit';
420import { ElementName } from './bundleManager/ElementName'
421import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
422
423let hceService: cardEmulation.HceService = new cardEmulation.HceService();
424let element: ElementName;
425const apduCallback: AsyncCallback<number[]> = (err, data) => {
426  // Implement data processing and handle exceptions.
427  console.log("AsyncCallback got apdu data");
428};
429
430export default class EntryAbility extends UIAbility {
431  onCreate(want: Want, param: AbilityConstant.LaunchParam) {
432    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onCreate');
433    element = {
434      bundleName: want.bundleName ?? '',
435      abilityName: want.abilityName ?? '',
436      moduleName: want.moduleName
437    }
438    const apduCallback: AsyncCallback<number[]> = (err, data) => {
439      // Implement data processing and handle exceptions.
440      console.log("got apdu data");
441    };
442    hceService.on('hceCmd', apduCallback);
443  }
444  onDestroy() {
445    hilog.info(0x0000, 'testHce', '%{public}s', 'Ability onDestroy');
446    hceService.off('hceCmd', apduCallback);
447    hceService.stop(element);
448  }
449  // Implement other lifecycle functions as demanded.
450}
451```
452
453### sendResponse<sup>(deprecated)</sup>
454
455sendResponse(responseApdu: number[]): void
456
457Sends a response to the peer card reader.
458
459> **NOTE**
460> This API is supported since API version 8 and deprecated since API version 9. Use [transmit](#transmit9) instead.
461
462**Required permissions**: ohos.permission.NFC_CARD_EMULATION
463
464**System capability**: SystemCapability.Communication.NFC.CardEmulation
465
466**Parameters**
467
468| Name      | Type    | Mandatory| Description                                              |
469| ------------ | -------- | ---- | -------------------------------------------------- |
470| responseApdu | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
471
472### transmit<sup>9+</sup>
473
474transmit(response: number[]): Promise\<void>
475
476Transmits 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).
477
478**Required permissions**: ohos.permission.NFC_CARD_EMULATION
479
480**System capability**: SystemCapability.Communication.NFC.CardEmulation
481
482**Atomic service API**: This API can be used in atomic services since API version 12.
483
484**Parameters**
485
486| Name      | Type    | Mandatory| Description                                              |
487| ------------ | -------- | ---- | -------------------------------------------------- |
488| response | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
489
490**Return value**
491
492| **Type** | **Description**                                |
493| ------- | -------------------------------------- |
494| Promise\<void> | Promise used to return the result.|
495
496**Error codes**
497
498For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
499
500| ID| Error Message |
501| ------- | -------|
502|201 | Permission denied.                 |
503|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
504|801 | Capability not supported.          |
505| 3100301 | Card emulation running state is abnormal in service. |
506
507**Example**
508```js
509import { cardEmulation } from '@kit.ConnectivityKit';
510import { BusinessError } from '@kit.BasicServicesKit';
511
512let hceService: cardEmulation.HceService = new cardEmulation.HceService();
513
514// Data to be sent by the application. The following data is for reference only.
515const responseData = [0x1, 0x2];
516hceService.transmit(responseData).then(() => {
517  // Process the promise.
518  console.log("transmit Promise success.");
519}).catch((err: BusinessError) => {
520  console.log("transmit Promise error:", err);
521});
522```
523
524### transmit<sup>9+</sup>
525
526transmit(response: number[], callback: AsyncCallback\<void>): void
527
528Transmits 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).
529
530**Required permissions**: ohos.permission.NFC_CARD_EMULATION
531
532**System capability**: SystemCapability.Communication.NFC.CardEmulation
533
534**Atomic service API**: This API can be used in atomic services since API version 12.
535
536**Parameters**
537
538| Name | Type    | Mandatory| Description                   |
539| ------- | -------- | ---- | ----------------------- |
540| response | number[] | Yes  | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
541| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
542
543**Error codes**
544
545For details about the error codes, see [NFC Error Codes](errorcode-nfc.md).
546
547| ID| Error Message |
548| ------- | -------|
549|201 | Permission denied.                 |
550|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. |
551|801 | Capability not supported.          |
552| 3100301 | Card emulation running state is abnormal in service. |
553
554**Example**
555```js
556import { cardEmulation } from '@kit.ConnectivityKit';
557import { BusinessError } from '@kit.BasicServicesKit';
558
559let hceService: cardEmulation.HceService = new cardEmulation.HceService();
560
561// Data to be sent by the application. The following data is for reference only.
562try {
563  const responseData = [0x1, 0x2];
564
565  hceService.transmit(responseData, (err : BusinessError)=> {
566    if (err) {
567      console.error(`transmit AsyncCallback err Code: ${err.code}, message: ${err.message}`);
568    } else {
569      console.log("transmit AsyncCallback success.");
570    }
571  });
572} catch (error) {
573  console.error(`transmit AsyncCallback catch Code: ${(error as BusinessError).code}, ` +
574    `message: ${(error as BusinessError).message}`);
575}
576```
577