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

# Create a Checkout Session

> Create a payment session to redirect your customers to the Yabetoo hosted payment page

## What is a Checkout Session?

A **Checkout Session** represents your customer's payment session. It controls what the customer sees on the payment page: products, amount, currency, and available options.

<Info>
  **Identifier format**: `cs_` followed by 24 alphanumeric characters.

  Example: `cs_abc123def456ghi789jkl012`
</Info>

## Session Modes

<CardGroup cols={3}>
  <Card title="payment" icon="credit-card">
    **One-time payment**

    For one-time purchases of products or services.
  </Card>

  <Card title="subscription" icon="repeat">
    **Subscription**

    To create a recurring subscription with automatic billing.
  </Card>

  <Card title="setup" icon="gear">
    **Setup**

    To save a payment method without making an immediate payment.
  </Card>
</CardGroup>

## Create a Checkout Session

### Basic Request

```bash theme={null}
curl -X POST https://api.yabetoo.com/v1/checkout/sessions \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "success_url": "https://your-site.com/success",
    "cancel_url": "https://your-site.com/cancel",
    "line_items": [
      {
        "price_data": {
          "currency": "XOF",
          "unit_amount": 15000,
          "product_data": {
            "name": "Premium T-shirt"
          }
        },
        "quantity": 2
      }
    ]
  }'
```

### Required Parameters

| Parameter     | Type   | Description                           |
| ------------- | ------ | ------------------------------------- |
| `success_url` | string | Redirect URL after successful payment |
| `line_items`  | array  | List of items to purchase             |

### Optional Parameters

| Parameter               | Type    | Description                                                |
| ----------------------- | ------- | ---------------------------------------------------------- |
| `cancel_url`            | string  | Redirect URL if customer cancels                           |
| `mode`                  | string  | `payment`, `subscription`, or `setup` (default: `payment`) |
| `customer`              | string  | ID of an existing customer (`cus_xxx`)                     |
| `customer_email`        | string  | Customer email (pre-fills the form)                        |
| `client_reference_id`   | string  | Your internal reference (e.g., order ID)                   |
| `allow_promotion_codes` | boolean | Allow promo codes                                          |
| `locale`                | string  | Page language (`fr`, `en`, etc.)                           |
| `expires_at`            | number  | Unix timestamp for expiration                              |
| `metadata`              | object  | Custom data                                                |

## Define Items (line\_items)

You have two options for defining items:

