> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tonder.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Ionic SDK Lite

The Tonder Ionic SDK Lite is a solution for integrating our system into your mobile application. This solution ensures PCI DSS (Payment Card Industry Data Security Standard) by securely collecting and tokenizing sensitive data in the browser, without exposing your front-end infrastructure to any sensitive data.

This guide will walk you through all the steps, from installation and configuring our SDK to fit your application.

## Installation

Tonder's Ionic SDK can be installed using our [npm package](https://www.npmjs.com/package/@tonder.io/ionic-lite-sdk). Use the following command to install it:

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm i @tonder.io/ionic-lite-sdk
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @tonder.io/ionic-lite-sdk
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @tonder.io/ionic-lite-sdk
    ```
  </Tab>
</Tabs>

## Requirements

To configure our SDK you need to add the following script tags to your HTML:

```html theme={null}
  <script src=https://openpay.s3.amazonaws.com/openpay.v1.min.js></script>
  <script src=https://openpay.s3.amazonaws.com/openpay-data.v1.min.js></script>
```

The code above is necessary to ensure a reliable connection to the payment processor.

<Note>You can also install each one with their respective [npm packages](https://www.npmjs.com/package/openpay-js).</Note>

### Mobile Requirements

<Tabs>
  <Tab title="Android">
    If you are deploying to Android, edit your `AndroidManifest.xml` file to add the Internet permission.

    ```
    <uses-permission android:name="android.permission.INTERNET" />
    ```
  </Tab>

  <Tab title="macOS">
    To deploy to macOS, edit your `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements` files to include the network client entitlement.

    ```
    <key>com.apple.security.network.client</key>
    <true>
    ```
  </Tab>
</Tabs>

## Configuration

With Tonder's SDK installed, and requirements met, you are ready to configure and use the SDK. The following step-by-step process takes you through everything, from starting a new instance, to performing a new transaction using the needed methods:

<Steps>
  <Step title="Import the Lite Checkout class">
    Start by adding the import statement for the `LiteCheckout` class in your file. Following you find an example of how to import the `LiteCheckout`:

    ```js theme={null}
      import { LiteCheckout } from "@tonder.io/ionic-lite-sdk"
    ```

    <Tip>
      The `LiteCheckout` object provides all the necessary methods to perform transactions. Essentially, LiteCheckout handles calls to Tonder services, allowing transactions to be performed without the need to integrate additional visual components.
    </Tip>
  </Step>

  <Step title="Initialize Tonder's SDK Instance">
    Initialize Tonder's Ionic SDK instance adding the following parameters:

    | Field      | Description                                                                                                     |
    | ---------- | --------------------------------------------------------------------------------------------------------------- |
    | `mode`     | Environment mode. Options: `stage`, `production`, `sandbox`, `development`. Default: `stage`                    |
    | `apiKey`   | Your Tonder API key. You can find it in your [Tonder dashboard](https://stage.tonder.io/dashboard/developers/). |
    | `returnrl` | URL where the checkout form is mounted (used for 3DS)                                                           |
    | `callBack` | Callback function to be invoked after the payment process ends successfully.                                    |

    ```js theme={null}
    const mode = 'stage';
    const apiKey = '00d17d61e9240c6e0611fbdb1558e636ed6389db';

    const liteCheckout = new LiteCheckout({ 
      mode, 
      apiKey, 
    });
    ```
  </Step>

  <Step title="Start Checkout Router method">
    Once you have initialized your `liteCheckout` instance, you need to call the `configureCheckout` method and provide all the necessary data as an object. This method handles the entire checkout process, executing the transaction and returning the payment response. To start, call the `configureCheckout` providing the necessary information found below:

    | Parameter       | Type      | Description                                                                                                                      |
    | --------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------- |
    | `order`         | `object`  | Represents the details of each item in the order.                                                                                |
    | `total`         | `number`  | The total amount for the order. This should match the sum of the costs of items in the order.                                    |
    | `customer`      | `object`  | Information about the customer.                                                                                                  |
    | `skyflowTokens` | `object`  | The details of the card to be used on the transaction.                                                                           |
    | `return_url`    | `string`  | URL to which the customer will be redirected after the checkout process is completed.                                            |
    | `isSandbox`     | `boolean` | A boolean indicating if the transaction is being processed in a sandbox environment for testing purposes.                        |
    | `metadata`      | `object`  | Optional additional data about the order that might be used for processing or tracking.                                          |
    | `currency`      | `string`  | The currency in which the transaction is conducted. Refer to the [Currencies Reference](/reference/currencies) page for details. |

    ```js theme={null}
      const checkoutResponse = liteCheckout.configureCheckout({ 
        order, 
        total, 
        customer, 
        skyflowTokens, 
        return_url, 
        isSandbox, 
        metadata, 
        currency
      });
    ```

    Below you find the types for each `configureCheckout` parameter, followed by an example code:

    ```ts theme={null}
      type configureCheckoutRequest = {
          order: {
              items: Array<{
                  description: string;
                  quantity: number;
                  price_unit: number;
                  discount: number;
                  taxes: number;
                  product_reference: number;
                  name: string;
                  amount_total: number;
              }>;
          };
          total: number;
          customer: {
              name: string;
              lastname: string;
              email: string;
              phone: string;
          };
          skyflowTokens: {
              cardholder_name: string;
              card_number: string;
              cvv: string;
              expiration_year: string;
              expiration_month: string;
              skyflow_id: string;
          };
          return_url: string;
          isSandbox: boolean;
          metadata: any;
          currency: string;
      };
    ```

    <Accordion title="Example">
      ```ts theme={null}
      const checkoutRequest: configureCheckoutRequest = {
          order: {
              items: [
                  {
                      description: "High-quality wireless headphones",
                      quantity: 2,
                      price_unit: 199.99,
                      discount: 20.00,
                      taxes: 15.99,
                      product_reference: 101234,
                      name: "Wireless Headphones",
                      amount_total: 395.96
                  },
                  {
                      description: "Ergonomic wireless mouse",
                      quantity: 1,
                      price_unit: 50.00,
                      discount: 5.00,
                      taxes: 3.75,
                      product_reference: 105678,
                      name: "Wireless Mouse",
                      amount_total: 48.75
                  }
              ]
          },
          total: 444.71,
          customer: {
              name: "John",
              lastname: "Doe",
              email: "johndoe@example.com",
              phone: "+11234567890"
          },
          skyflowTokens: {
              cardholder_name: "John Doe",
              card_number: "4111111111111111",
              cvv: "123",
              expiration_year: "2024",
              expiration_month: "12",
              skyflow_id: "abcd-1234-xyz"
          },
          return_url: "https://example.com/checkout/complete",
          isSandbox: true,
          metadata: {
              campaign_id: "BF2024",
              notes: "Customer opted for gift wrapping."
          },
          currency: "USD"
      };
      ```
    </Accordion>
  </Step>

  <Step title="Initialize the Checkout">
    Call the `injectCheckout` method with your liteCheckout instance, with the code below:

    ```javascript theme={null}
    inlineCheckout.injectCheckout();
    ```
  </Step>
</Steps>

## Class Methods

After properly configuring your Lite Checkout instance, you have at your hand various methods to work with Tonder. Below you will find all the available methods, with an example of the data returned by each so you can understand how they work:

<CardGroup cols={4}>
  <Card title="Cards" href="#cards" />

  <Card title="Payment Methods" href="#payment-methods" />

  <Card title="Payment" href="#payment" />

  <Card title="3DS Verification" href="#3ds-verification" />
</CardGroup>

### Cards

Tonder's SDK offers the following methods to manage customer cards:

* `getCustomerCards`
* `saveCustomerCard`
* `removeCustomerCard`

<Warning>You need to use the `secureToken` to be able to manage cards with Tonder's SDK. Refer to the [How to Use secureToken for Secure Card Saving](/integration/sdks/secure-token) to learn how to do this.</Warning>

#### Get Customer Cards

Use the `getCustomerCards` method to retrieve previously saved customer cards:

```js theme={null}
const cards = await liteCheckout.getCustomerCards();
```

#### Save Customer Card

Use the `saveCustomerCard` method to save a new card into the system. This method requires an object as parameter to define the card's properties:

Sure! Here's a markdown table with the keys and their descriptions:

| Key                | Description                                       |
| ------------------ | ------------------------------------------------- |
| `card_number`      | The credit card number without spaces or dashes.  |
| `cvv`              | The card verification value, a 3 or 4-digit code. |
| `expiration_month` | The month when the card expires.                  |
| `expiration_year`  | The year when the card expires.                   |
| `cardholder_name`  | The full name of the cardholder as on the card.   |

```js theme={null}
const cards = await liteCheckout.saveCustomerCard({
    card_number: "4111111111111111",
    cvv: "123",
    expiration_month: "12",
    expiration_year: "25",
    cardholder_name: "John Doe",
  });
