# Discount coupons
Source: https://docs.lomi.africa/build/billing/discount-coupons

Create, validate, stack, and track coupon discounts with the same rules used in checkout.

***

title: Discount coupons
description: Create, validate, stack, and track coupon discounts with the same rules used in checkout.
------------------------------------------------------------------------------------------------------

import { Tabs, Tab } from 'fumadocs-ui/components/tabs';

The Discount coupons API supports strict server-side validation and usage tracking for checkout flows.

This page describes coupon validation and application rules used by checkout and the API, including:

* creation-time validation
* checkout-time validation (customer, scope, quantity, frequency)
* single and multi-coupon application
* deduped coupon usage reservation and transaction linking

## How coupon logic works (end-to-end)

At a high level, coupon handling follows this flow:

1. Create a coupon via **`POST /coupons`** with your constraints.
2. Validate at checkout (server-side rules for customer, scope, quantity, and frequency).
3. Compute and apply the discount on the checkout session, including stacked coupons when allowed.
4. Reserve usage against the checkout session until payment completes.
5. Link the reservation to the final transaction when payment succeeds.
6. Increment usage counters when the transaction reaches **`completed`**.

This keeps coupon behavior deterministic between dashboard preview, hosted checkout, and API integrations.

## Create a discount coupon

### Request Body

| Field                   | Type      | Required      | Description                                                 |
| ----------------------- | --------- | ------------- | ----------------------------------------------------------- |
| `code`                  | `string`  | **Yes**       | Unique coupon code (auto-uppercased)                        |
| `discount_type`         | `string`  | No            | `percentage` or `fixed` (default: `percentage`)             |
| `discount_percentage`   | `number`  | If percentage | Discount percentage (`> 0` and `<= 100`)                    |
| `discount_fixed_amount` | `number`  | If fixed      | Fixed discount amount                                       |
| `description`           | `string`  | No            | Coupon description                                          |
| `is_active`             | `boolean` | No            | Active status (default: `true`)                             |
| `max_uses`              | `number`  | No            | Maximum total uses                                          |
| `max_quantity_per_use`  | `number`  | No            | Max quantity per use                                        |
| `valid_from`            | `string`  | No            | Start date (ISO 8601)                                       |
| `expires_at`            | `string`  | No            | Expiration date (ISO 8601)                                  |
| `customer_type`         | `string`  | No            | `all`, `new`, `returning`                                   |
| `usage_frequency_limit` | `string`  | No            | `total`, `per_customer`, `per_day`, `per_week`, `per_month` |
| `usage_limit_value`     | `number`  | Conditionally | Required if `usage_frequency_limit != total`                |
| `scope_type`            | `string`  | No            | `organization_wide`, `specific_products`, `specific_prices` |
| `product_ids`           | `array`   | No            | Product IDs (if scope is specific)                          |

### Creation-time validation rules

The API enforces these rules at creation:

* coupon code is unique per organization
* percentage and fixed discounts are mutually exclusive
* `valid_from < expires_at` when both exist
* `usage_limit_value` is required for non-`total` frequency modes
* for `specific_products` / `specific_prices`, linked products must belong to the same organization

<Tabs items={["TypeScript", "Python", "cURL"]}>
  <Tab value="TypeScript">
    ```typescript
    import { LomiSDK } from '@lomi./sdk';

    const lomi = new LomiSDK({
      apiKey: process.env.LOMI_SECRET_KEY!,
      environment: 'live',
    });

    // Percentage discount
    const coupon = await lomi.coupons.create({
      code: 'SAVE20',
      discount_type: 'percentage',
      discount_percentage: 20,
      description: '20% off all products',
      max_uses: 100,
      expires_at: '2024-12-31T23:59:59Z',
    });

    // Fixed amount discount
    const fixedCoupon = await lomi.coupons.create({
      code: 'FLAT5000',
      discount_type: 'fixed',
      discount_fixed_amount: 5000,
      description: '5000 XOF off',
      customer_type: 'new',
    });

    console.log(`Coupon created: ${coupon.code}`);
    ```
  </Tab>

  <Tab value="Python">
    ```python
    from lomi import LomiClient
    import os

    client = LomiClient(
        api_key=os.environ["LOMI_SECRET_KEY"],
        environment="test"
    )

    coupon = client.discount_coupons.create({
        "code": "SAVE20",
        "discount_type": "percentage",
        "discount_percentage": 20,
        "description": "20% off all products",
        "max_uses": 100,
        "expires_at": "2024-12-31T23:59:59Z"
    })

    print(f"Coupon created: {coupon['code']}")
    ```
  </Tab>

  <Tab value="cURL">
    ```bash
    curl -X POST "https://api.lomi.africa/coupons" \
      -H "X-API-KEY: $LOMI_SECRET_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "code": "SAVE20",
        "discount_type": "percentage",
        "discount_percentage": 20,
        "description": "20% off all products",
        "max_uses": 100,
        "expires_at": "2024-12-31T23:59:59Z"
      }'
    ```
  </Tab>
