# Checkout SDK

The Odus Checkout is a flexible, easy-to-implement JavaScript SDK that allows merchants to accept payments on their websites with minimal integration effort. This documentation provides all the necessary information to successfully implement the Odus Checkout on your website.

## Table of Contents

- [Installation](#installation)
- [Getting Started](#getting-started)
- [Configuration Options](#configuration-options)
- [Payment Methods](#payment-methods)
- [Callbacks and Event Handling](#callbacks-and-event-handling)
- [Localization Support](#localization-support)
- [Advanced Usage](#advanced-usage)
- [API Reference](#api-reference)
- [Troubleshooting](#troubleshooting)
- [Related Guides](#related-guides)

## Installation

### CDN Usage (Browser)

```html
<script src="https://cdn.example.com/odus-js/checkout.js"></script>

<script>
  document.addEventListener('DOMContentLoaded', () => {
    let checkout = null;

    function initializeCheckout() {
      try {
        // Create checkout configuration
        const checkoutConfig = {
          // Your configuration
        };

        // Initialize and mount checkout
        checkout = new window.OdusCheckout(checkoutConfig);
        checkout.mount('#checkout-container');
      } catch (error) {
        console.error('Checkout initialization error details:', error);
        console.trace();
      }
    }

    // Initialize checkout immediately
    initializeCheckout();
  });
</script>
```

### NPM Usage (Module)

```bash
npm install @odus/checkout
```

```javascript
import { OdusCheckout } from '@odus/checkout';
// Import the required styles
import '@odus/checkout/styles';

function CheckoutPage() {
  useEffect(() => {
    const checkout = new OdusCheckout({
      //  your configuration
    });

    try {
      checkout.mount('#checkout-container');
    } catch (error) {
      console.error('Error mounting checkout:', error);
    }

    return () => {
      checkout.unmount();
    };
  }, []);

  return <div id="checkout-container" />;
}
```

> **Important**: Always import the styles using `import '@odus/checkout/styles'` to ensure the checkout UI renders correctly. Without the styles, the checkout component will not display properly.

### TypeScript Support

For TypeScript users, we export type definitions to enhance your development experience with proper type checking and autocompletion:

```typescript
// Import the main class and TypeScript types
import { OdusCheckout, CheckoutConfig, CheckoutInstance, Locale } from '@odus/checkout';

// Now you can use these types in your code
const config: CheckoutConfig = {
  apiKey: 'your_api_key',
  paymentId: 'your_payment_id',
  checkoutKey: 'your_unique_checkout_key',
  returnUrl: 'https://your-website.com/payment-complete',
  environment: 'test',
  locale: 'en', // Type-safe locale values
};

// The checkout instance is properly typed
const checkout: CheckoutInstance = new OdusCheckout(config);
```

## Getting Started

### Basic Implementation

Here's a simple example of how to implement the Odus Checkout in your application:

```javascript
import { OdusCheckout } from '@odus/checkout';
// Import the required styles
import '@odus/checkout/styles';

// Initialize the checkout
const checkout = new OdusCheckout({
  apiKey: 'your_api_key',
  paymentId: 'your_payment_id',
  checkoutKey: 'your_unique_checkout_key',
  returnUrl: 'https://your-website.com/payment-complete',
  environment: 'test', // 'test' for sandbox or 'live' for production

  callbacks: {
    onPaymentSucceeded: (result) => {
      console.log('Payment successful!', result);
      // Handle successful payment (e.g., show confirmation page)
    },
    onPaymentFailed: (result) => {
      console.log('Payment failed!', result);
      // Handle failed payment
    },
    onActionRequired: (redirectUrl) => {
      console.log('3DS authentication required!', redirectUrl);
      // Custom redirect handling (only called when manualActionHandling is true)
    },
    onLoadingStateChange: (isLoading) => {
      console.log('Loading state changed:', isLoading);
      // Toggle loading indicators in your UI
    },
  },
  // Optional: Enable manual handling of 3DS redirects
  // manualActionHandling: true,
});

// Mount the checkout form to a container in your HTML
checkout.mount('#checkout-container');
```

Make sure you have a container element in your HTML:

```html
<div id="checkout-container"></div>
```

## Configuration Options

When initializing the Odus Checkout, you can configure various options:

| Option                 | Type    | Required | Description                                                                                                                                                                                 |
| ---------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`               | string  | ✅       | Your Odus API key obtained from the dashboard's API Keys page                                                                                                                               |
| `checkoutKey`          | string  | ✅       | Unique checkout key for this payment session                                                                                                                                                |
| `paymentId`            | string  | ✅       | The ID of the payment being processed                                                                                                                                                       |
| `environment`          | string  | ✅       | API environment to use - either 'test' or 'live'                                                                                                                                            |
| `returnUrl`            | string  | ✅       | The URL where the customer will be redirected after 3DS authentication or other redirect flows                                                                                              |
| `locale`               | Locale  |          | Language code for checkout localization. If not set, automatically defaults to the customer's browser language when supported. If browser language is not supported, falls back to English. |
| `disableErrorMessages` | boolean |          | Set to `true` to disable built-in error messages (defaults to `false`)                                                                                                                      |
| `manualActionHandling` | boolean |          | Set to `true` to manually handle 3DS redirects via the `onActionRequired` callback (defaults to `false`)                                                                                    |
| `callbacks`            | object  |          | Event callback functions (see [Callbacks](#callbacks-and-event-handling))                                                                                                                   |

## Payment Methods

The Odus Checkout automatically displays payment methods based on your account configuration and the checkout profile. The following payment methods are supported:

- Credit/Debit Cards (Visa, Mastercard, American Express, Discover, JCB, Diners)
- PayPal
- Additional methods based on your account configuration

## Callbacks and Event Handling

The Odus Checkout SDK provides callback functions to handle different payment scenarios:

### onPaymentSucceeded

Called when a payment is successfully authorized.

```javascript
onPaymentSucceeded: (result) => {
  // result is the payment status: 'authorized'
  console.log('Payment successful!', result);
  // Update UI, redirect to thank you page, etc.
};
```

### onPaymentFailed

Called when a payment fails.

```javascript
onPaymentFailed: (result) => {
  // result is the payment status: 'failed'
  console.log('Payment failed!', result);
  // Show error message, allow retry, etc.
};
```

### onActionRequired

Called when a payment requires additional action (such as 3DS authentication) and `manualActionHandling` is set to `true`.

```javascript
onActionRequired: (redirectUrl) => {
  // redirectUrl is the URL where the customer needs to be redirected for 3DS authentication
  console.log('Action required!', redirectUrl);
  // Handle the redirect manually, e.g., open in a modal, new window, or custom redirect
  window.location.href = redirectUrl;
};
```

### onLoadingStateChange

Called when the loading state of the checkout form changes. This is useful for showing or hiding custom loading indicators in your UI.

This callback is optional. If not provided, Odus will automatically render its default spinner during loading states.

```javascript
onLoadingStateChange: (isLoading) => {
  // isLoading is a boolean indicating whether the form is currently loading
  console.log('Loading state changed:', isLoading);

  // Example: Toggle a custom spinner in your UI
  const spinner = document.getElementById('my-spinner');
  if (isLoading) {
    spinner.style.display = 'block';
  } else {
    spinner.style.display = 'none';
  }
};
```

**Note:** Implementing this callback will override the default Odus loading indicator, giving you complete control over the loading experience.

## Localization Support

Odus provides localized payment experiences in 33 languages, helping you better serve your global customer base.

### How it works

- **Automatic Detection**: By default, Odus detects your customer's browser locale and displays the payment page in that language if supported.
- **Manual Override**: You can specify a particular language by passing the locale parameter when creating a Checkout Session.

### Supported Languages

Odus currently supports localization for 33 languages, ensuring broad international coverage for your payment processing needs.

## Advanced Usage

### Programmatic Control

You can programmatically control the checkout form:

```javascript
// Mount the checkout to a container
checkout.mount('#checkout-container');

// Unmount the checkout (e.g., when navigating away)
checkout.unmount();
```

### Custom 3DS Redirect Handling

By default, Odus Checkout automatically redirects customers to the 3DS authentication page when required. However, you can take control of this process for a more customized experience:

```javascript
const checkout = new OdusCheckout({
  // ... other configuration options
  manualActionHandling: true,
  callbacks: {
    // ... other callbacks
    onActionRequired: (redirectUrl) => {
      // Example: Open 3DS in a modal or iframe instead of full-page redirect
      const modal = document.getElementById('auth-modal');
      const iframe = document.createElement('iframe');
      iframe.src = redirectUrl;
      modal.appendChild(iframe);
      modal.style.display = 'block';
    },
  },
});
```

This approach is useful for:

- Implementing a modal/popup for 3DS authentication
- Using an iframe instead of a full page redirect
- Adding custom tracking or analytics before redirecting
- Implementing custom UI transitions during the authentication flow

### Displaying Error Messages Programmatically

You can display custom error messages using the checkout's built-in Alert UI. This is particularly useful for showing errors that occur outside the normal payment flow, such as after a failed 3DS redirect:

```javascript
const checkout = new OdusCheckout({
  // ... configuration
});

checkout.mount('#checkout-container');

// Display a custom error message (bypasses disableErrorMessages flag)
checkout.displayError('Payment failed after 3DS authentication. Please try again.');

// Clear the error message when needed
checkout.clearError();
```

**Common use cases:**

- Displaying errors after returning from 3DS authentication
- Showing validation errors from your backend
- Communicating payment failures that occur outside the checkout flow

**Note:** The `displayError` method always displays the message, even when `disableErrorMessages: true` is set in the configuration, since it represents an explicit intent to show a message. Both methods require the checkout to be mounted first.

## API Reference

### OdusCheckout Class

```typescript
class OdusCheckout {
  constructor(config: CheckoutConfig);
  mount(containerId: string): this;
  unmount(): void;
  displayError(message: string): void;
  clearError(): void;
}
```

#### Methods

- **`mount(containerId: string)`** - Mounts the checkout form to the specified container element.
- **`unmount()`** - Unmounts and cleans up the checkout form.
- **`displayError(message: string)`** - Displays a custom error message using the checkout's built-in Alert UI. This method bypasses the `disableErrorMessages` configuration flag. Throws an error if called before `mount()`.
- **`clearError()`** - Removes the currently displayed error message. Throws an error if called before `mount()`.

### CheckoutConfig Type

```typescript
type CheckoutConfig = {
  apiKey: string;
  returnUrl: string;
  checkoutKey: string;
  paymentId: string;
  environment: 'test' | 'live';
  callbacks?: {
    onPaymentSucceeded?: (result: string) => void;
    onPaymentFailed?: (result: string) => void;
    onActionRequired?: (redirectUrl: string) => void;
    onLoadingStateChange?: (isLoading: boolean) => void;
  };
  locale?: Locale;
  disableErrorMessages?: boolean;
  manualActionHandling?: boolean;
};

// Where Locale is a type representing supported languages
type Locale = 'en' | 'de' | 'es' | 'fr' | 'pl' | 'pt' | 'it' | 'tr';
```

### CheckoutInstance Type

```typescript
// This represents the checkout instance returned when you create a new OdusCheckout
interface CheckoutInstance {
  mount(containerId: string): this;
  unmount(): void;
  displayError(message: string): void;
  clearError(): void;
}
```

## Troubleshooting

### Common Issues

#### Checkout not appearing

- Ensure the container element exists before calling `mount()`
- Check that styles are imported with `import '@odus/checkout/styles'` when using npm/module approach
- Check browser console for errors
- Verify your API key and profile ID are correct
- Confirm that you're using the correct environment ('test' or 'live')

#### 3DS Authentication Issues

- Ensure your `returnUrl` is properly configured
- Verify your domain is whitelisted in your Odus account settings
- If using `manualActionHandling: true`, make sure the `onActionRequired` callback is properly implemented

#### Manual 3DS Handling Not Working

- Check that both `manualActionHandling: true` is set and `onActionRequired` callback is provided
- Ensure the callback correctly handles the redirectUrl parameter
- Verify that any custom redirect implementation maintains all URL parameters

## Related Guides

For a complete understanding of how to integrate the Checkout SDK in your application, please refer to these additional guides:

- [Payment Flow Overview](./flow-overview) - Understand the different payment flows and how they work
- [Handling Redirects](./handling-redirects) - Learn how to handle redirects for 3DS authentication and alternative payment methods
- [Making Payments](./making-payments) - Step-by-step guide on how to process payments