```

#### Remove Customer Card

Use the `removeCustomerCards` method to delete a previously saved customer card by passing the card ID as parameter:

```js theme={null}
const cards = await liteCheckout.removeCustomerCards(cardId);
```

### Payment Methods

You can retrieve all available payment methods for a respective user with the `getCustomerPaymentMethods` method:

```js theme={null}
const paymentMethods = await liteCheckout.getCustomerPaymentMethods();
```

### Payment

To create a new payment with the Lite SDK, use the `payment` method. This method requires an object as parameter with the following data:

| Key                 | Description                                         |
| ------------------- | --------------------------------------------------- |
| **customer**        | An object containing customer information           |
| **cart**            | An object containing cart and item details          |
| **currency**        | The currency code for the transaction (e.g., "MXN") |
| **metadata**        | An object for additional metadata (e.g., order ID)  |
| **card**            | An object containing card details for a new card    |
| **payment\_method** | The selected payment method (optional)              |

<AccordionGroup>
  <Accordion title="customer">
    | Key           | Description                |
    | ------------- | -------------------------- |
    | **firstName** | Customer's first name      |
    | **lastName**  | Customer's last name       |
    | **country**   | Customer's country         |
    | **address**   | Customer's street address  |
    | **city**      | Customer's city            |
    | **state**     | Customer's state or region |
    | **postCode**  | Customer's postal code     |
    | **email**     | Customer's email address   |
    | **phone**     | Customer's phone number    |
  </Accordion>

  <Accordion title="cart">
    | Key       | Description               |
    | --------- | ------------------------- |
    | **total** | Total amount for the cart |
    | **items** | An array of item objects  |

    **Item Object Structure**:

    | Key                    | Description                                              |
    | ---------------------- | -------------------------------------------------------- |
    | **description**        | Description of the product                               |
    | **quantity**           | Quantity of the product                                  |
    | **price\_unit**        | Unit price of the product                                |
    | **discount**           | Discount applied to the product                          |
    | **taxes**              | Taxes applied to the product                             |
    | **product\_reference** | Reference code for the product                           |
    | **name**               | Name of the product                                      |
    | **amount\_total**      | Total amount for this product (after discount and taxes) |
  </Accordion>

  <Accordion title="card">
    | Key                   | Description                                     |
    | --------------------- | ----------------------------------------------- |
    | **card\_number**      | The credit card number without spaces or dashes |
    | **cvv**               | Card Verification Value (3 or 4-digit code)     |
    | **expiration\_month** | Card's expiration month (e.g., "12")            |
    | **expiration\_year**  | Card's expiration year (e.g., "25")             |
    | **cardholder\_name**  | Name on the credit card                         |

    *Alternatively, if using a saved card, replace the `card` object with the saved card's identifier:*

    ```javascript theme={null}
    card: "skyflow_id" // for a selected saved card.
    ```
  </Accordion>

  <Accordion title="payment_method">
    Specify this key if using a different payment method instead of a card.

    | Key                 | Description                                |
    | ------------------- | ------------------------------------------ |
    | **payment\_method** | The selected payment method (e.g., "Spei") |
  </Accordion>

  <Accordion title="metadata">
    | Key           | Description                     |
    | ------------- | ------------------------------- |
    | **order\_id** | Unique identifier for the order |
  </Accordion>
</AccordionGroup>

With the required parameter in hand, call the method as presented below:

```js theme={null}
  const paymentData = {
    customer: {
      firstName: "John",
      lastName: "Doe",
      country: "USA",
      address: "123 Main St",
      city: "Anytown",
      state: "CA",
      postCode: "12345",
      email: "john.doe@example.com",
      phone: "1234567890",
    },
    cart: {
      total: "100.00",
      items: [
        {
          description: "Product description",
          quantity: 1,
          price_unit: "100.00",
          discount: "0.00",
          taxes: "0.00",
          product_reference: "PROD123",
          name: "Product Name",
          amount_total: "100.00",
        },
      ],
    },
    currency: "MXN",
    metadata: {
      order_id: "ORDER123",
    },
    // For a new card:
    card: {
      card_number: "4111111111111111",
      cvv: "123",
      expiration_month: "12",
      expiration_year: "25",
      cardholder_name: "John Doe",
    },
    // card: "skyflow_id" // for a selected saved card.
    // payment_method: "Spei", // For the selected payment method.
  };

  const responsePayment = await liteCheckout.payment(paymentData);