</Tabs>

***

## Checkout validation behavior

Checkout validation combines structural and business checks. A coupon must pass all checks below:

1. **Exists and active** in the same organization.
2. **Time window**: `valid_from` has started and `expires_at` has not passed.
3. **Global cap**: `current_uses < max_uses` (if `max_uses` set).
4. **Frequency cap** for the customer (when enabled): per customer/day/week/month.
5. **Quantity cap**: checkout quantity must not exceed `max_quantity_per_use`.
6. **Customer-type eligibility**:
   * `new`: customer must have no completed payment/installment transactions in org
   * `returning`: customer must have at least one completed payment/installment transaction
   * `all`: no customer-history restriction
7. **Scope check**:
   * `organization_wide`: valid for all products
   * `specific_products` / `specific_prices`: product must be linked in `coupon_product_links`

If any check fails, the API returns a specific reason message.

## Discount calculation behavior

`calculate_coupon_discount` computes discount on the base amount excluding optional fees:

* `base_price = p_base_amount - p_fees_amount`
* percentage coupon: `discount = base_price * percentage`
* fixed coupon: `discount = fixed_amount`
* discount is multiplied by quantity when applicable
* discount is clamped so it cannot exceed the eligible base price
* final amount is recomputed as `(base_price - discount) + fees`

This protects against negative totals and over-discounting.

## Multi-coupon stacking (sequential)

For multi-coupon flows, coupons are applied in order using a running amount:

* coupon A applies to original current amount
* coupon B applies to the reduced amount after A
* and so on

This is **sequential stacking**, not parallel summing.\
The response includes a breakdown per coupon with:

* original amount before this coupon
* discount amount for this coupon
* final amount after this coupon

If any coupon in the array fails validation, the whole multi-coupon calculation fails.

## Usage tracking and deduplication

Coupon usage is recorded in `coupon_usage` with safeguards to prevent duplicate pending reservations:

* a pending reservation is unique per `(coupon_id, checkout_session_id)` while `transaction_id IS NULL`
* stale duplicates are cleaned before enforcing the partial unique index
* when payment completes, reservation is linked to transaction (instead of inserting duplicates)
* if no reservation exists, a new transaction-linked record is inserted

This is the expected behavior for provider retries and webhook races.

## List discount coupons

Retrieve all discount coupons for your organization.

<Tabs items={["TypeScript", "Python", "cURL"]}>
  <Tab value="TypeScript">
    ```typescript
    const coupons = await lomi.coupons.list();
    ```
  </Tab>

  <Tab value="Python">
    ```python
    coupons = client.discount_coupons.list()
    ```
  </Tab>

  <Tab value="cURL">
    ```bash
    curl -X GET "https://api.lomi.africa/coupons" \
      -H "X-API-KEY: $LOMI_SECRET_KEY"
    ```
  </Tab>
</Tabs>

***

## Get a discount coupon

Retrieve details of a specific coupon.

<Tabs items={["TypeScript", "Python", "cURL"]}>
  <Tab value="TypeScript">
    ```typescript
    const coupon = await lomi.coupons.get('dc_abc123...');
    ```
  </Tab>

  <Tab value="Python">
    ```python
    coupon = client.discount_coupons.get('dc_abc123...')
    ```
  </Tab>

  <Tab value="cURL">
    ```bash
    curl -X GET "https://api.lomi.africa/coupons/dc_abc123..." \
      -H "X-API-KEY: $LOMI_SECRET_KEY"
    ```
  </Tab>
