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

# Mark Expense as Paid

> Mark an unpaid expense as paid by providing payment date and method

## Overview

The Mark Expense as Paid endpoint allows you to record payment for an unpaid expense. This is a specialized endpoint that specifically handles the payment workflow, updating the expense status and recording payment details.

<Info>
  This endpoint is designed for expenses that are currently unpaid. If an expense is already paid, the request will fail with an appropriate error message.
</Info>

## Path Parameters

<ParamField path="id" type="string" required>
  The CzUid of the expense to mark as paid
</ParamField>

## Request Body

<ParamField body="paid_date" type="string" required format="date">
  The date when the payment was made (YYYY-MM-DD format)
</ParamField>

<ParamField body="payment_type" type="integer" required>
  The payment method used (1-7):

  * `1` - Cash
  * `2` - Bank transfer
  * `3` - Card
  * `4` - Check
  * `5` - Promissory note
  * `6` - Other
  * `7` - Compensation
</ParamField>

## Response

<ResponseField name="expense" type="object">
  The updated expense object reflecting the payment

  <Expandable title="Updated Expense Properties">
    <ResponseField name="id" type="string">Expense CzUid</ResponseField>
    <ResponseField name="is_paid" type="boolean">Now set to true</ResponseField>
    <ResponseField name="paid_date" type="string">The payment date provided</ResponseField>

    <ResponseField name="payment_type" type="object">
      Payment type information

      <Expandable title="Payment Type Object">
        <ResponseField name="id" type="integer">Payment type ID</ResponseField>
        <ResponseField name="name" type="string">Payment type name</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="status" type="string">Updated to "paid"</ResponseField>
    <ResponseField name="updated_at" type="string">New modification timestamp</ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="message" type="string">
  Success message confirming the payment has been recorded
</ResponseField>

## Business Logic

When an expense is marked as paid:

1. **Status Update**: The expense status changes from unpaid/overdue to paid
2. **Payment Recording**: Payment date and method are permanently recorded
3. **Audit Trail**: The payment action is logged for audit purposes
4. **Notifications**: Internal notifications may be triggered (if configured)

## Validation Rules

* **Expense Exists**: The expense must exist and be owned by your firm
* **Payment Status**: The expense must currently be unpaid (not already paid)
* **Date Format**: Payment date must be in YYYY-MM-DD format
* **Payment Type**: Must be a valid payment type ID (1-7)
* **Date Logic**: Payment date should typically not be in the future

## Error Scenarios

### Already Paid

If the expense is already marked as paid, you'll receive a 400 error. Use the [Update Expense](/api-reference/endpoints/expenses/update) endpoint if you need to change payment details for an already-paid expense.

### Invalid Payment Type

Payment types must match the predefined values. Check the payment\_type parameter documentation for valid options.

### Date Validation

