# Web/WAP 

> Learn how to integrate the independent card binding SDK into a web or WAP client.

In this topic, you'll learn how to integrate the card vaulting SDK into a web or WAP client. This will allow you to render the card vaulting page in a computer or mobile browser.

---

## Prerequisites

Before the integration, ensure that you have completed the following tasks:

- Install npm (Node Package Manager).
- Properly handle compatibility issues: Provide corresponding polyfills for Internet Explorer and other old browser versions. We recommend that you use [babel-preset-env](https://babeljs.io/docs/babel-preset-env) to address browser compatibility issues when you build a project.
- Use the following recommended browser versions:
  - For mobile browsers:
    - iOS 11 and later
    - Android 5.0 and later
  - For computer browsers, use the following recommended versions:

| Edge | Firefox | Chrome | Safari | Opera | Electron |
|------|---------|--------|--------|-------|----------|
| Latest 2 versions | Latest 2 versions | Latest 2 versions | Latest 2 versions | Latest 2 versions | Last 2 versions |

---

## Key integration steps

Integrate the independent card vaulting SDK by following these steps:

### Step 1: Integrate the SDK package

**Merchant client**

To integrate the SDK package, please refer to [Integrate the SDK Package for Web/WAP](https://docs.antom.com/ac/sdks/web.md).

### Step 2: Create an SDK instance by using `AMSVaulting`

**Merchant client**

- Create a config object: Required. The object must contain all of the following configuration parameters:
  - **locale**: Optional. String type. It is used to pass in language information. Valid values are listed as follows. If other values are passed, English is used by default:
    - `en_US`: English
    - `pt_BR`: Portuguese
    - `ko_KR`: Korean
    - `es_ES`: Spanish
    - `fr_FR`: French
    - `nl_NL`: Dutch
    - `it_IT`: Italian
    - `de_DE`: German
    - `zh_CN`: Simplified Chinese
    - `zh_HK`: Traditional Chinese
  - **environment**: Required string. It is used to pass in environmental information. Valid values are:
    - `sandbox`: Sandbox environment
    - `prod`: Production environment
  - **analytics**: Optional object. It is used to configure and analyze data. It contains a value below:
    - **enabled**: Optional Boolean. It defaults to `true`, which indicates that you allow the SDK to upload and analyze operational data to deliver a better service. If you do not allow the data to be uploaded and analyzed, specify it as `false`.
  - **onLog**: Optional. It is a callback method that is used to generate the error information about logs and API exceptions during the execution of the SDK.
  - **onEventCallback**: Optional. A callback function that returns various types of data or values, including event codes. See the [References](https://docs.antom.com/ac/sdks/ref.md) for further information.
  - **onError**: Optional. Triggered when an error occurs during SDK usage (initialization exception, network timeout, etc.). Refer to the error codes in the References.

- Instantiate `AMSVaulting`.

**Example - Obtain the browser language:**

```javascript
let language = navigator.language || navigator.userLanguage;
language = language.replace("-", "_"); // Replace "-" with "_"
```

**Example - Create an SDK instance (npm):**

```javascript
import { AMSVaulting } from '@alipay/ams-checkout' // Package management

const vaultingApp = new AMSVaulting({
  environment: "sandbox",
  locale: "en_US",
  analytics: {
    enabled: true
  },
  onLog: ({code, message})=>{},
  onEventCallback: ({code, result})=>{},
  onError: ({code, result})=>{}
});
```

**Example - Create an SDK instance (CDN):**

```javascript
const vaultingApp = new window.AMSVaulting({
  environment: "sandbox",
  locale: "en_US",
  analytics: {
    enabled: true
  },
  onLog: ({code, message})=>{},
  onEventCallback: ({code, result})=>{},
  onError: ({code, message})=>{}
});
```

### Step 3: Initiate a createVaultingSession request

**Merchant server**

The merchant client monitors the click events of the **Add Card** button itself. When the buyer clicks the card vaulting button, the merchant server sends the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md) request to the Antom server. Once the response to the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md) request is received, the `vaultingSessionData` value in the response is used in Step 4.

If you need to automatically redirect buyers to your page after card vaulting is complete, pass in the `redirectUrl` field in the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md) API. If you want to control the subsequent process of card vaulting through client-side event codes, you do not need to pass in the `redirectUrl` field. You can monitor the card vaulting result event code through `onEventCallback`.