</Tabs>

***

## Get coupon performance

Retrieve usage statistics and revenue impact for a coupon (`completed` transactions only).

<Tabs items={["TypeScript", "Python", "cURL"]}>
  <Tab value="TypeScript">
    ```typescript
    const performance = await lomi.coupons.getPerformance('dc_abc123...');

    console.log(`Total uses: ${performance.total_uses}`);
    console.log(`Total discounted: ${performance.total_discount_amount}`);
    console.log(`Revenue generated: ${performance.total_revenue}`);
    console.log(`Avg order value: ${performance.average_order_value}`);
    ```
  </Tab>

  <Tab value="Python">
    ```python
    performance = client.discount_coupons.get_performance('dc_abc123...')
    print(f"Total uses: {performance['total_uses']}")
    ```
  </Tab>

  <Tab value="cURL">
    ```bash
    curl -X GET "https://api.lomi.africa/coupons/dc_abc123.../performance" \
      -H "X-API-KEY: $LOMI_SECRET_KEY"
    ```
  </Tab>
</Tabs>

### Response

```json
{
  "total_uses": 45,
  "total_discounts": 25000,
  "total_revenue": 150000,
  "average_discount": 555.56,
  "unique_customers": 38
}
```

***

## Discount Coupon Object

| Field                          | Type      | Description                                                 |
| ------------------------------ | --------- | ----------------------------------------------------------- |
| `id`                           | `string`  | Unique identifier                                           |
| `code`                         | `string`  | Coupon code                                                 |
| `discount_type`                | `string`  | `percentage` or `fixed`                                     |
| `discount_percentage`          | `number`  | Percentage value                                            |
| `discount_fixed_amount`        | `number`  | Fixed amount value                                          |
| `customer_type`                | `string`  | `all`, `new`, `returning`                                   |
| `usage_frequency_limit`        | `string`  | `total`, `per_customer`, `per_day`, `per_week`, `per_month` |
| `usage_limit_value`            | `number`  | Frequency limit count where applicable                      |
| `is_active`                    | `boolean` | Active status                                               |
| `max_uses`                     | `number`  | Maximum uses                                                |
| `current_uses`                 | `number`  | Current use count                                           |
| `max_quantity_per_use`         | `number`  | Max quantity allowed per redemption                         |
| `valid_from`                   | `string`  | Start date                                                  |
| `expires_at`                   | `string`  | Expiration date                                             |
| `scope_type`                   | `string`  | Application scope                                           |
| `product_links`                | `array`   | Linked products where scope is specific                     |
| `completed_redemptions`        | `number`  | Completed redemptions count                                 |
| `distinct_customers_completed` | `number`  | Distinct customers with completed redemptions               |
| `created_at`                   | `string`  | Creation timestamp                                          |

***

## Common implementation patterns

### Validate before applying

For a clean UX:

1. validate coupon first (frontend validation endpoint),
2. show discount preview,
3. apply coupon during checkout creation/confirmation.

### Handle retries safely

Payment providers may retry callbacks. The coupon reservation/linking logic is designed to be idempotent around checkout session + coupon pairs.

### Prefer customer context when possible

For `new` and `returning` restricted coupons, send `customer_id` so eligibility can be evaluated correctly.

***

## Error Responses

| Status | Description                     |
| ------ | ------------------------------- |
| `400`  | Invalid input or duplicate code |
| `401`  | Invalid or missing API key      |
| `404`  | Coupon not found                |

## Worked examples

### New-customer-only coupon

Coupon configuration:

* `customer_type = new`
* `scope_type = organization_wide`
* `discount_type = percentage`
* `discount_percentage = 20`

Behavior:

* Customer with no completed payment/installment transactions in the organization: coupon is valid.
* Customer with at least one completed payment/installment transaction: coupon is rejected as not eligible.
* If customer context is missing, eligibility checks for restricted customer types may fail.

### Returning-customer-only coupon

Coupon configuration:

* `customer_type = returning`
* `usage_frequency_limit = per_month`
* `usage_limit_value = 1`

Behavior:

* Returning customer can redeem once per month.
* Second redemption in the same month is rejected.
* Redemptions in a new month are allowed again (subject to other limits).