Payment dates must be valid dates in the correct format. The system may also validate that payment dates are reasonable (not too far in the past or future).

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.contazen.ro/v1/expenses/exp_abc123/pay" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "paid_date": "2024-01-20",
      "payment_type": 2
    }'
  ```

  ```javascript JavaScript theme={null}
  const expenseId = 'exp_abc123';
  const paymentData = {
    paid_date: "2024-01-20",
    payment_type: 2  // Bank transfer
  };

  const response = await fetch(`https://api.contazen.ro/v1/expenses/${expenseId}/pay`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(paymentData)
  });

  const data = await response.json();
  if (data.success) {
    console.log('Expense marked as paid:', data.expense.status);
  } else {
    console.error('Payment failed:', data.error.message);
  }
  ```

  ```php PHP theme={null}
  $expenseId = 'exp_abc123';
  $paymentData = [
      'paid_date' => '2024-01-20',
      'payment_type' => 2  // Bank transfer
  ];

  $curl = curl_init();

  curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.contazen.ro/v1/expenses/{$expenseId}/pay",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => json_encode($paymentData),
      CURLOPT_HTTPHEADER => [
          'Authorization: Bearer YOUR_API_KEY',
          'Content-Type: application/json'
      ]
  ]);

  $response = curl_exec($curl);
  $data = json_decode($response, true);
  curl_close($curl);

  if ($data['success']) {
      echo 'Payment recorded: ' . $data['expense']['paid_date'];
  } else {
      echo 'Error: ' . $data['error']['message'];
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "success": true,
    "expense": {
      "id": "exp_abc123",
      "reference": "INV-2024-001",
      "description": "Office supplies purchase",
      "amount": {
        "total": "238.00",
        "without_vat": "200.00",
        "vat": "38.00",
        "currency": "RON"
      },
      "account_amount": {
        "total": "238.00",
        "without_vat": "200.00",
        "vat": "38.00",
        "currency": "RON"
      },
      "vat_percent": 19,
      "with_vat": true,
      "date": "2024-01-15",
      "due_date": "2024-02-15",
      "paid_date": "2024-01-20",
      "is_paid": true,
      "payment_type": {
        "id": 2,
        "name": "Bank transfer"
      },
      "status": "paid",
      "supplier_id": "sup_xyz789",
      "category_id": 1,
      "user_id": 1,
      "created_at": "2024-01-15 10:30:00",
      "updated_at": "2024-01-20 14:30:00"
    },
    "message": "Expense marked as paid successfully"
  }
  ```

  ```json 400 - Already Paid theme={null}
  {
    "success": false,
    "error": {
      "message": "Expense is already marked as paid",
      "type": "invalid_request_error",
      "code": "expense_already_paid"
    }
  }
  ```

  ```json 400 - Validation Error theme={null}
  {
    "success": false,
    "error": {
      "message": "Validation failed",
      "type": "invalid_request_error",
      "code": "validation_error",
      "fields": {
        "paid_date": "Payment date is required",
        "payment_type": "Invalid payment type. Must be between 1 and 7"
      }
    }
  }
  ```

  ```json 404 - Not Found theme={null}
  {
    "success": false,
    "error": {
      "message": "Expense not found",
      "type": "invalid_request_error",
      "code": "resource_missing",
      "param": "id"
    }
  }
  ```
</ResponseExample>

## Use Cases

### Bulk Payment Processing

When processing multiple payments (e.g., from bank statements), you can use this endpoint to mark individual expenses as paid:

```javascript JavaScript theme={null}
const payments = [
  { expenseId: 'exp_abc123', date: '2024-01-20', type: 2 },
  { expenseId: 'exp_def456', date: '2024-01-21', type: 1 },
];

