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

# Create Collection

> Create a payment collection session with hosted checkout. Accept payments from customers with callback and webhook support. POST /collections.

## Overview

Create a checkout session to collect payment from a customer. Returns a checkout URL where the customer completes payment.

## Request Body

| Field         | Type   | Required | Description                                                                |
| ------------- | ------ | -------- | -------------------------------------------------------------------------- |
| `amount`      | number | Yes      | Payment amount in USD                                                      |
| `currency`    | string | No       | Currency code (default: USD). Only USD supported, other values are ignored |
| `orderId`     | string | Yes      | Your unique order/invoice ID (max 100 chars)                               |
| `description` | string | Yes      | Payment description (max 100 chars)                                        |
| `callbackUrl` | string | No       | Return URL after payment (overrides dashboard setting)                     |
| `webhookUrl`  | string | No       | IPN URL for server-to-server notifications (overrides dashboard setting)   |
| `metadata`    | object | No       | Custom data to attach to the payment                                       |

<Note>
  `callbackUrl` and `webhookUrl` are optional overrides. If not provided, the URLs configured in your app dashboard will be used.
</Note>

## Response

| Field          | Type   | Description                               |
| -------------- | ------ | ----------------------------------------- |
| `collectionId` | string | Unique collection identifier              |
| `reference`    | string | Human-readable reference (shown to payer) |
| `orderId`      | string | Your order ID (if provided)               |
| `amount`       | number | Payment amount                            |
| `fee`          | number | Processing fee (deducted from amount)     |
| `netAmount`    | number | Amount you receive (amount - fee)         |
| `currency`     | string | Currency code                             |
| `status`       | string | `PENDING`                                 |
| `checkoutUrl`  | string | URL to redirect customer for payment      |
| `expiresAt`    | string | Session expiry time (60 minutes)          |

## Integration Examples

