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 isHceSupported: boolean = cardEmulation.isSupported(cardEmulation.FeatureType.HCE); 155if (!isHceSupported) { 156 console.log('this device is not supported for HCE, ignore it.'); 157} 158 159let hasHceCap: boolean = cardEmulation.hasHceCapability(); 160if (!hasHceCap) { 161 console.log('this device hasHceCapability false, ignore it.'); 162} 163``` 164 165## isDefaultService<sup>9+</sup> 166 167isDefaultService(elementName: ElementName, type: CardType): boolean 168 169Checks whether an application is the default application of the specified service type. 170 171**System capability**: SystemCapability.Communication.NFC.CardEmulation 172 173**Required permissions**: ohos.permission.NFC_CARD_EMULATION 174 175**Atomic service API**: This API can be used in atomic services since API version 12. 176 177**Parameters** 178 179| Name | Type | Mandatory | Description | 180| ----------- | ---------------------------------------- | ---- |-------------------------| 181| 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**.| 182| type | [CardType](#cardtype9) | Yes | Card emulation service type. Currently, only the default payment application can be queried. | 183 184**Error codes** 185 186For details about the error codes, see [NFC Error Codes](errorcode-nfc.md). 187 188| ID| Error Message | 189| -------- | ---------------------------- | 190|201 | Permission denied. | 191|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. | 192|801 | Capability not supported. | 193 194**Return value** 195 196| **Type** | **Description** | 197| ------- | ------------------------------------ | 198| boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.| 199 200 201**Example** 202```js 203import { cardEmulation } from '@kit.ConnectivityKit'; 204import { bundleManager, Want } from '@kit.AbilityKit'; 205 206// Initialize elementName here. bundleName and abilityName are required. 207let want: Want = { 208 bundleName: "com.example.myapplication", 209 moduleName: "entry", 210 abilityName: "EntryAbility" 211}; 212let elementName: bundleManager.ElementName = { 213 bundleName: "com.example.myapplication", 214 moduleName: "entry", 215 abilityName: "EntryAbility" 216}; 217 218let isDefaultService: boolean = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT); 219// Do something according to the isDefaultService value. 220``` 221 222 223## HceService<sup>8+</sup> 224 225Provides 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. 226 227### startHCE<sup>(deprecated)</sup> 228 229startHCE(aidList: string[]): boolean 230 231Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list. 232 233> **NOTE** 234> This API is supported since API version 8 and deprecated since API version 9. Use [start](#start9) instead. 235 236**Required permissions**: ohos.permission.NFC_CARD_EMULATION 237 238**System capability**: SystemCapability.Communication.NFC.CardEmulation 239 240**Parameters** 241 242| Name | Type | Mandatory| Description | 243| ------- | -------- | ---- | ----------------------- | 244| aidList | string[] | Yes | AID list to register.| 245 246**Return value** 247 248| **Type** | **Description** | 249| ------- | -------------------------------------- | 250| boolean | Returns **true** if HCE is started or has been started; returns **false** otherwise.| 251 252### start<sup>9+</sup> 253 254start(elementName: [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname), aidList: string[]): void 255 256Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list. 257 258**Required permissions**: ohos.permission.NFC_CARD_EMULATION 259 260**System capability**: SystemCapability.Communication.NFC.CardEmulation 261 262**Atomic service API**: This API can be used in atomic services since API version 12. 263 264**Parameters** 265 266| Name | Type | Mandatory| Description | 267| ------- | -------- | ---- | ----------------------- | 268| 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.| 269| aidList | string[] | Yes | List of AIDs to register. This parameter can be left empty.| 270 271**Error codes** 272 273For details about the error codes, see [NFC Error Codes](errorcode-nfc.md). 274 275| ID| Error Message | 276| ------- | -------| 277|201 | Permission denied. | 278|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. | 279|801 | Capability not supported. | 280| 3100301 | Card emulation running state is abnormal in service. | 281 282### stopHCE<sup>(deprecated)</sup> 283 284stopHCE(): boolean 285 286Stops HCE, including exiting the current application from the foreground, releasing the dynamically registered AID list, and canceling the subscription of **hceCmd**. 287 288> **NOTE** 289> This API is supported since API version 8 and deprecated since API version 9. Use [stop](#stop9) instead. 290 291**Required permissions**: ohos.permission.NFC_CARD_EMULATION 292 293**System capability**: SystemCapability.Communication.NFC.CardEmulation 294 295**Return value** 296 297| **Type** | **Description** | 298| ------- | -------------------------------------- | 299| boolean | Returns **true** is HCE is stopped; returns **false** otherwise.| 300 301**Example** 302 303For details, see the example of [on](#on8). 304 305### stop<sup>9+</sup> 306 307stop(elementName: [ElementName](../apis-ability-kit/js-apis-bundleManager-elementName.md#elementname)): void 308 309Stops 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. 310 311**Required permissions**: ohos.permission.NFC_CARD_EMULATION 312 313**System capability**: SystemCapability.Communication.NFC.CardEmulation 314 315**Atomic service API**: This API can be used in atomic services since API version 12. 316 317**Parameters** 318 319| Name | Type | Mandatory| Description | 320| ------- | -------- | ---- | ----------------------- | 321| 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.| 322 323**Error codes** 324 325For details about the error codes, see [NFC Error Codes](errorcode-nfc.md). 326 327| ID| Error Message | 328| ------- | -------| 329|201 | Permission denied. | 330|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. | 331|801 | Capability not supported. | 332| 3100301 | Card emulation running state is abnormal in service. | 333 334### on<sup>8+</sup> 335 336on(type: 'hceCmd', callback: AsyncCallback\<number[]>): void 337 338Registers a callback to receive APDUs from the peer card reader. The application needs to call this API in **onCreate()** of the HCE page. 339 340**Required permissions**: ohos.permission.NFC_CARD_EMULATION 341 342**System capability**: SystemCapability.Communication.NFC.CardEmulation 343 344**Atomic service API**: This API can be used in atomic services since API version 12. 345 346**Parameters** 347 348| Name | Type | Mandatory| Description | 349| -------- | ----------------------- | ---- | -------------------------------------------- | 350| type | string | Yes | Callback type to register. It has a fixed value of **hceCmd**. | 351| callback | AsyncCallback\<number[]> | Yes | Callback used to return the APDU, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| 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 //handle the data and err 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 // other life cycle method... 383} 384``` 385 386 387### sendResponse<sup>(deprecated)</sup> 388 389sendResponse(responseApdu: number[]): void 390 391Sends a response to the peer card reader. 392 393> **NOTE** 394> This API is supported since API version 8 and deprecated since API version 9. Use [transmit](#transmit9) instead. 395 396**Required permissions**: ohos.permission.NFC_CARD_EMULATION 397 398**System capability**: SystemCapability.Communication.NFC.CardEmulation 399 400**Parameters** 401 402| Name | Type | Mandatory| Description | 403| ------------ | -------- | ---- | -------------------------------------------------- | 404| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| 405 406### transmit<sup>9+</sup> 407 408transmit(response: number[]): Promise\<void> 409 410Transmits 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). 411 412**Required permissions**: ohos.permission.NFC_CARD_EMULATION 413 414**System capability**: SystemCapability.Communication.NFC.CardEmulation 415 416**Atomic service API**: This API can be used in atomic services since API version 12. 417 418**Parameters** 419 420| Name | Type | Mandatory| Description | 421| ------------ | -------- | ---- | -------------------------------------------------- | 422| response | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| 423 424**Return value** 425 426| **Type** | **Description** | 427| ------- | -------------------------------------- | 428| Promise\<void> | Promise used to return the result.| 429 430**Error codes** 431 432For details about the error codes, see [NFC Error Codes](errorcode-nfc.md). 433 434| ID| Error Message | 435| ------- | -------| 436|201 | Permission denied. | 437|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. | 438|801 | Capability not supported. | 439| 3100301 | Card emulation running state is abnormal in service. | 440 441**Example** 442```js 443import { cardEmulation } from '@kit.ConnectivityKit'; 444import { BusinessError } from '@kit.BasicServicesKit'; 445 446let hceService: cardEmulation.HceService = new cardEmulation.HceService(); 447 448// the data app wanna send, just a example data 449const responseData = [0x1, 0x2]; 450hceService.transmit(responseData).then(() => { 451 // handle the transmit promise 452 console.log("transmit Promise success."); 453}).catch((err: BusinessError) => { 454 console.log("transmit Promise error:", err); 455}); 456``` 457 458### transmit<sup>9+</sup> 459 460transmit(response: number[], callback: AsyncCallback\<void>): void 461 462Transmits 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). 463 464**Required permissions**: ohos.permission.NFC_CARD_EMULATION 465 466**System capability**: SystemCapability.Communication.NFC.CardEmulation 467 468**Atomic service API**: This API can be used in atomic services since API version 12. 469 470**Parameters** 471 472| Name | Type | Mandatory| Description | 473| ------- | -------- | ---- | ----------------------- | 474| response | number[] | Yes | Response APDU sent to the peer card reader. The value consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| 475| callback | AsyncCallback\<void> | Yes | Callback used to return the result.| 476 477**Error codes** 478 479For details about the error codes, see [NFC Error Codes](errorcode-nfc.md). 480 481| ID| Error Message | 482| ------- | -------| 483|201 | Permission denied. | 484|401 | The parameter check failed. Possible causes: <br>1. Mandatory parameters are left unspecified.<br>2. Incorrect parameters types.<br>3. Parameter verification failed. | 485|801 | Capability not supported. | 486| 3100301 | Card emulation running state is abnormal in service. | 487 488**Example** 489```js 490import { cardEmulation } from '@kit.ConnectivityKit'; 491import { BusinessError } from '@kit.BasicServicesKit'; 492 493let hceService: cardEmulation.HceService = new cardEmulation.HceService(); 494 495// the data app wanna send, just a example data 496try { 497 const responseData = [0x1, 0x2]; 498 499 hceService.transmit(responseData, (err : BusinessError)=> { 500 if (err) { 501 console.error(`transmit AsyncCallback err Code: ${err.code}, message: ${err.message}`); 502 } else { 503 console.log("transmit AsyncCallback success."); 504 } 505 }); 506} catch (error) { 507 console.error(`transmit AsyncCallback catch Code: ${(error as BusinessError).code}, ` + 508 `message: ${(error as BusinessError).message}`); 509} 510``` 511