```

<Accordion title="Create Payment response">
  The response to this method will be the following:

  ```ts theme={null}
    {
      pk: number,
      order?: string,
      amount: string,
      status: string,
      date: string,
      paid_date?: string,
      shipping_address: {
        street: string,
        number: string,
        suburb: string,
        city: {
          name: string
        },
        state: {
          name: string,
          country: {
              name: string
          }
        },
        zip_code: string
      },
      shipping_address_id?: string,
      billing_address: {
        street: string,
        number: string,
        suburb: string,
        city: {
          name: string
        },
        state: {
          name: string,
          country: {
            name: string
          }
        },
        zip_code: string
      },
      billing_address_id?: string,
      client?: string,
      customer_order_reference?: string
    }
  ```
</Accordion>

### 3DS Verification

You can use the `verify3dsTransaction()` method to validate if a 3DS challenge was successful or not. Use the example below to call the method and handle the response as needed:

```js theme={null}
  liteCheckout.verify3dsTransaction().then(response => {
    console.log('Verify 3ds response', response);
    
    if (response.transaction_status === 'Success') {
      alert('3DS Transaction verified.');
      // Proceed with normal payment flow
    } else if (response.transaction_status === 'Failed') {
      alert('3DS Transaction Failed');
    }
  });
```

## Field Validation

Tonder's SDK provides validation functions to ensure the integrity of card data before submitting them:

| Function                                 | Description                                         |
| ---------------------------------------- | --------------------------------------------------- |
| `validateCardNumber(cardNumber)`         | Validates the card number using the Luhn algorithm. |
| `validateCardholderName(name)`           | Checks if the cardholder name is valid.             |
| `validateCVV(cvv)`                       | Ensures the CVV is in the correct format.           |
| `validateExpirationDate(expirationDate)` | Validates the expiration date in MM/YY format.      |
| `validateExpirationMonth(month)`         | Checks if the expiration month is valid.            |
| `validateExpirationYear(year)`           | Validates the expiration year.                      |

```js Example theme={null}
import {
  validateCardNumber,
  validateCardholderName,
  validateCVV,
  validateExpirationDate,
} from "@tonder.io/ionic-lite-sdk";

const cardNumber = "4111111111111111";
const cardholderName = "John Doe";
const cvv = "123";
const expirationDate = "12/25";

if (
  validateCardNumber(cardNumber) &&
  validateCardholderName(cardholderName) &&
  validateCVV(cvv) &&
  validateExpirationDate(expirationDate)
) {
  // Proceed with payment
} else {
  // Show error message
}
```
