# Start a subscription

Creates an incomplete subscription and its first payment. Send the customer to `checkout_url`; when they pay, it becomes active, the card is kept for renewals and `subscription.activated` is sent. With a free trial (the plan's `trial_days`, or `trial_days` here) it starts as `trialing` with nothing to pay; when the trial ends, `subscription.payment_required` carries the first checkout link. Add `trial_requires_card: true` to take the card first: the customer pays a small check at `checkout_url` (refunded at once), the trial then starts, and the first period is charged to that card when it ends.

## Endpoint

POST https://api.veyqo.org/api/v1/subscriptions

Server secret key required. Scope: subscriptions:write. The key determines the project and environment; no project-selection header is accepted.

> For each new operation, generate and persist one OPERATION_IDEMPOTENCY_KEY. Retry the unchanged request with that same key. Do not generate a new key on every retry.

## Example request

Examples use illustrative IDs and provider URLs. Replace path variables with IDs returned by your own requests. Never paste a live secret into client code or a public tool.

### cURL

```bash
curl --request POST "https://api.veyqo.org/api/v1/subscriptions" \
  --header "Authorization: Bearer $VEYQO_SECRET_KEY" \
  --header "Accept: application/json" \
  --header "Idempotency-Key: $OPERATION_IDEMPOTENCY_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "plan": "rplan_01M7Q2Z8X4K3V9B6N5C1D0E2F3",
  "customer": {
    "email": "customer@example.com",
    "name": "Ada Lovelace"
  },
  "reference": "SUB-1001",
  "metadata": {
    "customer_id": "42"
  }
}'
```

### Node.js

```javascript
// Server-side Node.js 18+. Save operation.idempotencyKey before a write.
const response = await fetch(`https://api.veyqo.org/api/v1/subscriptions`, {
  method: 'POST',
  headers: {
  "Authorization": `Bearer ${process.env.VEYQO_SECRET_KEY}`,
  "Accept": "application/json",
  "Idempotency-Key": operation.idempotencyKey,
  "Content-Type": "application/json"
},
  body: JSON.stringify({
  "plan": "rplan_01M7Q2Z8X4K3V9B6N5C1D0E2F3",
  "customer": {
    "email": "customer@example.com",
    "name": "Ada Lovelace"
  },
  "reference": "SUB-1001",
  "metadata": {
    "customer_id": "42"
  }
}),
});
const result = await response.json();
if (!response.ok || !result.success) {
  console.error(response.status, result.error?.code, response.headers.get('X-Request-Id'));
  throw new Error(result.error?.message ?? 'Veyqo request failed');
}
console.log(result.data);
```

### PHP

```php
<?php
// Server-side PHP with the cURL extension. Persist $operationIdempotencyKey.
$curl = curl_init('https://api.veyqo.org/api/v1/subscriptions');
curl_setopt_array($curl, [
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer '.getenv('VEYQO_SECRET_KEY'),
    'Accept: application/json',
    'Idempotency-Key: '.$operationIdempotencyKey,
    'Content-Type: application/json'
  ],
  CURLOPT_POSTFIELDS => <<<'JSON'
{
  "plan": "rplan_01M7Q2Z8X4K3V9B6N5C1D0E2F3",
  "customer": {
    "email": "customer@example.com",
    "name": "Ada Lovelace"
  },
  "reference": "SUB-1001",
  "metadata": {
    "customer_id": "42"
  }
}
JSON,
]);
$body = curl_exec($curl);
if ($body === false) throw new RuntimeException(curl_error($curl));
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
curl_close($curl);
$result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400 || !($result['success'] ?? false)) {
  throw new RuntimeException($result['error']['code'] ?? 'Veyqo request failed');
}
print_r($result['data']);
```

### Python

```python
# pip install requests; run on your server.
import os, requests
from urllib.parse import quote