<Tabs>
  <Tab title="Inline price (price_data)">
    Define the price directly in the request:

    ```json theme={null}
    {
      "line_items": [
        {
          "price_data": {
            "currency": "XOF",
            "unit_amount": 25000,
            "product_data": {
              "name": "JavaScript Training",
              "description": "Full access to the course",
              "images": ["https://example.com/image.jpg"]
            }
          },
          "quantity": 1
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Existing price (price)">
    Reference a price created in your catalog:

    ```json theme={null}
    {
      "line_items": [
        {
          "price": "price_abc123def456",
          "quantity": 1
        }
      ]
    }
    ```

    <Tip>
      Use pre-created prices for centralized catalog management.
    </Tip>
  </Tab>
</Tabs>

### Line Item Structure

| Field                 | Type   | Description                           |
| --------------------- | ------ | ------------------------------------- |
| `price_data`          | object | Inline defined price (see below)      |
| `price`               | string | ID of an existing price (`price_xxx`) |
| `quantity`            | number | Quantity (minimum 1)                  |
| `adjustable_quantity` | object | Allows customer to modify quantity    |

### Price Data Structure

| Field          | Type   | Description                         |
| -------------- | ------ | ----------------------------------- |
| `currency`     | string | Currency code (`XOF`, `EUR`, `USD`) |
| `unit_amount`  | number | Unit price                          |
| `product_data` | object | Product information                 |
| `recurring`    | object | For subscriptions only              |

### Product Data Structure

| Field         | Type   | Description             |
| ------------- | ------ | ----------------------- |
| `name`        | string | Product name (required) |
| `description` | string | Description             |
| `images`      | array  | Image URLs              |
| `metadata`    | object | Custom data             |

## Recurring Subscriptions

To create a subscription, use `mode: "subscription"` and add `recurring` in `price_data`:

```json theme={null}
{
  "mode": "subscription",
  "success_url": "https://your-site.com/success",
  "line_items": [
    {
      "price_data": {
        "currency": "XOF",
        "unit_amount": 9900,
        "product_data": {
          "name": "Pro Subscription"
        },
        "recurring": {
          "interval": "month",
          "interval_count": 1
        }
      },
      "quantity": 1
    }
  ]
}
```

### Available Intervals

| Interval | Description     |
| -------- | --------------- |
| `day`    | Daily billing   |
| `week`   | Weekly billing  |
| `month`  | Monthly billing |
| `year`   | Annual billing  |

## Advanced Options

### Collect Addresses

```json theme={null}
{
  "billing_address_collection": "required",
  "shipping_address_collection": {
    "allowed_countries": ["CG", "CD", "CI", "SN"]
  }
}
```

### Collect Phone Number

```json theme={null}
{
  "phone_number_collection": {
    "enabled": true
  }
}
```

### Allow Promo Codes

```json theme={null}
{
  "allow_promotion_codes": true
}
```

### Apply a Promo Code Automatically

```json theme={null}
{
  "discounts": [
    {
      "promotion_code": "promo_abc123"
    }
  ]
}
```

### Customize the Payment Button

```json theme={null}
{
  "submit_type": "pay"
}
```

| Value    | Button Text                |
| -------- | -------------------------- |
| `auto`   | Automatic based on context |
| `pay`    | "Pay"                      |
| `book`   | "Book"                     |
| `donate` | "Donate"                   |

### Adjustable Quantity

Allow the customer to modify quantity on the payment page:

```json theme={null}
{
  "line_items": [
    {
      "price_data": {
        "currency": "XOF",
        "unit_amount": 5000,
        "product_data": { "name": "Item" }
      },
      "quantity": 1,
      "adjustable_quantity": {
        "enabled": true,
        "minimum": 1,
        "maximum": 10
      }
    }
  ]
}
```

## Complete Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.yabetoo.com/v1/checkout/sessions \
    -H "Authorization: Bearer sk_live_..." \
    -H "Content-Type: application/json" \
    -d '{
      "mode": "payment",
      "success_url": "https://your-site.com/success?session_id={CHECKOUT_SESSION_ID}",
      "cancel_url": "https://your-site.com/cancel",
      "customer_email": "customer@example.com",
      "client_reference_id": "order_12345",
      "allow_promotion_codes": true,
      "billing_address_collection": "required",
      "phone_number_collection": { "enabled": true },
      "locale": "en",
      "metadata": {
        "order_id": "12345",
        "source": "website"
      },
      "line_items": [
        {
          "price_data": {
            "currency": "XOF",
            "unit_amount": 25000,
            "product_data": {
              "name": "HD Screen",
              "description": "24 inch Full HD screen",
              "images": ["https://example.com/screen.jpg"]
            }
          },
          "quantity": 1
        },
        {
          "price_data": {
            "currency": "XOF",
            "unit_amount": 5000,
            "product_data": {
              "name": "HDMI Cable"
            }
          },
          "quantity": 2
        }
      ]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.yabetoo.com/v1/checkout/sessions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer sk_live_...",
    },
    body: JSON.stringify({
      mode: "payment",
      success_url: "https://your-site.com/success?session_id={CHECKOUT_SESSION_ID}",
      cancel_url: "https://your-site.com/cancel",
      customer_email: "customer@example.com",
      allow_promotion_codes: true,
      line_items: [
        {
          price_data: {
            currency: "XOF",
            unit_amount: 25000,
            product_data: {
              name: "HD Screen",
            },
          },
          quantity: 1,
        },
      ],
    }),
  });

  const session = await response.json();
  // Redirect to session.url
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.yabetoo.com/v1/checkout/sessions",
      headers={
          "Authorization": "Bearer sk_live_...",
          "Content-Type": "application/json"
      },
      json={
          "mode": "payment",
          "success_url": "https://your-site.com/success",
          "cancel_url": "https://your-site.com/cancel",
          "line_items": [
              {
                  "price_data": {
                      "currency": "XOF",
                      "unit_amount": 25000,
                      "product_data": {
                          "name": "HD Screen"
                      }
                  },
                  "quantity": 1
              }
          ]
      }
  )

  session = response.json()
  ```

  ```php PHP theme={null}
  $curl = curl_init();

  curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.yabetoo.com/v1/checkout/sessions",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => [
          "Authorization: Bearer sk_live_...",
          "Content-Type: application/json"
      ],
      CURLOPT_POSTFIELDS => json_encode([
          "mode" => "payment",
          "success_url" => "https://your-site.com/success",
          "cancel_url" => "https://your-site.com/cancel",
          "line_items" => [
              [
                  "price_data" => [
                      "currency" => "XOF",
                      "unit_amount" => 25000,
                      "product_data" => [
                          "name" => "HD Screen"
                      ]
                  ],
                  "quantity" => 1
              ]
          ]
      ])
  ]);

  $response = curl_exec($curl);
  $session = json_decode($response, true);
  ```
