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

# Subscriptions

Ecart Pay’s Subscriptions API allows you to create and manage recurring payments for your users.

Ecart Pay's Subscriptions API allows you to create and manage recurring payments for your users. Whether you're billing daily, weekly, monthly, quarterly, semiannually, or yearly, our flexible system supports direct subscriptions, reusable [subscription templates](https://docs.ecartpay.com/docs/subscription-templates#/), pro-rata billing, trial periods, and automatic payment processing.

## Overview

You can create a subscription for a user in three ways:

* **Using a Subscription Template**: Ideal when you need to apply the same subscription logic to multiple customers (e.g., gym memberships, SaaS plans).
* **Creating a Direct Subscription**: When you want to create a unique subscription for a specific user without saving the configuration for reuse.
* **Creating Subscriptions with Advanced Features**: Including pro-rata billing, specific billing cycles, trial periods, end dates for temporary subscriptions, and [Merchant Managed Subscriptions](https://docs.ecartpay.com/update/docs/merchant-management-for-subscriptions#/).

## Key Features

<Cards columns={3}>
  <SimpleFeatureCard title="Multiple Billing Intervals" icon="fa-calendar-alt">
    Daily, weekly, monthly, quarterly, semiannual, and yearly
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Pro-rata Billing" icon="fa-sliders-h">
    Proportional charges based on specific billing cycle dates
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Trial Periods" icon="fa-hourglass-start">
    Free trial days before the first charge
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Automatic Payment Processing" icon="fa-credit-card">
    Smart payment logic when customers add payment methods
  </SimpleFeatureCard>

  <SimpleFeatureCard title="End Date Support" icon="fa-calendar-times">
    Temporary subscriptions with automatic termination
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Customer Dashboard" icon="fa-user-cog">
    Secure portal for customers to manage their subscriptions
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Notification System" icon="fa-envelope">
    Automatic email notification throughout the subscription lifecycle
  </SimpleFeatureCard>

  <SimpleFeatureCard title="Commitments" icon="fa-handshake">
    A commitment feature to set an specific number of periods a subscription will be active. Only a Merchant can cancel a subscription with commitment. Periods can be set as `daily`, `weekly`, `monthly`, `quarterly`, `semiannual`, or `yearly`.
  </SimpleFeatureCard>
</Cards>

<br />

<br />

> ⚠️ WARNING
>
> To follow the steps below, it is essential to have the corresponding Authorization Token. For more information, please refer to the following documentation page: [Authorization Token](https://docs.ecartpay.com/docs/authorization-token#/)

***

## Create a Direct Subscription

Create a subscription directly **without saving a reusable template**. This supports all advanced features including pro-rata billing, specific billing cycles, trial periods, and end dates.

<Callout icon="💻" theme="default">
  ### Visit our API Reference to [test this endpoint](https://docs.ecartpay.com/reference/create-subscription#/).
</Callout>

### Endpoint

* `POST https://ecartpay.com/api/subscriptions`
* `POST https://sandbox.ecartpay.com/api/subscriptions`

### Request Body

<Table align={["left","left","left"]}>
  <thead>
    <tr>
      <th>
        Field
      </th>

      <th>
        Type
      </th>

      <th>
        Description
      </th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        `customer_id`
      </td>

      <td>
        string
      </td>

      <td>
        ID of the customer to subscribe
      </td>
    </tr>

    <tr>
      <td>
        `amount`
      </td>

      <td>
        number
      </td>

      <td>
        Amount to charge per interval (e.g., `299` = $299.00)
      </td>
    </tr>

    <tr>
      <td>
        `currency`
      </td>

      <td>
        string
      </td>

      <td>
        ISO 4217 currency code (`MXN` or `USD`)
      </td>
    </tr>

    <tr>
      <td>
        `interval`
      </td>

      <td>
        string
      </td>

      <td>
        Billing interval: `daily`, `weekly`, `monthly`, `quarterly`, `semiannual`, or `yearly`
      </td>
    </tr>

    <tr>
      <td>
        `frequency`
      </td>

      <td>
        number
      </td>

      <td>
        Frequency multiplier (default: 1)
      </td>
    </tr>

    <tr>
      <td>
        `service`
      </td>

      <td>
        string
      </td>

      <td>
        Name or label for the subscription service
      </td>
    </tr>

    <tr>
      <td>
        `trial_period_days`
      </td>

      <td>
        number
      </td>

      <td>
        (Optional) Number of days before the first charge
      </td>
    </tr>

    <tr>
      <td>
        `billing_cycle`
      </td>

      <td>
        object
      </td>

      <td>
        (Optional) Specific billing cycle for pro-rata billing
      </td>
    </tr>

    <tr>
      <td>
        `end_date`
      </td>

      <td>
        string
      </td>

      <td>
        (Optional) ISO date string for subscription termination
      </td>
    </tr>

    <tr>
      <td>
        `benefits`
      </td>

      <td>
        array
      </td>

      <td>
        (Optional) List of benefits included in the subscription
      </td>
    </tr>

    <tr>
      <td>
        `merchant_management`
      </td>

      <td>
        boolean
      </td>

      <td>
        (Optional) Enables [merchant-managed ](https://docs.ecartpay.com/docs/merchant-management-for-subscriptions#/) subscription when `true`.

        * Requires a `notify_URL`
      </td>
    </tr>

    <tr>
      <td>
        `mixed_management`
      </td>

      <td>
        boolean
      </td>

      <td>
        (Optional) Enables [mixed-managed ](https://docs.ecartpay.com/docs/merchant-management-for-subscriptions#/) subscription when `true`.

        * Requires a `notify_URL`
      </td>
    </tr>

    <tr>
      <td>
        `notify_url`
      </td>

      <td>
        string
      </td>

      <td>
        (Optional) Webhook URL for payment notifications.

        * This field is required if the `merchant_management` is set to `true`
      </td>
    </tr>

    <tr>
      <td>
        `commitment_periods`
      </td>

      <td>
        number
      </td>

      <td>
        (Optional) The number of months for commitment in a subscription. Minimum 1 if enabled. During this period, only the merchant can cancel the subscription.
      </td>
    </tr>

    <tr>
      <td>
        `commitment_end_date`
      </td>

      <td>
        date
      </td>

      <td>
        (Optional) The date for the commitment end. This date is automatically calculated by the `commitment_periods`.
      </td>
    </tr>
  </tbody>
</Table>

<br />

> 📘 Merchant-Managed Subscriptions
>
> For further details on these type of subscriptions, please visit [Merchant Management for Subscriptions](https://docs.ecartpay.com/update/docs/merchant-management-for-subscriptions#/)

### Examples

#### Request

```json Standard Subscription
{
    "customer_id": "6854346910775959c2173b48",
    "amount": 599,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "service": "Business Plan",
    "benefits": [
        "Advanced analytics dashboard",
        "Priority customer support",
        "Custom integrations",
        "Team collaboration tools"
    ]
}
```
```json Pro-rata with Billing Cycle
{
    "customer_id": "6854346910775959c2173b48",
    "amount": 1299,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "service": "Enterprise Plan",
    "billing_cycle": {
        "day": 15,
        "month": 1
    },
    "trial_period_days": 7,
    "end_date": "2025-12-31",
    "benefits": [
        "Unlimited everything",
        "Dedicated account manager",
        "White-label solution",
        "99.9% SLA guarantee"
    ]
}
```

#### Response

```json
{
    "account_id": "6851ef3dd0b39474707f960d",
    "customer_id": "6854346910775959c2173b48",
    "status": "active",
    "service": "Enterprise Plan",
    "amount": 1299,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "trial_period_days": 7,
    "billing_cycle": {
        "day": 15,
        "month": 1
    },
    "end_date": "2025-12-31",
    "attempts": 0,
    "benefits": [
        "Unlimited everything",
        "Dedicated account manager",
        "White-label solution",
        "99.9% SLA guarantee"
    ],
    "errors": [],
    "card_ids": [],
    "id": "687e87d3e0ceebb93d273da9",
    "created_at": "2025-01-21T18:32:51.952Z",
    "updated_at": "2025-01-21T18:32:51.952Z"
}
```

<br />

<br />

## Create a Subscription from a Subscription Template

Once a [subscription template](https://docs.ecartpay.com/docs/subscription-templates#/) is created, you can use the `template_ id` to subscribe users to it.

It is possible to override certain fields that are already pre-defined in a specific subscription table. For example, by including an `amount` in the request you can override that value from the original `amount` set in the subscription template.

<Callout icon="💻" theme="default">
  ### Visit our API Reference to [test this endpoint](https://docs.ecartpay.com/reference/create-subscription#/).
</Callout>

### Endpoint

* `POST https://ecartpay.com/api/subscriptions`
* `POST https://sandbox.ecartpay.com/api/subscriptions`

### Request Body

| Field         | Type   | Description                                                                                                                                  |
| ------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `template_id` | string | ID of the subscription template used                                                                                                         |
| `customer_id` | string | ID of the customer the subscription was created for                                                                                          |
| `card_ids`    | array  | (Optional) List of card IDs associated with the subscription                                                                                 |
| `amount`      | number | (Optional override) The price amount of the subscription. This will override any `amount` value defined in an existing Subscription Template |

### Example

#### Request Body

```json Request
{
  "customer_id": "68cdcbfed75e4961c7188672",
  "template_id": "692a23df6fc020f57f572486"
}
```
```json Request with card_ids
{
  "customer_id": "68cdcbfed75e4961c7188672",
  "template_id": "692a23df6fc020f57f572486",
  "card_ids": [
    "68dec27a4fc15f2238b3476c"
  ]
}
```
```json Request with amount override
{
  "customer_id": "68cdcbfed75e4961c7188672",
  "template_id": "692a23df6fc020f57f572486",
  "card_ids": [
    "68dec27a4fc15f2238b3476c"
  ],
  "amount": 999
}
```

#### Response

```json Response
{
    "account_id": "68a4c3150b28a9584305a2a6",
    "customer_id": "68cdcbfed75e4961c7188672",
    "card_ids": [],
    "status": "active",
    "service": "Super Premium Plan",
    "amount": 499,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "trial_period_days": 14,
    "merchant_management": false,
    "mixed_management": false,
    "attempts": 0,
    "benefits": [
        "Unlimited access to premium content",
        "24/7 priority support",
        "Exclusive 35% discounts",
        "Up to 6 additional users"
    ],
    "errors": [],
    "auto_renew_commitment": false,
    "id": "6930cbb3ffee47566ea1cf2f",
    "created_at": "2025-12-03T23:45:55.155Z",
    "updated_at": "2025-12-03T23:45:55.155Z"
}
```
```json Response with card_ids 
{
    "account_id": "68a4c3150b28a9584305a2a6",
    "customer_id": "68cdcbfed75e4961c7188672",
    "card_ids": [
        "68dec27a4fc15f2238b3476c"
    ],
    "status": "active",
    "service": "Super Premium Plan",
    "amount": 499,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "trial_period_days": 14,
    "merchant_management": false,
    "mixed_management": false,
    "attempts": 0,
    "benefits": [
        "Unlimited access to premium content",
        "24/7 priority support",
        "Exclusive 35% discounts",
        "Up to 6 additional users"
    ],
    "errors": [],
    "auto_renew_commitment": false,
    "id": "6930cc95ffee47566ea1cf41",
    "created_at": "2025-12-03T23:49:41.068Z",
    "updated_at": "2025-12-03T23:49:41.068Z"
}
```
```json Response with amount override
{
    "account_id": "68a4c3150b28a9584305a2a6",
    "customer_id": "68cdcbfed75e4961c7188672",
    "card_ids": [
        "68dec27a4fc15f2238b3476c"
    ],
    "status": "active",
    "service": "Super Premium Plan",
    "amount": 999,
    "currency": "MXN",
    "interval": "monthly",
    "frequency": 1,
    "trial_period_days": 14,
    "merchant_management": false,
    "mixed_management": false,
    "attempts": 0,
    "benefits": [
        "Unlimited access to premium content",
        "24/7 priority support",
        "Exclusive 35% discounts",
        "Up to 6 additional users"
    ],
    "errors": [],
    "auto_renew_commitment": false,
    "id": "6930cdfdffee47566ea1cf4c",
    "created_at": "2025-12-03T23:55:41.204Z",
    "updated_at": "2025-12-03T23:55:41.204Z"
}
```

<br />

***

## How Subscription Processing Works

### Automatic Payment Flow

1. **Subscription Created**:
   * POST `/api/subscriptions` creates subscription WITHOUT card\_ids
   * Customer receives email invitation with secure link
   * Subscription status: `active` but no payment methods

2. **Customer Dashboard Access**:
   * **Option A:** Customer clicks email link for direct access
   * **Option B:** Customer visits sandbox.ecartpay.com/subscriptions/login for OTP login
   * Customer sees subscription details and payment form

3. **Payment Method Addition**:
   * Customer adds credit card through secure form
   * Frontend calls PUT `/api/subscriptions/from-customer/:id` with `card_ids`
   * **This triggers automatic payment processing evaluation**

4. **Smart Processing** (triggered by card\_ids update):
   * **Trial Period**: No immediate charge, sets trial dates
   * **Pro-rata**: Charges proportional amount to next billing date
   * **Standard**: Charges full amount immediately
   * **Failed Payment**: Subscription continues with retry logic

### Pro-rata Billing

When a subscription has a `billing_cycle`, the first payment is calculated proportionally:

**Formula:** `(total_amount / days_in_cycle) * days_until_next_billing_date`

**Example:** Monthly subscription with `billing_cycle.day = 5` created on January 15th:

* Charges proportional amount from January 15th to February 5th
* Sets `next_payment_date = February 5th`
* Future payments charge full amount every 5th of the month

### Trial Periods

* **With Trial**: No immediate charge, establishes trial end date
* **Trial + Pro-rata**: After trial, first charge is proportional to billing cycle
* **Trial End**: Automatic charge processing when trial period expires

### Recurring Payments

* **Worker Process**: Automatically processes payments for subscriptions with `next_payment_date <= today`
* **Error Handling**: Multiple retry attempts with notifications
* **End Date Support**: Automatic termination for temporary subscriptions

***

## Billing Cycle Configuration

### Weekly Billing Cycle

```json
{
    "billing_cycle": {
        "day": 1,    // 1=Monday, 2=Tuesday, ..., 7=Sunday
        "month": 1   // Not used but required
    }
}
```

### Monthly/Quarterly/Semiannual/Yearly Billing Cycle

```json
{
    "billing_cycle": {
        "day": 15,   // Day of month (1-31)
        "month": 3   // Month of year (1-12)
    }
}
```

### Important Notes

* `billing_cycle` is **immutable** after creation
* System automatically handles short months (e.g., day 31 in February becomes day 28/29)
* `billing_cycle` is optional - subscriptions without it work as before
* Not supported for `daily` interval

***

## Notification System

### Automatic Notifications

**Events:**

* `create`: Subscription invitation sent to customer
* `success`: First successful payment
* `retry_success`: Payment successful after previous failures
* `failure`: Payment failure (attempt 2)
* `final_failure`: Multiple failures, subscription paused

**Channels:**

* **Email**: Always sent if customer has email

**Limits:**

* Maximum 5 invitation emails per subscription
* 24-hour cooldown between resend attempts

### Customer Access Methods

**Method 1: Direct Email Link (Invitation)**

* Customer receives invitation email after subscription creation
* Email contains direct link to specific subscription dashboard
* Immediate access to that subscription without additional verification

**Method 2: Customer Portal Login**

* Customer visits `app.ecartpay.com/subscriptions/login`
* Enters email address for OTP verification
* Uses OTP endpoints to access all their subscriptions
* **Note:** Only subscriptions whose invitations have been previously accessed will be visible

### Customer Dashboard Features

* **Secure Access**: Two-method authentication system
* **Subscription Details**: Plan information, benefits, status, pricing
* **Payment Management**: Add credit cards (triggers automatic payment processing)
* **Billing History**: View past and upcoming payments
* **Cancellation**: Self-service subscription cancellation

### OTP Authentication Flow

**Endpoints for Customer Login:**

* `POST /api/notifications/otp-send` - Send OTP code to customer email
* `POST /api/notifications/otp-verification` - Verify OTP code

**Process:**

1. Customer visits `/subscriptions/login`
2. Enters email address
3. System sends OTP via `otp-send` endpoint
4. Customer enters OTP code
5. System verifies via `otp-verification` endpoint
6. Customer gets authenticated token for session management

***

## Error Handling & Status Management

### Subscription States

* **Active**: Subscription is functioning normally
* **Pause**: Temporarily paused due to payment failures (≥5 attempts)
* **Cancelled**: Permanently terminated

### Payment Retry Logic

1. **Attempt 1**: Continue normally
2. **Attempt 2**: Send failure notification
3. **Attempts 3-4**: Continue retrying
4. **Attempt 5**: Pause subscription, send final notification

### Validation Rules

* `customer_id` must exist and belong to the account
* `amount` must be positive number
* `currency` must be `MXN` or `USD`
* `end_date` must be future date
* `billing_cycle.day` must be 1-31
* `billing_cycle.month` must be 1-12 (except weekly)
* `card_ids` maximum 5 cards per subscription