response = requests.request('POST', f'https://api.veyqo.org/api/v1/subscriptions',
    headers={
  "Authorization": 'Bearer ' + os.environ['VEYQO_SECRET_KEY'],
  "Accept": "application/json",
  "Idempotency-Key": operation_idempotency_key,
  "Content-Type": "application/json"
},
    json={
  "plan": "rplan_01M7Q2Z8X4K3V9B6N5C1D0E2F3",
  "customer": {
    "email": "customer@example.com",
    "name": "Ada Lovelace"
  },
  "reference": "SUB-1001",
  "metadata": {
    "customer_id": "42"
  }
},
    timeout=30)
result = response.json()
if not response.ok or not result.get('success'):
    raise RuntimeError(f"{response.status_code} {result.get('error')} request_id={response.headers.get('X-Request-Id')}")
print(result['data'])
```

## Request body

| Field | Type | Presence | Description |
| --- | --- | --- | --- |
| plan | string | Required | Plan id. |
| customer | object | Required | email (required) and name. |
| reference | string \| null | Optional | Your reference; unique in the environment. Maximum 150 characters. |
| callback_url | string \| null | Optional | HTTPS return URL after the first payment. Format: uri. |
| provider | string \| null | Optional | Provider slug; omitted, routed like a payment. |
| trial_days | integer \| null | Optional | Overrides the plan's free trial for this customer; 0 for none. Minimum 0. |
| trial_requires_card | boolean \| null | Optional | With a trial: take the card first with a small check that is refunded at once, and charge the first period to it when the trial ends. |
| metadata | object \| null | Optional | Copied onto every payment of the subscription. |

## Successful response · 201

HTTP success means the request was accepted. A pending payment or refund is not completed merely because the response is 200 or 201.

```json
{
  "success": true,
  "data": {
    "id": "csub_01M7Q3A1B2C3D4E5F6G7H8J9K0",
    "object": "subscription",
    "reference": "SUB-1001",
    "status": "incomplete",
    "plan": {
      "id": "rplan_01M7Q2Z8X4K3V9B6N5C1D0E2F3",
      "object": "plan",
      "name": "Pro monthly",
      "description": "Everything in Pro",
      "amount": 250000,
      "currency": "NGN",
      "interval": "month",
      "interval_count": 1,
      "trial_days": 0,
      "active": true,
      "metadata": [],
      "created_at": "2026-11-19T12:00:00+00:00"
    },
    "customer": {
      "email": "customer@example.com",
      "name": "Ada Lovelace"
    },
    "card": null,
    "current_period_start": null,
    "current_period_end": null,
    "trial_ends_at": null,
    "pending_plan": null,
    "cancel_at_period_end": false,
    "cancelled_at": null,
    "failed_attempts": 0,
    "next_attempt_at": null,
    "payments_count": 0,
    "latest_payment_id": "pay_01M7Q3B2C3D4E5F6G7H8J9K0L1",
    "checkout_url": "https://checkout.paystack.com/example",
    "metadata": {
      "customer_id": "42"
    },
    "created_at": "2026-11-19T12:00:00+00:00"
  }
}
```

## Response fields

| Field in data | Type | Presence | Description |
| --- | --- | --- | --- |
| id | string | Optional | csub_ id. |
| object | string | Optional | Always subscription. |
| reference | string \| null | Optional | Your own reference, unique in the environment. |
| status | string | Optional | incomplete, trialing, active, past_due or cancelled. Values: incomplete, trialing, active, past_due, cancelled. |
| plan | Plan | Optional | A plan your customers subscribe to. |
| plan.id | string | Optional | rplan_ id. |
| plan.object | string | Optional | Always plan. |
| plan.name | string | Optional | Shown on checkout. |
| plan.description | string \| null | Optional | Optional. |
| plan.amount | integer | Optional | Per period, in the smallest currency unit. |
| plan.currency | string | Optional | ISO 4217. |
| plan.interval | string | Optional | day, week, month or year. Values: day, week, month, year. |
| plan.interval_count | integer | Optional | Periods per charge, e.g. 3 with month for quarterly. |
| plan.trial_days | integer | Optional | Free trial for new subscriptions, in days (0 for none). |
| plan.active | boolean | Optional | False once archived. |
| plan.metadata | object | Optional | Your own key-values. |
| plan.created_at | string | Optional | ISO 8601. Format: date-time. |
| customer | object | Optional | email and name. |
| card | object \| null | Optional | brand and last4 of the saved card, if any. |
| current_period_start | string \| null | Optional | Start of the paid period. |
| current_period_end | string \| null | Optional | When the next charge is due. |
| trial_ends_at | string \| null | Optional | When the free trial ends, if it had one. |
| pending_plan | object \| null | Optional | The plan that takes over at the next renewal, if a change is scheduled. |
| cancel_at_period_end | boolean | Optional | Ends instead of renewing. |
| cancelled_at | string \| null | Optional | When it ended. |
| failed_attempts | integer | Optional | Failed renewal tries this period (ends after 3). |
| next_attempt_at | string \| null | Optional | Next charge or retry. |
| payments_count | integer | Optional | Periods paid. |
| latest_payment_id | string \| null | Optional | The most recent payment. |
| checkout_url | string \| null | Optional | Where the customer pays, when something is due from them. |
| metadata | object | Optional | Your own key-values. |
| created_at | string | Optional | ISO 8601. Format: date-time. |

## Errors and recovery

| Code | HTTP | Recovery | Retry policy |
| --- | --- | --- | --- |
| INVALID_API_KEY | 401 | Use a current kc_test_ or kc_live_ secret key on /api/v1. Use a pk_test_ or pk_live_ publishable key only on browser checkout. | After fixing credentials. |
| INSUFFICIENT_PERMISSION | 403 | Grant the required scope or use a suitably scoped key. Dashboard organization roles and staff permissions are separate. | After permission changes. |
| RATE_LIMIT_EXCEEDED | 429 | Honor Retry-After, use bounded exponential backoff with jitter, and reduce concurrent requests. Read X-RateLimit headers. | Yes, after Retry-After; preserve write idempotency. |
| METHOD_NOT_ALLOWED | 405 | Use the method documented for the endpoint, such as POST for verification and refunds. | After fixing the method. |
| INTERNAL_ERROR | 500 | Record X-Request-Id, timestamp and sanitized request context. Reconcile unknown payment outcomes before retrying a write; contact support if it persists. | Safe reads: bounded backoff. Writes: reconcile first. |
| VALIDATION_FAILED | 422 | Read error.details when present, correct the named fields and retry only after correction. Validation messages may describe state/capability errors without field details. | No automatic retry. |
| RESOURCE_NOT_FOUND | 404 | Check the ID, project and environment. Do not guess another project’s IDs. An inactive payment link is also not-found. | No blind retry. |
| DUPLICATE_REFERENCE | 409 | Retrieve that payment and reconcile its state. For a genuinely new attempt, use a new unique reference and operation key; do not create a second charge just because a response was lost. | Reconcile first. |
| PROVIDER_NOT_CONNECTED | 422 | Connect a provider, choose the project default, or explicitly pass provider. An account shared with another project still needs its own assignment here. | After configuration changes. |
| PROVIDER_REQUEST_FAILED | 422 | Read the safe message, inspect the payment’s failure details and correct the request or provider account. Never repeatedly retry a business rejection. | Only after resolving the cause. |
| PROVIDER_UNAVAILABLE | 503 | Check the existing payment and verify its state before starting another attempt. Retry safe reads with backoff; preserve operation identity for retried writes. | Conditional: reconcile unknown outcomes first. |
| IDEMPOTENCY_KEY_REUSED | 409 | Reuse the exact original request to recover that operation, or use a new key only for a genuinely different operation. | Do not retry a changed body with that key. |
| IDEMPOTENCY_IN_PROGRESS | 409 | Wait briefly, retry with the same key and unchanged request, then reconcile by reference if the result remains uncertain. | Back off with jitter; preserve key/body. |

- [Complete error catalogue](https://veyqo.org/docs/errors): Every Veyqo error code, including which surface emits it and how to recover.