for (const payment of payments) {
  await markExpensePaid(payment.expenseId, payment.date, payment.type);
}
```

### Integration with Banking APIs

This endpoint is ideal for integrating with banking APIs that provide transaction data:

```javascript JavaScript theme={null}
// Process bank transactions and mark corresponding expenses as paid
bankTransactions.forEach(async (transaction) => {
  const expense = findMatchingExpense(transaction);
  if (expense) {
    await markExpensePaid(expense.id, transaction.date, getPaymentType(transaction.type));
  }
});
```

### Manual Payment Entry

For manual payment entry in accounting workflows:

```javascript JavaScript theme={null}
const recordPayment = async (expenseId, paymentDetails) => {
  try {
    const result = await markExpensePaid(expenseId, paymentDetails.date, paymentDetails.method);
    showSuccessMessage('Payment recorded successfully');
    refreshExpenseList();
  } catch (error) {
    showErrorMessage('Failed to record payment: ' + error.message);
  }
};
```


## OpenAPI

````yaml POST /expenses/{id}/pay
openapi: 3.1.0
info:
  title: Contazen API
  version: 1.2.0
  description: >
    Build powerful integrations with the Contazen invoicing platform. The
    Contazen API is organized around REST, 

    has predictable resource-oriented URLs, accepts JSON request bodies, returns
    JSON-encoded responses, 

    and uses standard HTTP response codes, authentication, and verbs.


    ## Authentication

    The API uses Bearer token authentication. Include your API key in the
    Authorization header.


    ### Getting your API Key

    1. Log in to your Contazen account

    2. Navigate to Settings > API

    3. Generate or copy your API key (starts with `sk_live_` for production or
    `sk_test_` for testing)


    ### Using the API Key

    Include your API key in the Authorization header:

    ```

    Authorization: Bearer sk_live_YOUR_API_KEY

    ```


    ### Example Request with cURL

    ```bash

    curl --request GET \
      --url https://api.contazen.ro/v1/clients \
      --header 'Authorization: Bearer sk_live_YOUR_API_KEY' \
      --header 'Accept: application/json'
    ```


    ## Rate Limiting

    - 1000 requests per hour per API key

    - 100 create operations per minute per API key


    Rate limit information is included in response headers:

    - `X-RateLimit-Limit`: Maximum requests allowed

    - `X-RateLimit-Remaining`: Requests remaining

    - `X-RateLimit-Reset`: Reset time (Unix timestamp)


    ## Pagination

    All list endpoints return paginated results with the following format:

    ```json

    {
      "success": true,
      "data": {
        "object": "list",
        "data": [...],
        "has_more": true,
        "total": 245,
        "page": 1,
        "per_page": 50,
        "total_pages": 5
      },
      "meta": {
        "version": "v1",
        "request_id": "req_1a2b3c4d",
        "response_time": "23.45ms"
      }
    }

    ```


    ## Multi-Work-Point Access

    API keys belong to a specific work point but can access data from all work
    points

    within the same parent company.


    ## Error Handling

    The API uses conventional HTTP response codes to indicate success or
    failure. 

    In general: 2xx codes indicate success, 4xx codes indicate an error due to
    the 

    information provided, and 5xx codes indicate an error with Contazen's
    servers.


    ## Expanding Nested Objects

    Many endpoints support the `expand` parameter to include related objects in
    the response.

    This follows the Stripe API pattern. For example:

    - `expand[]=lines` - Include invoice line items

    - `expand[]=payments` - Include payment records

    - `expand[]=client` - Include full client object


    ## Localization

    The API supports multiple languages through:

    - `locale` query parameter (en, ro)

    - `Accept-Language` header

    - Default: English
  contact:
    name: Contazen Support
    email: support@contazen.ro
    url: https://contazen.ro
  license:
    name: Proprietary
    url: https://www.contazen.ro/termeni-si-conditii-de-utilizare/
servers:
  - url: https://api.contazen.ro/v1
    description: Production API server
security:
  - bearerAuth: []
tags:
  - name: Authentication
    description: API authentication and test endpoints
  - name: Clients
    description: Manage your customers (B2B and B2C)
  - name: Invoices
    description: Create and manage invoices, proformas, and receipts
  - name: Products
    description: Manage your product and service catalog
  - name: Expenses
    description: Track and manage business expenses
  - name: Expense Categories
    description: Organize expenses with categories
  - name: Suppliers
    description: Manage expense suppliers and vendors
  - name: Settings
    description: API settings and configuration
  - name: Payments
    description: Payments received against invoices
  - name: Receipts
    description: Cash receipts (chitanțe) — standalone or paired with an invoice
  - name: Company Lookup
    description: Romanian company lookup (ANAF / VIES)
  - name: Invoice Series
    description: Manage invoice numbering series
  - name: Bank Accounts
    description: Manage IBAN bank accounts
  - name: E-Factura
    description: Romanian e-invoicing status and configuration
  - name: Supplier Bills
    description: Supplier invoices imported from the ANAF SPV inbox
  - name: VAT Rates
    description: Firm-scoped custom VAT rates on top of the Romanian catalog
  - name: Currencies
    description: Currencies enabled for the firm's bill templates
  - name: Languages
    description: Languages enabled for the firm's bill templates
  - name: Conta
    description: |
      Public ANAF data for the firm's CUI: fiscal profile (TVA scope, RTVAI,
      split TVA, status, e-Factura registration, CAEN) and annual balance
      sheets (cifra de afaceri, profit, capitaluri, datorii, salariați).

      Powered by the public ANAF webservices (no OAuth required for these
      endpoints). The data is cached locally and refreshed on demand via
      the `/sync` actions.
paths:
  /expenses/{id}/pay:
    post:
      tags:
        - Expenses
      summary: Mark expense as paid
      description: Mark an expense as paid
      operationId: payExpense
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          description: Expense CzUid
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - paid_date
                - payment_type
              properties:
                paid_date:
                  type: string
                  format: date
                  description: Payment date
                payment_type:
                  type: integer
                  minimum: 1
                  maximum: 7
                  description: Payment method (1-7)
      responses:
        '200':
          description: Expense marked as paid
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    $ref: '#/components/schemas/Expense'
                  meta:
                    $ref: '#/components/schemas/ResponseMeta'
        '401':
          $ref: '#/components/responses/UnauthorizedError'
        '404':
          $ref: '#/components/responses/NotFoundError'
components:
  schemas:
    Expense:
      type: object
      required:
        - id
        - reference
        - amount
        - date
        - due_date
        - status
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: exp_1a2b3c4d5e
        reference:
          type: string
          description: Invoice/document reference number
        description:
          type: string
        amount:
          type: object
          properties:
            total:
              type: number
              example: 500
            without_vat:
              type: number
            vat:
              type: number
            currency:
              type: string
        account_amount:
          type: object
          description: Amounts in account currency (RON)
          properties:
            total:
              type: number
            without_vat:
              type: number
            vat:
              type: number
            currency:
              type: string
              default: RON
        vat_percent:
          type: integer
          enum:
            - 0
            - 5
            - 9
            - 11
            - 19
            - 21
        with_vat:
          type: boolean
          description: Whether amount includes VAT
        date:
          type: string
          format: date
        due_date:
          type: string
          format: date
        paid_date:
          type: string
          format: date
          nullable: true
        is_paid:
          type: boolean
        payment_type:
          type: object
          nullable: true
          properties:
            id:
              type: integer
            name:
              type: string
        status:
          type: string
          enum:
            - paid
            - unpaid
            - overdue
            - registered
        supplier_id:
          type: string
        supplier:
          $ref: '#/components/schemas/Supplier'
        category_id:
          type: integer
        category:
          $ref: '#/components/schemas/ExpenseCategory'
        user_id:
          type: integer
        user:
          type: object
          properties:
            id:
              type: integer
            name:
              type: string
        currency_exchange:
          type: object
          nullable: true
          properties:
            from:
              type: string
            to:
              type: string
            rate:
              type: number
        attachment:
          type: object
          nullable: true
          description: Single attachment (stored in the 'image' field)
          properties:
            url:
              type: string
            filename:
              type: string
            type:
              type: string
              enum:
                - pdf
                - image
            size:
              type: integer
        efactura:
          type: object
          nullable: true
          description: |
            Populated when the expense was imported from the ANAF e-Factura SPV
            inbox. `null` for manually created expenses.
          properties:
            supplier_invoice_id:
              type: string
            invoice_number:
              type: string
              nullable: true
            anaf_message_id:
              type: string
              nullable: true
            xml_available:
              type: boolean
            pdf_available:
              type: boolean
            pdf_url:
              type: string
              nullable: true
              description: >-
                Bearer-authenticated URL that streams the e-Factura PDF;
                regenerated on demand when missing
        items:
          type: array
          description: |
            Line rows for the expense. Always at least one entry — legacy flat
            expenses get a single synthesized line built from the header totals
            so API consumers can render a uniform table. Send `items` on
            create/update to persist real multi-line rows.
          items:
            $ref: '#/components/schemas/ExpenseLine'
        vat_breakdown:
          type: array
          nullable: true
          description: |
            Per-rate VAT tranches when the receipt mixes two or more rates.
            `null` for single-rate expenses.
          items:
            $ref: '#/components/schemas/ExpenseVatBreakdownEntry'
        category_source:
          type: string
          nullable: true
          enum:
            - ai
            - supplier
            - manual
          description: |
            How the category was assigned. `null` on uncategorized expenses
            or legacy rows where provenance wasn't recorded.
        category_confidence:
          type: number
          nullable: true
          minimum: 0
          maximum: 1
          description: Auto-classifier confidence when category_source is 'ai'.
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    ResponseMeta:
      type: object
      properties:
        version:
          type: string
          default: v1
        request_id:
          type: string
          format: uuid
          description: Unique request identifier for debugging
        response_time:
          type: string
          example: 23.45ms
    Supplier:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: string
          description: Unique identifier (CzUid)
          example: sup_1a2b3c4d5e
        name:
          type: string
        cui:
          type: string
          description: Tax identification number
        rc:
          type: string
          description: Company registration number
        cnp:
          type: string
          description: Personal identification number
        address:
          type: string
        city:
          type: string
        county:
          type: string
        country:
          type: string
        postal_code:
          type: string
        phone:
          type: string
        email:
          type: string
        iban:
          type: string
        bank:
          type: string
        contact_person:
          type: string
        contact_phone:
          type: string
        contact_email:
          type: string
        is_vat_payer:
          type: boolean
        statistics:
          type: object
          properties:
            expense_count:
              type: integer
            total_amount:
              type: number
            paid_amount:
              type: number
            unpaid_amount:
              type: number
        recent_expenses:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              reference:
                type: string
              amount:
                type: number
              currency:
                type: string
              date:
                type: string
                format: date
              is_paid:
                type: boolean
        metadata:
          type: object
          description: |
            Lightweight expense aggregates. Returned by `GET /suppliers` only
            when `with_totals=1` is supplied. Cheaper than `expand=statistics`
            since the totals come from a single inline subquery rather than
            a per-row N+1 follow-up. Amounts are expressed in the firm's
            accounting currency.
          properties:
            expense_count:
              type: integer
              description: Number of non-deleted expenses for this supplier
            total_expenses:
              type: number
              description: Sum of `account_amount_total` across all matching expenses
            unpaid_total:
              type: number
              description: Sum of `account_amount_total` across unpaid matching expenses
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
    ExpenseCategory:
      type: object
      required:
        - id
        - name
        - type
      properties:
        id:
          type: integer
        name:
          type: string
        parent_id:
          type: integer
          nullable: true
        is_default:
          type: boolean
          description: Whether this is a system default category
        is_visible:
          type: boolean
        type:
          type: string
          enum:
            - system
            - custom
        expense_count:
          type: integer
          description: Number of expenses in this category
        children:
          type: array
          items:
            $ref: '#/components/schemas/ExpenseCategory'
    ExpenseLine:
      type: object
      required:
        - id
        - line_index
        - name
        - quantity
        - unit_price
        - vat_rate
        - amount_wvat
        - amount_vat
        - amount
      properties:
        id:
          type: integer
          description: Line row ID. `0` for synthesized legacy lines.
        line_index:
          type: integer
          description: Zero-based position within the expense.
        name:
          type: string
        description:
          type: string
          nullable: true
        quantity:
          type: number
          description: Supports fractional quantities (e.g. 0.5 kg).
        unit_code:
          type: string
          nullable: true
          description: Optional UN/ECE unit code (e.g. H87, KGM).
        unit_price:
          type: number
          description: >-
            Net unit price (excluding VAT). Negative values represent discount
            rows (e.g. bon fiscal `DISCOUNT 4,40-A`); the sign is preserved
            through net/VAT/gross.
        vat_rate:
          type: integer
          enum:
            - 0
            - 5
            - 9
            - 11
            - 19
            - 21
        amount_wvat:
          type: number
          description: Line net, 2dp, `round(quantity * unit_price, 2)`.
        amount_vat:
          type: number
          description: Line VAT, 2dp, `round(amount_wvat * vat_rate / 100, 2)`.
        amount:
          type: number
          description: Line gross, 2dp, `amount_wvat + amount_vat`.
        category_id:
          type: string
          nullable: true
          description: >-
            Optional per-line category override (falls back to expense-level
            category).
        product_id:
          type: string
          nullable: true
          description: Optional link to a product in the firm's catalog.
    ExpenseVatBreakdownEntry:
      type: object
      required:
        - rate
        - vat_amount
      properties:
        rate:
          type: integer
          enum:
            - 0
            - 5
            - 9
            - 11
            - 19
            - 21
        net:
          type: number
          nullable: true
          description: Sum of line nets at this rate (2dp).
        vat_amount:
          type: number
          description: Sum of line VATs at this rate (2dp).
        gross:
          type: number
          nullable: true
          description: Sum of line gross values at this rate (2dp).
    ErrorResponse:
      type: object
      required:
        - success
        - error
      properties:
        success:
          type: boolean
          default: false
        error:
          type: object
          required:
            - message
            - type
            - code
          properties:
            message:
              type: string
              description: Human-readable error message
            type:
              type: string
              enum:
                - api_error
                - authentication_error
                - invalid_request_error
                - rate_limit_error
                - permission_error
                - validation_error
            code:
              type: string
              description: Machine-readable error code
            param:
              type: string
              description: The parameter that caused the error
            doc_url:
              type: string
              format: uri
              description: URL to relevant documentation
        meta:
          $ref: '#/components/schemas/ResponseMeta'
  responses:
    UnauthorizedError:
      description: API key is missing or invalid
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFoundError:
      description: The specified resource was not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Use your API key (sk_live_xxx or sk_test_xxx)

````