API Reference

Koin Checkout SDK

A simple and secure way to collect credit card details on your website without the burden of PCI DSS compliance.

The Koin Checkout SDK renders a secure iframe on your page, isolating sensitive cardholder data from your domain. Your application receives a secure, single-use token upon submission, which you can then use to process payments via your backend

🗺️ Integration Flow

The integration flow is designed to be straightforward:

  1. Mount: Add an empty div to your site where you want the payment form to appear.
  2. Initialize: Use your unique clientKey to initialize the SDK and mount it into your container.
  3. Tokenize: When the user is ready to pay, call the tokenize() method.
  4. Callback: The SDK will trigger either the onSuccess or onError callback, which you define during initialization.
  5. Process: Send the received token from the onSuccess callback to your backend to process the payment through your server-side integration.

Full Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Koin Checkout Example</title>
  <script src="https://portal-dev.koin.com.br/checkout/static/scripts/sdk/tokenize.js"></script>
  <style>
    /* Basic styling for the example */
    body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
    #koin-checkout-container { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; }
    button { width: 100%; padding: 12px; font-size: 16px; background-color: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; }
    button:disabled { background-color: #ccc; cursor: not-allowed; }
  </style>
</head>
<body>

  <h2>Pay with Card</h2>
  <div id="koin-checkout-container"></div>
  <button id="pay-button">Pay Now</button>
  <p id="feedback-message"></p>

  <script>
    const payButton = document.getElementById('pay-button');
    const feedbackMessage = document.getElementById('feedback-message');

    // 1. Initialize and Mount
    const checkout = koinCheckout
      .initialize({
        clientKey: "YOUR_CLIENT_KEY_HERE",
        language: "en"
      })
      .mount(document.getElementById("koin-checkout-container"))
      .onSuccess((data) => {
        console.log("Tokenization successful:", data);
        feedbackMessage.textContent = `Success! Token: ${data.token}. Sending to server...`;
        payButton.disabled = false;
        // Here you would send the token to your server
        // e.g., sendTokenToServer(data.token);
      })
      .onError((error) => {
        console.error("Tokenization failed:", error);
        const firstError = Object.values(error.errors)[0];
        feedbackMessage.textContent = `Error: ${firstError}`;
        payButton.disabled = false;
      });

    // 2. Add event listener to trigger tokenization
    payButton.addEventListener('click', () => {
      feedbackMessage.textContent = 'Processing...';
      payButton.disabled = true;
      checkout.tokenize();
    });
  </script>

</body>
</html>


🚀 Getting Started

1. Prerequisites

First, you'll need a clientKey.

2. Installation

Add the following script tag to the <head> of your HTML file. It's best practice to load it directly from our server to ensure you're always using the latest, most secure version.

<script src="https://portal-dev.koin.com.br/checkout/static/scripts/sdk/tokenize.js"></script>

URL - Production: https://api-v1.koinsecure.com/checkout/static/scripts/sdk/tokenize.js
URL - Sandbox: https://portal-dev.koin.com.br/checkout/static/scripts/sdk/tokenize.js

3. Implementation

The implementation involves three main steps: creating a container, initializing the SDK, and triggering tokenization.

3.1 Create a Container

First, add an empty div element to your HTML where you want the checkout form to appear.

<div id="koin-checkout-container"></div>

3.2 Initialize and Mount

In your JavaScript, initialize the SDK with your clientKey and mount it to the container you just created.

const checkout = koinCheckout.initialize({
  clientKey: "YOUR_CLIENT_KEY", // Replace with your actual client key
  language: "en", // Optional: 'en', 'es', or 'pt'. Defaults to 'es'.
  css: "https://your-site.com/styles/custom-checkout.css" // Optional: URL for custom styling
}).mount(document.getElementById("koin-checkout-container"));

3.3 Tokenize the Card

When the user is ready to pay, call the checkout.tokenize() method. This is an async function that returns a Promise. We strongly recommend using a try...catch block to handle both success and error states.

document.getElementById('pay-button').addEventListener('click', async () => {
  try {
    // This function validates the form and returns a token if valid.
    const tokenData = await checkout.tokenize();
    
    console.log("Tokenization successful!", tokenData);
    
    // ✅ SUCCESS: Send the tokenData.token to your server for payment processing.
    // await fetch('/your-backend/process-payment', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify({ paymentToken: tokenData.token })
    // });

  } catch (error) {
    // ❌ ERROR: The form is invalid or another error occurred.
    // The error object contains details about the invalid fields.
    console.error("Tokenization failed:", error);
    // You can use error.errors to display messages to the user.
  }
});

📢 Event Handling & Callbacks

While the Promise returned by tokenize() is the primary way to handle the result, you can also set up global event listeners during initialization. These callbacks will be triggered whenever the corresponding event occurs.


MethodDescription
onSuccess(cb)Registers a callback function that fires when tokenization is successful.
onError(cb)Registers a callback function that fires when tokenization fails.
koinCheckout
  .initialize({ clientKey: "YOUR_CLIENT_KEY" })
  .mount(document.getElementById("koin-checkout-container"))
  .onSuccess((data) => {
    // Called upon successful tokenization.
    // Equivalent to the 'resolve' part of the tokenize() Promise.
    console.log("onSuccess Callback Triggered:", data);
  })
  .onError((error) => {
    // Called when tokenization fails.
    // Equivalent to the 'reject' part of the tokenize() Promise.
    console.error("onError Callback Triggered:", error);
  });

⚙️ API Reference

initialize(config)

Initializes the checkout with your configuration.

  • config (Object):
ParameterTypeRequiredDescription
clientKeyStringtrueYour public client key
languageStringfalseSets the component language. Supports 'en', 'es', 'pt'. Defaults to 'es'.
cssStringfalseA URL to a custom CSS file to style the iframe content.

  • Returns: The koinCheckout instance for method chaining.


mount(htmlElement)

Renders the checkout iframe inside a specified DOM element.

  • htmlElement (HTMLElement, required): The container element for the checkout form.
  • Returns: The koinCheckout instance for method chaining.

tokenize()

Validates the form fields and, if valid, requests a secure token from Koin's servers.

  • Returns: A Promise that resolves with a token object ({ bin:"XXXXXXXX",last_four:"XXXX",secure_token: "..." }) or rejects with an error object containing validation details ({ isValid: false, errors: {...} }).

validate()

Performs validation on the form fields without attempting to tokenize the card. Useful for enabling/disabling a submit button in real-time.

  • Returns: A Promise that resolves with a validation result object, e.g., { isValid: boolean, errors: { card_number: "...", ... } }.

destroy()

Removes the checkout iframe and all associated event listeners from the DOM.

  • Returns: The koinCheckout instance.