> For the complete documentation index, see [llms.txt](https://docs.one-cp.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.one-cp.com/integration-and-development/checkout-web-sdk.md).

# Web SDK Integration

1-CP Corporate Checkout Web SDK

The 1-CP Web SDK is a lightweight yet powerful JavaScript library that seamlessly integrates the 1-CP Corporate Checkout experience directly into your web applications. It's designed to streamline corporate purchasing, making it as effortless and intuitive as your favorite online shopping experience.

### Why choose the 1-CP Web SDK?

* **Seamless Integration:** Easily embed the 1-CP Corporate Checkout technology into your existing web applications, regardless of your tech stack.
* **Enhanced User Experience:** Provide your employees with a familiar, user-friendly checkout process that boosts adoption and satisfaction, leading to higher compliance.

### Usage

### Installation

You can install the 1-CP Web SDK via npm:

```bash
npm install @one-cp/web-checkout
```

Alternatively, you can include it directly in your HTML file using a script tag:

```html
<script src="https://one-cp-public.s3.eu-central-1.amazonaws.com/init.min.js"></script>
```

### Initialization

To integrate the 1-CP checkout into your web application, follow these steps:

1. Import or include the 1-CP Web SDK in your JavaScript file or HTML file.
2. Call the init function with the required parameters:

```ts
import { init } from "@one-cp/web-checkout";

// Initialize 1-CP checkout
init({
  transactionID: "transaction_id",
  widgetID: "your_widget_id",
  config: {
    env: "sandbox", // or 'production'
    mode: "lightbox", // or 'inline'
    containerID: "checkout-container", // optional, defaults to 'checkout-container'
    expand: false,
    viewOnly: false,
    redirectURL: "https://yoursite.com/success", // optional redirect after success
  },
  onSuccess: (data) => {
    // Callback function on successful transaction
    console.log("Transaction completed successfully", data);
  },
  onError: (message) => {
    // Callback function on transaction error
    console.error("Transaction failed:", message);
  },
  onClose: () => {
    // Callback function on iframe close
    console.log("Checkout iframe closed");
  },
});
```

#### Parameters

<table><thead><tr><th width="140.79998779296875">Parameter</th><th width="403.5999755859375">Description</th><th width="265">Type</th><th>Required</th></tr></thead><tbody><tr><td><code>transactionID</code></td><td>Unique ID for the transaction.</td><td><code>string</code></td><td>Yes</td></tr><tr><td><code>widgetID</code></td><td>ID of the widget associated with the transaction.</td><td><code>string</code></td><td>No</td></tr><tr><td><code>config</code></td><td>Configuration object for customizing the checkout.</td><td><code>OneCPCheckoutConfig</code></td><td>No</td></tr><tr><td><code>onSuccess</code></td><td>Callback function called on successful transaction.</td><td><code>(data: CheckoutInfo) => void</code></td><td>No</td></tr><tr><td><code>onError</code></td><td>Callback function called on transaction error.</td><td><code>(message: string) => void</code></td><td>No</td></tr><tr><td><code>onClose</code></td><td>Callback function called when the user closes the checkout <strong>without completing</strong> the payment (e.g. clicking the X button). This is <strong>not</strong> called after a successful payment.</td><td><code>() => void</code></td><td>No</td></tr></tbody></table>

#### Configuration Object

<table><thead><tr><th width="219.20001220703125">Parameter</th><th width="398.4000244140625">Description</th><th width="243.39990234375">Type</th><th>Default Value</th></tr></thead><tbody><tr><td><code>env</code></td><td>Environment for the checkout.</td><td><code>'sandbox' | 'production'</code></td><td><code>'sandbox'</code></td></tr><tr><td><code>mode</code></td><td>Mode of checkout display.</td><td><code>'lightbox' | 'inline'</code></td><td><code>'lightbox'</code></td></tr><tr><td><code>containerID</code></td><td>ID of the container element for inline mode.</td><td><code>string</code></td><td><code>'checkout-container'</code></td></tr><tr><td><code>expand</code></td><td>Whether to expand the checkout component.</td><td><code>boolean</code></td><td><code>false</code></td></tr><tr><td><code>viewOnly</code></td><td>Hide action buttons (view-only mode).</td><td><code>boolean</code></td><td><code>false</code></td></tr><tr><td><code>useTemplateData</code></td><td>Use template data when in view-only mode.</td><td><code>boolean</code></td><td><code>false</code></td></tr><tr><td><code>lang</code></td><td><a href="https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes">ISO 639 language code</a> for the checkout interface.</td><td><code>'en' | 'de'</code></td><td><code>'en'</code></td></tr><tr><td><code>redirectURL</code></td><td>URL to redirect to after successful transaction completion.</td><td><code>string</code></td><td>-</td></tr><tr><td><code>colors</code></td><td>Custom colors for the checkout interface.</td><td><code>object</code></td><td>See Colors section</td></tr><tr><td><code>logoURL</code></td><td>Custom logo URL for the provider.</td><td><code>string</code></td><td>-</td></tr><tr><td><code>hidePriceOverThumbnail</code></td><td>Hide/show price over thumbnail.</td><td><code>boolean</code></td><td><code>false</code></td></tr><tr><td><code>hideCo2Tag</code></td><td>Hide/show CO2 tag.</td><td><code>boolean</code></td><td><code>false</code></td></tr></tbody></table>

**Important Notes:**

* Passing a widget ID will override the `logoURL` parameter. If no logo is found in the widget configuration, the `logoURL` from the configuration will be used. If neither is available, a default company logo will be displayed.
* Passing a widget ID will override the `hidePriceOverThumbnail` and `hideCo2Tag` parameters.
* Setting a language will override the browser's default language. The language selector in the footer will not be shown. This ensures a consistent language experience for users, regardless of their browser settings.
* If `containerID` is not provided for inline mode, it defaults to `'checkout-container'`. Ensure a DOM element with this ID exists.

#### onSuccess Response Data

When a transaction is completed successfully, the `onSuccess` callback receives a `CheckoutInfo` object with the following structure:

```typescript
interface CheckoutInfo {
  reference: string;
  payment: {
    reference: string;
    provider: string;
  };
  customer: {
    firstName: string;
    lastName: string;
    email?: string;
    phone?: string;
    address?: Address;
  };
  beneficiary?: {
    firstName: string;
    lastName: string;
    email: string;
  };
  billing: {
    name?: string;
    email: string;
    address: Address;
    externalIds: {
      [key: string]: string;
    };
    identifiers: CompanyIdentifiers;
  };
  /**
   * Payment card data will be present if the payment method used is a card and the card details are available.
   * This property will be undefined if the payment was made using a non-card method, or if card data is not returned for security or compliance reasons.
   */
  card?: PaymentCardData;
  reporting?: Record<string, string | number>;
}

interface CompanyIdentifiers {
  VATIN: string;
  BIC?: string;
  DID?: string;
  GLN?: string;
  DUNS?: string;
  TIN?: string;
  LEI?: string;
  IATA?: string;
}

interface Address {
  street: string;
  house: string;
  city: string;
  country: string;
  zipCode: string;
}

interface PaymentCardData {
  fingerprint?: string;
  masked?: string;
  expiryMonth: string;
  expiryYear: string;
  cardHolder: {
    prefix?: string;
    title?: string;
    salutation?: string;
    first?: string;
    last?: string;
  };
  useType: "SINGLE" | "MULTIPLE";
  cardInfo?: {
    type: string;
    brand: string;
    usage: string;
    country: string;
    issuer: string;
  };
}
```

#### Handling the Success State

Understanding the flow after a successful transaction is crucial for creating a seamless user experience. The SDK simplifies this process by handling the post-success redirection for you via the **redirectURL** parameter.

#### The onSuccess Callback

This callback is fired immediately after the payment is successfully processed. It is the ideal place to update your application's state (e.g., clear a shopping cart, update internal order status ) without worrying about UI changes.

#### The redirectURL Parameter

This optional parameter gives you control over the post-checkout experience.

**1. If redirectURL is Provided (Recommended):**

After a successful transaction, the checkout UI will display a confirmation message with a 3-second countdown. Once the countdown finishes, the SDK will automatically redirect the user to the URL you provided. The `onSuccess` callback is fired when the payment completes — `onClose` is **not** called in this flow.

**2. If redirectURL is NOT Provided:**

The behavior depends on the mode.

**Lightbox Mode:** The checkout modal will close automatically after the 3-second countdown. The user will remain on your page.

**Inline Mode:** The success message will remain visible within its container. The user will not be redirected.

#### Color Customization

You can customize the appearance of the checkout interface by providing a `colors` object in the configuration:

<table><thead><tr><th width="248.60003662109375">Color Parameter</th><th width="430.60009765625">Description</th><th>Default Value</th></tr></thead><tbody><tr><td><code>lightbox-color</code></td><td>Lightbox overlay color.</td><td><code>#2e2f4690</code></td></tr><tr><td><code>primary-color</code></td><td>Main color for header text and buttons.</td><td><code>#0866b6</code></td></tr><tr><td><code>light-primary-text</code></td><td>Text color on primary color buttons and components.</td><td><code>#ffffff</code></td></tr><tr><td><code>primary-color-white</code></td><td>Main background color.</td><td><code>#ffffff</code></td></tr><tr><td><code>primary-color-light</code></td><td>Light gray background color.</td><td><code>#f9f9fb</code></td></tr><tr><td><code>dark-primary-text</code></td><td>Main text color.</td><td><code>#000000de</code></td></tr><tr><td><code>medium-color-shade</code></td><td>Color for disabled buttons and other disabled elements.</td><td><code>#b2b8cd</code></td></tr><tr><td><code>accent-color</code></td><td>Hover effects color for buttons and other elements.</td><td><code>#88c7fd</code></td></tr><tr><td><code>tertiary-color-shade-tint</code></td><td>Color for borders and checkboxes.</td><td><code>#d8e4e3</code></td></tr><tr><td><code>danger-color</code></td><td>Background color for alerts and validation form errors.</td><td><code>#eb445a</code></td></tr><tr><td><code>danger-color-text</code></td><td>Text color for error messages and alerts.</td><td><code>#eb445a</code></td></tr><tr><td><code>medium-color-gray</code></td><td>Border color for input fields.</td><td><code>#8d8d8d</code></td></tr></tbody></table>

**Note:** Passing a widget ID will override the color configuration.

### How to Obtain a Transaction ID

To initialize a checkout session, you need to obtain a transaction ID from the 1-CP API:

1. Your backend needs to call the `/initialize` endpoint of the 1-CP API.
2. To obtain `client-id` and `client-secret`, access the 1-CP Dashboard:
   * Navigate to **Config → Widget**
   * Create and configure your widget
   * You will receive the `client-id` and `client-secret` credentials

### Example Implementation

#### HTML Example

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>1-CP Checkout Example</title>
  </head>
  <body>
    <div id="checkout-container"></div>
    <script src="https://one-cp-public.s3.eu-central-1.amazonaws.com/init.min.js"></script>

    <script>
      const transactionID = await request('your-api-to-create-transaction');

      // Initialize 1-CP checkout
      OneCP.init({
        transactionID,
        widgetID: 'your_widget_id',
        config: {
          env: 'sandbox',
          mode: 'inline',
          containerID: 'checkout-container', // optional, defaults to 'checkout-container'
          expand: false,
          viewOnly: false,
          lang: 'de', // Set checkout interface to German
          redirectURL: 'https://yoursite.com/success' // optional redirect after success
        },
        onSuccess: (data) => {
          console.log('Transaction completed successfully', data);
        },
        onError: (message) => {
          console.error('Transaction failed:', message);
        },
        onClose: () => {
          console.log('Checkout iframe closed');
        }
      });
    </script>
  </body>
</html>
```

#### Cleanup and Memory Management

**The SDK handles cleanup automatically** when the checkout process completes normally. This includes:

* **Event Listener Cleanup**: Message event listeners are automatically removed when the checkout closes
* **DOM Cleanup**: Iframe elements and containers (in lightbox mode) are automatically removed
* **Style Restoration**: Original body overflow styles are restored in lightbox mode

**Cleanup Triggers:**

* When the user completes or cancels the checkout
* When a `redirectURL` is provided and the user is redirected after success
* When the iframe sends a 'close' message

**For Single-Page Applications (SPAs):** The automatic cleanup should prevent memory leaks in most scenarios. However, if you need to handle edge cases or force cleanup:

**Edge Case Considerations:**

1. **Unexpected Page Navigation**: If the user navigates away during checkout, cleanup may not trigger
2. **Manual iframe Removal**: If you remove iframe elements manually, ensure proper cleanup
3. **Multiple Rapid Initializations**: Allow previous checkout to complete before initializing a new one

**Best Practices for SPAs:**

* Let the normal checkout flow complete (don't manually interrupt)
* Wait for `onSuccess` or `onClose` before reinitializing — note that after a completed payment only `onSuccess` fires; `onClose` only fires when the user abandons the checkout
* Test your specific use cases to ensure proper cleanup

#### TypeScript Support

The SDK now includes comprehensive TypeScript definitions. All configuration options, callback parameters, and return types are fully typed for better development experience and type safety.
