1# @ohos.nfc.cardEmulation (标准NFC-cardEmulation)
2
3本模块主要提供NFC卡模拟业务,包括判断支持哪种卡模拟类型,HCE卡模拟的业务实现等。
4HCE(Host Card Emulation),称为基于主机的卡模拟,表示不依赖安全单元芯片,应用程序模拟NFC卡片,可以通过NFC服务和NFC读卡器通信。
5
6> **说明:**
7>
8> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
9
10## HCE卡模拟和AID列表的声明定义
11
12开发HCE卡模拟相关应用时,需要在应用的属性配置文件中,声明与NFC相关的属性值,比如,在module.json5文件中,声明下面属性值:
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> **注意:**
50>1. 声明"actions"字段的内容填写,必须包含"ohos.nfc.cardemulation.action.HOST_APDU_SERVICE",不能更改。
51>2. 声明aid时,name必须为payment-aid,或者other-aid。填写错误会造成解析失败。
52>3. 声明权限时"requestPermissions"中的"name"字段的内容填写,必须是"ohos.permission.NFC_CARD_EMULATION",不能更改。
53
54## 导入模块
55
56```
57import { cardEmulation } from '@kit.ConnectivityKit';
58```
59
60## FeatureType<sup>(deprecated)</sup>
61
62定义不同的NFC卡模拟类型。
63
64> **说明:**
65> 从 API version 6 开始支持,从 API version 9 开始废弃,建议使用[hasHceCapability](#hashcecapability9)替代。
66
67**系统能力:** SystemCapability.Communication.NFC.CardEmulation
68
69| 名称   | 值    | 说明       |
70| ---- | ---- | -------- |
71| HCE  | 0    | HCE 卡模拟。 |
72| UICC | 1    | SIM 卡模拟。 |
73| ESE  | 2    | ESE 卡模拟。  |
74
75## CardType<sup>9+</sup>
76
77定义卡模拟应用所使用的业务类型,是支付类型,还是其他类型。
78
79**系统能力:** SystemCapability.Communication.NFC.CardEmulation
80
81**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
82
83| 名称      | 值         | 说明                |
84| ------- | --------- | ----------------- |
85| PAYMENT | "payment" | 卡模拟应用所使用的业务是支付类型。 |
86| OTHER   | "other"   | 卡模拟应用所使用的业务是其他类型。 |
87
88## isSupported<sup>(deprecated)</sup>
89
90isSupported(feature: number): boolean
91
92是否支持某种类型的卡模拟。
93
94> **说明:**
95> 从 API version 6 开始支持,从 API version 9 开始废弃,建议使用[hasHceCapability](#hashcecapability9)替代。
96
97**系统能力:** SystemCapability.Communication.NFC.CardEmulation
98
99**参数:**
100
101| 参数名     | 类型     | 必填   | 说明                                       |
102| ------- | ------ | ---- | ---------------------------------------- |
103| feature | number | 是    | 卡模拟类型值,详细请见[FeatureType](#featuretypedeprecated)枚举值。 |
104
105**返回值:**
106
107| **类型**  | **说明**                                 |
108| ------- | -------------------------------------- |
109| boolean | true: 支持该类型卡模拟,&nbsp;false: 不支持该类型卡模拟。 |
110
111**示例:**
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
126判断设备是否支持HCE卡模拟功能。
127
128**系统能力:** SystemCapability.Communication.NFC.CardEmulation
129
130**需要权限:** ohos.permission.NFC_CARD_EMULATION
131
132**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
133
134**返回值:**
135
136| **类型**  | **说明**                           |
137| ------- | -------------------------------- |
138| boolean | true: 支持HCE,&nbsp;false: 不支持HCE。 |
139
140**错误码**:
141
142以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
143
144| 错误码ID | 错误信息 |
145| -------- | ---------------------------- |
146|201 | Permission denied.                 |
147|801 | Capability not supported.          |
148
149**示例:**
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
169判断指定的应用是否为指定业务类型的默认应用。
170
171**系统能力:** SystemCapability.Communication.NFC.CardEmulation
172
173**需要权限:** ohos.permission.NFC_CARD_EMULATION
174
175**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
176
177**参数:**
178
179| 参数名         | 类型                                       | 必填   | 说明                      |
180| ----------- | ---------------------------------------- | ---- |-------------------------|
181| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname) | 是    | 所属应用声明NFC卡模拟能力的页面信息(至少包含bundleName、abilityName这两项的赋值),不可以为空。 |
182| type        | [CardType](#cardtype9)                   | 是    | 卡模拟业务类型。目前只支持默认支付应用查询。   |
183
184**错误码**:
185
186以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
187
188| 错误码ID | 错误信息 |
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**返回值:**
195
196| **类型**  | **说明**                               |
197| ------- | ------------------------------------ |
198| boolean | true: 是默认支付应用,&nbsp;false: 不是默认支付应用。 |
199
200
201**示例:**
202```js
203import { cardEmulation } from '@kit.ConnectivityKit';
204import { bundleManager, Want } from '@kit.AbilityKit';
205
206// init 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
225提供HCE卡模拟的实现,主要包括接收对端读卡设备的APDU数据,并响应APDU数据到对端读卡设备。使用HCE相关接口前,必须先判断设备是否支持HCE卡模拟能力。
226
227### startHCE<sup>(deprecated)</sup>
228
229startHCE(aidList: string[]): boolean
230
231启动HCE业务功能。包括设置当前应用为前台优先,动态注册AID列表。
232
233> **说明:**
234> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[start](#start9)替代。
235
236**需要权限:** ohos.permission.NFC_CARD_EMULATION
237
238**系统能力:** SystemCapability.Communication.NFC.CardEmulation
239
240**参数:**
241
242| 参数名  | 类型     | 必填 | 说明                    |
243| ------- | -------- | ---- | ----------------------- |
244| aidList | string[] | 是   | 动态注册卡模拟的AID列表。 |
245
246**返回值:**
247
248| **类型**  | **说明**                                 |
249| ------- | -------------------------------------- |
250| boolean | true: 启动HCE功能或HCE已启动,&nbsp;false: 启动失败。 |
251
252### start<sup>9+</sup>
253
254start(elementName: [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname), aidList: string[]): void
255
256启动HCE业务功能。包括设置当前应用为前台优先,动态注册AID列表。
257
258**需要权限:** ohos.permission.NFC_CARD_EMULATION
259
260**系统能力:** SystemCapability.Communication.NFC.CardEmulation
261
262**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
263
264**参数:**
265
266| 参数名  | 类型     | 必填 | 说明                    |
267| ------- | -------- | ---- | ----------------------- |
268| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname) | 是   | 所属应用声明NFC卡模拟能力的页面信息(至少包含bundleName、abilityName这两项的赋值),不可以为空。 |
269| aidList | string[] | 是   | 动态注册卡模拟的AID列表,允许为空。 |
270
271**错误码:**
272
273以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
274
275| 错误码ID | 错误信息|
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
286停止HCE业务功能。包括退出当前应用前台优先,释放动态注册的AID列表,释放hceCmd的订阅。
287
288> **说明:**
289> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[stop](#stop9)替代。
290
291**需要权限:** ohos.permission.NFC_CARD_EMULATION
292
293**系统能力:** SystemCapability.Communication.NFC.CardEmulation
294
295**返回值:**
296
297| **类型**  | **说明**                                 |
298| ------- | -------------------------------------- |
299| boolean | true: 禁用HCE功能或HCE已禁用,&nbsp;false: 禁用失败。 |
300
301**示例:**
302
303示例请参见[on](#on8)接口的示例。
304
305### stop<sup>9+</sup>
306
307stop(elementName: [ElementName](../apis-ability-kit/js-apis-bundleManager-elementName.md#elementname)): void 
308
309停止HCE业务功能。包括取消APDU数据接收的订阅,退出当前应用前台优先,释放动态注册的AID列表。应用程序需要在HCE卡模拟页面的onDestroy函数里调用该接口。
310
311**需要权限:** ohos.permission.NFC_CARD_EMULATION
312
313**系统能力:** SystemCapability.Communication.NFC.CardEmulation
314
315**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
316
317**参数:**
318
319| 参数名  | 类型     | 必填 | 说明                    |
320| ------- | -------- | ---- | ----------------------- |
321| elementName | [ElementName](../apis-ability-kit/js-apis-bundle-ElementName.md#elementname) | 是   | 所属应用声明NFC卡模拟能力的页面信息(至少包含bundleName、abilityName这两项的赋值),不可以为空。 |
322
323**错误码:**
324
325以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
326
327| 错误码ID | 错误信息|
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
338订阅回调,用于接收对端读卡设备发送的APDU数据。应用程序需要在HCE卡模拟页面的onCreate函数里面调用该订阅函数。
339
340**需要权限:** ohos.permission.NFC_CARD_EMULATION
341
342**系统能力:** SystemCapability.Communication.NFC.CardEmulation
343
344**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
345
346**参数:**
347
348| 参数名   | 类型                    | 必填 | 说明                                         |
349| -------- | ----------------------- | ---- | -------------------------------------------- |
350| type     | string                  | 是   | 要订阅的回调类型,固定填"hceCmd"字符串。                         |
351| callback | AsyncCallback\<number[]> | 是   | 订阅的事件回调,入参是符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
352
353**示例:**
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
391发送APDU数据到对端读卡设备。
392
393> **说明:**
394> 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用[transmit](#transmit9)替代。
395
396**需要权限:** ohos.permission.NFC_CARD_EMULATION
397
398**系统能力:** SystemCapability.Communication.NFC.CardEmulation
399
400**参数:**
401
402| 参数名       | 类型     | 必填 | 说明                                               |
403| ------------ | -------- | ---- | -------------------------------------------------- |
404| responseApdu | number[] | 是   | 发送到对端读卡设备的符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
405
406### transmit<sup>9+</sup>
407
408transmit(response: number[]): Promise\<void>
409
410发送APDU数据到对端读卡设备,使用Promise异步回调。应用程序必须在[on](#on8)收到读卡设备发送的APDU数据后,才调用该接口响应数据。
411
412**需要权限:** ohos.permission.NFC_CARD_EMULATION
413
414**系统能力:** SystemCapability.Communication.NFC.CardEmulation
415
416**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
417
418**参数:**
419
420| 参数名       | 类型     | 必填 | 说明                                               |
421| ------------ | -------- | ---- | -------------------------------------------------- |
422| response | number[] | 是   | 发送到对端读卡设备的符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
423
424**返回值:**
425
426| **类型**  | **说明**                                 |
427| ------- | -------------------------------------- |
428| Promise\<void> | 以Promise形式异步返回发送APDU数据的结果。 |
429
430**错误码:**
431
432以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
433
434| 错误码ID | 错误信息|
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**示例:**
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
462发送APDU数据到对端读卡设备,使用Callback异步回调。应用程序必须在[on](#on8)收到读卡设备发送的APDU数据后,才调用该接口响应数据。
463
464**需要权限:** ohos.permission.NFC_CARD_EMULATION
465
466**系统能力:** SystemCapability.Communication.NFC.CardEmulation
467
468**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
469
470**参数:**
471
472| 参数名  | 类型     | 必填 | 说明                    |
473| ------- | -------- | ---- | ----------------------- |
474| response | number[] | 是   | 发送到对端读卡设备的符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
475| callback | AsyncCallback\<void> | 是   | 以callback形式异步返回发送APDU数据的结果。 |
476
477**错误码:**
478
479以下错误码的详细介绍请参见[NFC错误码](errorcode-nfc.md)。
480
481| 错误码ID | 错误信息|
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**示例:**
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
512