### Product-scoped coupon

Coupon configuration:

* `scope_type = specific_products`
* `product_ids = [Product A, Product B]`

Behavior:

* Checkout for Product A or B: can pass scope checks.
* Checkout for Product C: rejected (`coupon is not applicable to this product`).
* Organization-wide coupons skip product-link checks.

### Quantity-capped coupon

Coupon configuration:

* `max_quantity_per_use = 2`

Behavior:

* Quantity `1` or `2`: valid.
* Quantity `3+`: rejected with a quantity-limit message.

### Fixed discount clamped to base amount

Checkout:

* Base amount: `3,000`
* Fees amount: `500`
* Eligible base price: `2,500`

Coupon:

* `discount_type = fixed`
* `discount_fixed_amount = 5,000`

Result:

* Discount is clamped to `2,500` (cannot exceed eligible base).
* Final amount is `(2,500 - 2,500) + 500 = 500`.

### Sequential stacking (two coupons)

Checkout amount: `10,000`

Coupons in order:

1. `SAVE20` (20%)
2. `FLAT1000` (fixed 1,000)

Sequential calculation:

* After `SAVE20`: discount `2,000`, running amount `8,000`
* After `FLAT1000`: discount `1,000`, running amount `7,000`
* Total discount: `3,000`

Important: second coupon is applied to the reduced running amount, not the original amount.

### Pending reservation and transaction linking

Flow:

1. Coupon is applied to checkout session.
2. A pending `coupon_usage` reservation is recorded for `(coupon_id, checkout_session_id)`.
3. Payment provider callback creates/finalizes transaction.
4. Reservation is linked to the transaction.

Why this matters:

* Prevents duplicate coupon usage rows during retries/webhook races.
* Keeps reporting accurate when providers retry callbacks.

### Safe retry behavior

If the same provider event is retried:

* existing pending reservation is updated/linked when possible,
* duplicate inserts are prevented by uniqueness and conflict handling,
* usage counting remains consistent when transaction completion logic runs.

### Stacking order changes the total discount

Same two coupons as sequential stacking, but reverse the order:

1. `FLAT1000` first: discount `1,000`, running amount `9,000`
2. `SAVE20` second: 20% of `9,000` = `1,800`, running amount `7,200`
3. **Total discount: `2,800`** (not `3,000`)

Always show the applied order in UI and persist the same order server-side.

### Usage frequency: sliding window vs calendar

Depending on which validation path runs, usage limits may be evaluated differently:

* One path counts coupon usage rows in a **sliding** window (for example last 24 hours for `per_day`).
* Another path ties `per_day` / `per_week` / `per_month` to **calendar** boundaries.

For a coupon limited to **one use per day**, a customer who redeems at 23:59 may or may not redeem again at 00:01 the next day, depending on which helper your checkout stack calls. **Treat limits as “at most N redemptions in the configured period”** and test in sandbox.

### Re-applying a coupon on the same checkout session

When a coupon is applied to a session that already has a pending `coupon_usage` row, the system may **upsert** that row (update discount and timestamps) instead of inserting duplicates, as long as the transaction is not finalized yet.

Implications:

* Changing the coupon code or recomputing the cart should **replace** the pending reservation, not stack duplicate rows.
* After **payment completes**, usage is keyed off the transaction; do not rely on session-only rows for accounting.

### Free or fully discounted checkouts

When the discount brings the payable amount to **zero** (for example 100% off campaigns), the platform may record a **free** completion path using dedicated provider/method codes so ledger and webhooks remain consistent.

Merchant-facing reporting should still show **list price**, **discount**, and **net**.

### Client-side retries

Your app retries `POST /checkout-sessions` or `apply coupon` due to a flaky network:

* Use the **same idempotency key** or session id so you do not create parallel sessions.
* On the server, duplicate completion webhooks should not double-increment usage if transaction completion is idempotent, still avoid duplicate **client-initiated** applies when possible.

### Integration notes

* Always validate before final apply.
* Send customer context when using `new`/`returning` restricted coupons.
* Keep coupon application idempotent in your own client retries.
* For multi-coupon UX, preserve intended coupon order.
* Document for your team whether **percentage or fixed** coupons should be applied first (product decision, affects totals).