<CodeGroup>
  ```php PHP Server-Side theme={null}
  <?php
  // Create checkout session via API

  $appId = 'DD123FR45446CECES';
  $secretKey = 'YOUR_SECRET_KEY';

  // Step 1: Get access token
  $tokenResponse = file_get_contents('https://api.fyatu.com/api/v3/auth/token', false, stream_context_create([
      'http' => [
          'method' => 'POST',
          'header' => 'Content-Type: application/json',
          'content' => json_encode([
              'appId' => $appId,
              'secretKey' => $secretKey,
              'grantType' => 'client_credentials'
          ])
      ]
  ]));

  $token = json_decode($tokenResponse, true)['data']['accessToken'];

  // Step 2: Create checkout session
  $response = file_get_contents('https://api.fyatu.com/api/v3/collections', false, stream_context_create([
      'http' => [
          'method' => 'POST',
          'header' => [
              'Content-Type: application/json',
              'Authorization: Bearer ' . $token
          ],
          'content' => json_encode([
              'amount' => 25.00,
              'orderId' => 'INV-' . time(),
              'description' => 'Premium Subscription',
              'callbackUrl' => 'https://yoursite.com/payment/complete',  // Optional override
              'webhookUrl' => 'https://yoursite.com/webhook/fyatu',      // Optional override
              'metadata' => [
                  'userId' => '12345',
                  'plan' => 'premium'
              ]
          ])
      ]
  ]));

  $result = json_decode($response, true);

  if ($result['success']) {
      // Redirect customer to checkout
      header('Location: ' . $result['data']['checkoutUrl']);
      exit;
  } else {
      echo 'Error: ' . $result['message'];
  }
  ```

  ```javascript Node.js Server-Side theme={null}
  const APP_ID = 'DD123FR45446CECES';
  const SECRET_KEY = 'YOUR_SECRET_KEY';

  async function createCheckout(orderData) {
    // Step 1: Get access token
    const tokenResponse = await fetch('https://api.fyatu.com/api/v3/auth/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        appId: APP_ID,
        secretKey: SECRET_KEY,
        grantType: 'client_credentials'
      })
    });

    const { data: tokenData } = await tokenResponse.json();
    const accessToken = tokenData.accessToken;

    // Step 2: Create checkout session
    const response = await fetch('https://api.fyatu.com/api/v3/collections', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`
      },
      body: JSON.stringify({
        amount: orderData.amount,
        orderId: orderData.orderId,
        description: orderData.description,
        callbackUrl: 'https://yoursite.com/payment/complete',  // Optional override
        webhookUrl: 'https://yoursite.com/webhook/fyatu',      // Optional override
        metadata: orderData.metadata
      })
    });

    const result = await response.json();

    if (result.success) {
      return result.data.checkoutUrl;
    } else {
      throw new Error(result.message);
    }
  }

  // Usage in Express.js
  app.post('/create-payment', async (req, res) => {
    try {
      const checkoutUrl = await createCheckout({
        amount: 25.00,
        orderId: `INV-${Date.now()}`,
        description: 'Premium Subscription',
        metadata: { userId: req.user.id }
      });

      res.json({ checkoutUrl });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });
  ```
</CodeGroup>

## Example Response

```json theme={null}
{
  "success": true,
  "status": 201,
  "message": "Checkout session created successfully",
  "data": {
    "collectionId": "col_a1b2c3d4e5f6",
    "reference": "A2B4C6D8E0F2",
    "orderId": "ORD-0001",
    "amount": 25.00,
    "fee": 0.75,
    "netAmount": 24.25,
    "currency": "USD",
    "status": "PENDING",
    "checkoutUrl": "https://checkout.fyatu.com/sci/checkout?batch=col_a1b2c3d4e5f6",
    "expiresAt": "2026-01-08T12:30:00+00:00"
  },
  "meta": {
    "requestId": "req_abc123def456",
    "timestamp": "2026-01-08T11:30:00+00:00"
  }
}
```

## Checkout Flow

1. **Create Session**: Call this endpoint to create a checkout session
2. **Redirect Customer**: Send customer to the `checkoutUrl`
3. **Customer Pays**: Customer logs in and completes payment on Fyatu
4. **Webhook Notification**: Receive IPN at your `webhookUrl` (server-to-server)
5. **Customer Returns**: Customer is redirected to `callbackUrl` with status

## Callback URL

After payment (success or failure), the customer is redirected to your `callbackUrl` with query parameters:

```
https://yoursite.com/payment/complete?batch=col_a1b2c3d4e5f6&status=COMPLETED
```

| Parameter | Description                                         |
| --------- | --------------------------------------------------- |
| `batch`   | The collection ID                                   |
| `status`  | Payment status (`COMPLETED`, `FAILED`, `CANCELLED`) |

<Warning>
  Never trust callback parameters alone. Always verify payment status server-side using the webhook or by calling the [Get Collection](/v3/api-reference/collections/get) endpoint.
</Warning>

## Webhook (IPN)

Your `webhookUrl` receives a POST request with the payment details:

```json theme={null}
{
  "event": "collection.completed",
  "collectionId": "col_a1b2c3d4e5f6",
  "orderId": "ORD-0001",
  "reference": "A2B4C6D8E0F2",
  "status": "COMPLETED",
  "amount": 25.00,
  "fee": 0.75,
  "netAmount": 24.25,
  "currency": "USD",
  "payer": {
    "clientId": "clt_a1b2c3d4e5f6",
    "name": "Alice Example"
  },
  "metadata": {
    "plan": "premium"
  },
  "completedAt": "2026-01-08T11:35:00+00:00"
}
```

## Session Expiration

* Checkout sessions expire after **60 minutes**
* Expired sessions are automatically updated to status `EXPIRED`
* Create a new session if the customer returns after expiration

## Duplicate Prevention

* The `orderId` must be unique per app
* Attempting to create a collection with a duplicate `orderId` returns `409 Conflict`
* Use `orderId` to link payments to your order/invoice system

<Tip>
  Store the `collectionId` to later verify the payment status or issue refunds.
</Tip>


## OpenAPI

````yaml v3/openapi.json POST /collections
openapi: 3.1.0
info:
  title: FYATU API v3
  description: >-
    FYATU API v3 with JWT authentication for Collections, Payouts, and Card
    Issuing.
  version: 3.0.0
  contact:
    name: FYATU Support
    url: https://fyatu.com
    email: support@fyatu.com
servers:
  - url: https://api.fyatu.com/api/v3
    description: Production
security: []
tags:
  - name: Authentication
    description: JWT token management endpoints
  - name: Account
    description: Business account, wallet, and address management
  - name: Collections
    description: Accept payments from customers via checkout sessions
  - name: Refunds
    description: Issue refunds for completed collections
  - name: Payouts
    description: Send money to Fyatu account holders
  - name: Cardholders
    description: Cardholder management for card issuing programs
  - name: Cards
    description: Issue, fund, freeze, and manage virtual cards
  - name: Webhooks
    description: Webhook configuration and management
paths:
  /collections:
    post:
      tags:
        - Collections
      summary: Create Collection
      description: >-
        Create a checkout session to collect payment from a customer. Returns a
        checkout URL where the customer completes payment.
      operationId: createCollection
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CollectionRequest'
            example:
              amount: 25
              currency: USD
              orderId: ORD-0001
              description: Premium Subscription
              callbackUrl: https://yoursite.com/payment/complete
              webhookUrl: https://yoursite.com/webhook/fyatu
              metadata:
                userId: '12345'
                plan: premium
      responses:
        '201':
          description: Checkout session created successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CollectionResponse'
              example:
                success: true
                status: 201
                message: Checkout session created successfully
                data:
                  collectionId: col_a1b2c3d4e5f6
                  reference: A2B4C6D8E0F2
                  orderId: ORD-0001
                  amount: 25
                  fee: 0.75
                  netAmount: 24.25
                  currency: USD
                  status: PENDING
                  checkoutUrl: >-
                    https://checkout.fyatu.com/sci/checkout?batch=col_a1b2c3d4e5f6
                  expiresAt: '2026-01-08T12:30:00+00:00'
                meta:
                  requestId: req_abc123
                  timestamp: '2026-01-08T11:30:00+00:00'
        '400':
          $ref: '#/components/responses/ValidationError'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: Duplicate order ID
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                status: 409
                message: A collection with this order ID already exists
                error:
                  code: DUPLICATE_REFERENCE
                meta:
                  requestId: req_abc123
                  timestamp: '2026-01-08T11:30:00+00:00'
      security:
        - BearerAuth: []
components:
  schemas:
    CollectionRequest:
      type: object
      required:
        - amount
        - orderId
        - description
      properties:
        amount:
          type: number
          minimum: 1
          description: Payment amount in USD
        currency:
          type: string
          default: USD
          description: Currency code (only USD supported, other values ignored)
        orderId:
          type: string
          maxLength: 100
          description: Your unique order/invoice ID (required)
        description:
          type: string
          maxLength: 100
          description: Payment description (max 100 chars)
        callbackUrl:
          type: string
          format: uri
          description: Return URL after payment (overrides dashboard setting)
        webhookUrl:
          type: string
          format: uri
          description: >-
            IPN URL for server-to-server notifications (overrides dashboard
            setting)
        metadata:
          type: object
          description: Custom data to attach
    CollectionResponse:
      type: object
      properties:
        success:
          type: boolean
          example: true
        status:
          type: integer
          example: 201
        message:
          type: string
        data:
          $ref: '#/components/schemas/CollectionData'
        meta:
          $ref: '#/components/schemas/Meta'
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        status:
          type: integer
          example: 401
        message:
          type: string
          example: Invalid credentials
        error:
          $ref: '#/components/schemas/Error'
        meta:
          $ref: '#/components/schemas/Meta'
    CollectionData:
      type: object
      properties:
        collectionId:
          type: string
          description: Unique collection identifier
        reference:
          type: string
          description: Human-readable reference
        orderId:
          type: string
          description: Your order ID
        amount:
          type: number
          description: Payment amount
        fee:
          type: number
          description: Processing fee
        netAmount:
          type: number
          description: Amount after fee
        currency:
          type: string
        status:
          type: string
          enum:
            - PENDING
            - COMPLETED
            - EXPIRED
            - FAILED
            - REFUNDED
            - PARTIALLY_REFUNDED
        checkoutUrl:
          type: string
          description: URL to redirect customer
        expiresAt:
          type: string
          format: date-time
    Meta:
      type: object
      properties:
        requestId:
          type: string
          description: Unique request ID for tracking
          example: req_abc123def456
        timestamp:
          type: string
          format: date-time
          description: ISO 8601 timestamp of the response
    Error:
      type: object
      properties:
        code:
          type: string
          description: Error code for programmatic handling
          example: AUTH_INVALID_CREDENTIALS
        details:
          type: array
          items:
            $ref: '#/components/schemas/ValidationError'
          description: Validation error details (for VALIDATION_ERROR)
    ValidationError:
      type: object
      properties:
        field:
          type: string
          description: Field that failed validation
          example: appId
        message:
          type: string
          description: Validation error message
          example: AppId is required
  responses:
    ValidationError:
      description: Validation failed
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            status: 400
            message: Validation failed
            error:
              code: VALIDATION_ERROR
              details:
                - field: currency
                  message: Currency is required
            meta:
              requestId: req_abc123
              timestamp: '2026-01-05T10:30:00+00:00'
    Unauthorized:
      description: Authentication required or token invalid
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            success: false
            status: 401
            message: Unable to identify business
            error:
              code: AUTH_TOKEN_INVALID
            meta:
              requestId: req_abc123
              timestamp: '2026-01-05T10:30:00+00:00'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: JWT access token obtained from /auth/token

````