# 交通卡更新

交通卡的更新可以用在更新卡片有效期等卡内数据的场景，其过程分为：卡片展示、生成更新业务订单和发起更新三个步骤，整体流程如下图，相关接口定义请参照钱包服务API。

*   开发者的app启动后，可调用getCardMetadataInDevice接口获取指定设备上开发者的app可以访问的交通卡的信息以数组的方式返回。如返回的数组为空，则表示开发者的app在该设备上没有可访问的交通卡，无需显示卡片开通入口；如返回数组不为空，则按具体的交通卡信息做展示。如果交通卡信息中包括卡号、余额信息，则表明该卡片在设备上已开通，显示卡片信息即可；否则可显示卡片的开通入口。
    
*   用户选择了要更新的交通卡后，开发者的app需向开发者的后台服务器发起更新业务订单的生成请求。
    
*   开发者的app可调用updateTransitCard接口发起更新处理过程。如更新过程出现异常导致失败，开发者的app会收到相应的错误码，可参考ArkTS API错误码。
    

#### 开发步骤

1.  获取设备上已开通的交通卡列表。
    
    初始化TransitCardClient时，构造方法的第二个入参callerId是接口调用方ID。开发者可以联系钱包运营申请交通卡服务时获取。
    
    ```
    import { common } from '@kit.AbilityKit';
    import { walletTransitCard } from '@kit.WalletKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    @Entry
    @Component
    struct Index {
      private transitCardClient: walletTransitCard.TransitCardClient = new walletTransitCard.TransitCardClient(this.getUIContext().getHostContext() as common.UIAbilityContext, 'callerId');
    
      async getCardMetadataInDevice() {
        this.transitCardClient.getCardMetadataInDevice(walletTransitCard.DeviceType.DEVICE_PHONE).then((result) => {
          console.info(`Succeeded in getting cardMetadataInDevice`);
        }).catch((err: BusinessError) => {
          console.error(`Failed to get CardMetadataInDevice, code:${err.code}, message:${err.message}`);
        })
      }
    
      build() {
        // your application UI
      }
    }
    ```
    
2.  更新交通卡。
    
    ```
    import { common } from '@kit.AbilityKit';
    import { walletTransitCard } from '@kit.WalletKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    @Entry
    @Component
    struct Index {
      private transitCardClient: walletTransitCard.TransitCardClient = new walletTransitCard.TransitCardClient(this.getUIContext().getHostContext() as common.UIAbilityContext, 'callerId');
    
      async updateTransitCard() {
        // number of the enabled traffic card returned by the step 1
        const logicalCardNumber = 'logicalCardNumber';
        // the specifiedDeviceId returned by the step 1
        const specifiedDeviceId = 'specifiedDeviceId';
        // order ID generated after payment in a developer's app, which is implemented by the developer
        const serverOrderId = 'serverOrderId';
        this.transitCardClient.updateTransitCard(logicalCardNumber, specifiedDeviceId, serverOrderId).then(() => {
          console.info(`Succeeded in updating TransitCard`);
        }).catch((err: BusinessError) => {
          console.error(`Failed to update TransitCard, code:${err.code}, message:${err.message}`);
        })
      }
    
      build() {
        // your application UI
      }
    }
    ```