</CodeGroup>

## Response

```json theme={null}
{
  "id": "cs_abc123def456ghi789",
  "object": "checkout.session",
  "mode": "payment",
  "status": "open",
  "payment_status": "unpaid",
  "url": "https://checkout.yabetoo.com/cs_abc123def456ghi789",
  "success_url": "https://your-site.com/success?session_id={CHECKOUT_SESSION_ID}",
  "cancel_url": "https://your-site.com/cancel",
  "customer_email": "customer@example.com",
  "client_reference_id": "order_12345",
  "amount_subtotal": 35000,
  "amount_total": 35000,
  "amount_discount": 0,
  "currency": "XOF",
  "allow_promotion_codes": true,
  "line_items": [
    {
      "price_data": {
        "currency": "XOF",
        "unit_amount": 25000,
        "product_data": { "name": "HD Screen" }
      },
      "quantity": 1,
      "amount_subtotal": 25000,
      "amount_total": 25000
    },
    {
      "price_data": {
        "currency": "XOF",
        "unit_amount": 5000,
        "product_data": { "name": "HDMI Cable" }
      },
      "quantity": 2,
      "amount_subtotal": 10000,
      "amount_total": 10000
    }
  ],
  "metadata": {
    "order_id": "12345",
    "source": "website"
  },
  "expires_at": "2024-01-15T12:00:00.000Z",
  "created_at": "2024-01-15T11:00:00.000Z"
}
```

### Response Fields

| Field             | Description                                |
| ----------------- | ------------------------------------------ |
| `id`              | Unique session identifier                  |
| `url`             | Payment page URL                           |
| `status`          | `open`, `complete`, or `expired`           |
| `payment_status`  | `unpaid`, `paid`, or `no_payment_required` |
| `amount_subtotal` | Subtotal before discounts                  |
| `amount_total`    | Total amount to pay                        |
| `amount_discount` | Applied discounts amount                   |

## Redirect the Customer

Once the session is created, redirect the customer to the payment URL:

```javascript theme={null}
// Server-side: create the session
const session = await createCheckoutSession(/* ... */);

// Client-side: redirect
window.location.href = session.url;
```

## After Payment

### Redirection

After payment, the customer is redirected to `success_url` with the session ID:

```
https://your-site.com/success?session_id=cs_abc123def456
```

### Verify Status

<Warning>
  Never trust the redirect alone. Always verify the session status server-side.
</Warning>

```javascript theme={null}
// Get session ID from URL
const sessionId = new URLSearchParams(window.location.search).get("session_id");

// Verify status server-side
const response = await fetch(
  "https://api.yabetoo.com/v1/checkout/sessions/" + sessionId,
  {
    headers: {
      Authorization: "Bearer sk_live_...",
    },
  }
);

const session = await response.json();

if (session.status === "complete" && session.payment_status === "paid") {
  // Payment confirmed - process the order
}
```

### Webhooks

For a robust integration, use webhooks to receive payment notifications:

```json theme={null}
{
  "type": "checkout.session.completed",
  "data": {
    "object": {
      "id": "cs_abc123def456",
      "status": "complete",
      "payment_status": "paid",
      "amount_total": 35000,
      "currency": "XOF"
    }
  }
}
```

See [Webhooks Documentation](/en/developer-tools/webhook/overview) for more details.

## Session Statuses

| Status     | Description                                |
| ---------- | ------------------------------------------ |
| `open`     | Active session, awaiting payment           |
| `complete` | Payment successful                         |
| `expired`  | Session expired (not paid within deadline) |

## Best Practices

<AccordionGroup>
  <Accordion title="Security">
    * Always create sessions server-side
    * Never store API keys client-side
    * Verify status via API or webhooks
  </Accordion>

  <Accordion title="User Experience">
    * Pre-fill email if you have it
    * Use `client_reference_id` to link to your order
    * Customize `submit_type` based on context
  </Accordion>

  <Accordion title="Error Handling">
    * Handle the case where customer cancels
    * Plan for session expiration
    * Use webhooks for edge cases
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Webhooks" icon="bell" href="/en/developer-tools/webhook/overview">
    Receive real-time notifications
  </Card>

  <Card title="Promo Codes" icon="percent" href="/en/products/coupons">
    Apply discounts to your sessions
  </Card>
</CardGroup>