> **Note**: The vaulting result event code returned by the client is only used as a reference for redirection operations on the client page. Please refer to the [notifyVaulting](https://docs.antom.com/ac/apo/notify_vaulting.md) API on the server for updates on the vaulting status.

**Example - createVaultingSession request:**

```json
{
  "paymentMethodType": "CARD",
  "vaultingRequestId":"vaultingRequestId_001",
  "vaultingNotificationUrl": "https://www.example.com.sg",
  "redirectUrl": "https://www.example.com"
}
```

**Example - Response for createVaultingSession request:**

```json
{
  "vaultingSessionData": "UNvjVWnWPXJA4BgW+vfjsQj7PbOraafHY19X+6EqMz6Kvvmsdk+akdLvoShW5avHX8e8J15P8uNVEf/PcCMyXg==&&SG&&111",
  "vaultingSessionExpiryTime": "2023-04-06T03:28:49Z",
  "vaultingSessionId": "UNvjVWnWPXJA4BgW+vfjsQj7PbOraafHY19X+6EqMz6Ikyj9FPVUOpv+DjiIZqMe",
  "result": {
    "resultCode": "SUCCESS",
    "resultMessage": "success.",
    "resultStatus": "S"
  }
}
```

### Step 4: Create a card vaulting component using the createComponent method in the instance object

**Merchant client**

- Create a configuration object using the **sessionData** parameter: Pass in the complete data of the `vaultingSessionData` field obtained in the response of the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md) request into the `sessionData` parameter.

- Call the `createComponent()` method in the instance object, returning a `Promise` with the component instance object obtained using this method. The vaulting block DOM node can render a pop-up view on the current page based on parameters:
  - **notRedirectAfterComplete**: Optional, Boolean type. The default value is `false`, which means it will jump back to your page after the card vaulting is completed. The same applies when the value is empty. `true` value means there will be no jump after the card vaulting is completed. You need to use the customer event code to control the card vaulting to complete the subsequent process. Please note that the card vaulting result event code returned by the client is only used as a reference for the jump operation of the client page. For transaction status's updates, please refer to the results returned by the server's [notifyVaulting](https://docs.antom.com/ac/apo/notify_vaulting.md) or [inquireVaulting](https://docs.antom.com/ac/apo/inquire_vaulting.md) API.

- Free resources of the SDK component by calling the `unmount()` method in the instance object. You need to unmount a component in the following cases:
  - When the user switches views to exit the card vaulting page, free the component resources created in the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md).
  - When the user initiates multiple card vaulting requests, free the component resources created in the previous [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md).
  - When the user completes the card vaulting and sets `notRedirectAfterComplete` to `true`, free the component resources after obtaining specific vaulting result codes.

**Example - Call the createComponent() method:**

```javascript
async function create(sessionData) {
  await vaultingApp.createComponent({ 
    sessionData: sessionData, 
    notRedirectAfterComplete: true,
  });
}
// Free SDK component resources
vaultingApp.unmount();
```

---

## Sample code of key integration steps

The following sample code demonstrates the key steps in the integration process. The code does not include examples of calling the [createVaultingSession](https://docs.antom.com/ac/apo/vaulting_session.md) API. You need to handle the server API calls on your own.

```javascript
import { AMSVaulting } from '@alipay/ams-checkout'

const vaultingApp = new AMSVaulting({
  environment: "sandbox",
  locale: "en_US",
  analytics: {
    enabled: true
  },
  onLog: ({code, message})=>{},
  onEventCallback: ({code, result})=>{
    if (code === "SDK_ASSET_BINDING_SUCCESSFUL") {
      // Card vaulting is successful. The SDK needs to be revoked. It is recommended to redirect to the card vaulting result page.
    } else if (code === "SDK_ASSET_BINDING_FAIL") {
      // Card vaulting failed. We suggest that you follow the vaultingResultCode error code prompt and guide the buyer to retry card vaulting.
    } else if (code === "SDK_ASSET_BINDING_ERROR") {
      // Card vaulting is abnormal. We suggest that you wait for the card vaulting result notification or redirect the buyer to retry card vaulting.
    } else {
      // Other custom event or errors
    }
  },
  onError: ({code, message})=>{}
});

// You must initiate a createVaultingSession request to the Antom server before calling the following
async function create(sessionData) {
  await vaultingApp.createComponent({ 
    sessionData: sessionData, 
    notRedirectAfterComplete: true,
  });
}

// Free SDK component resources when needed
vaultingApp.unmount();
```

---

## Event codes

The SDK may return the following event codes during the card vaulting process:

| Event Code | Description |
|------------|-------------|
| `SDK_ASSET_BINDING_SUCCESSFUL` | Card vaulting is successful. |
| `SDK_ASSET_BINDING_FAIL` | Card vaulting failed. |
| `SDK_ASSET_BINDING_ERROR` | Card vaulting encountered an error. |

---

## References

The References offers callback data and code samples for integration steps. For further details, refer to the [References](https://docs.antom.com/ac/sdks/ref.md).

---