# Invoices (/en/integrate/invoices)

Create, issue and send an invoice from your server, listen for the events that tell you it was paid, record payments, issue credit notes and manage tax rates.

An Invoice is a bill for one customer, with a hosted page where they pay it. Your server creates a draft, finalizes it, and sends it. XPay hosts the pay page, sends reminders, and posts a webhook when money arrives.

This page covers the developer path. For the dashboard flow your team uses day to day, see [Invoices](/features/invoices/overview) under Features.

<Callout type="info">
  The invoice API follows the shape of Stripe's invoice API: the same objects, statuses, actions and
  event names. Field names are camelCase, and amounts are integers in minor units (`150000` is
  1,500.00 EGP). If you have built on Stripe invoices, the model is the one you know.
</Callout>

## How it works [#how-it-works]

1. **Your server** creates a draft with `POST /invoices`: a customer and line items.
2. **Your server** finalizes it with `POST /invoices/:id/finalize`. The invoice gets its number and its `hostedInvoiceUrl`, and its amounts are frozen.
3. **Your server** sends it with `POST /invoices/:id/send`, or shares `hostedInvoiceUrl` itself.
4. **The customer** pays on the hosted page, in full, in parts or by installment.
5. **XPay** posts `invoice.paid` when nothing remains to pay. That is your signal to fulfil.

Sending a draft finalizes it first, so steps 2 and 3 can be one call.

The dashboard calls finalizing **issuing**. An issued invoice in the dashboard is a finalized invoice in the API.

## Statuses [#statuses]

`status` holds one of five stored values. Each change is its own action; you never set `status` with an update.

| `status`        | Meaning                                                   |
| --------------- | --------------------------------------------------------- |
| `draft`         | Editable. No number, no pay link.                         |
| `open`          | Finalized and waiting for payment.                        |
| `paid`          | Nothing remains to pay.                                   |
| `uncollectible` | Written off. It can still be paid, which makes it `paid`. |
| `void`          | Cancelled. It keeps its number.                           |

`displayStatus` is what to show people. It adds three computed values: `scheduled` (a draft with `automaticallyFinalizesAt`), `partially_paid` and `past_due`.

## Build it [#build-it]

### 1. Create a draft [#1-create-a-draft]

`POST /invoices` needs a `customerId`. Everything else is optional and can be added later with `PATCH /invoices/:id` while the invoice is a draft.

<Tabs items="[&#x22;cURL&#x22;, &#x22;Node.js&#x22;, &#x22;Python&#x22;]">
  <Tab value="cURL">
    ```bash
    curl -X POST https://api.xpay.app/invoices \
      -H "Authorization: Bearer sk_test_..." \
      -H "Idempotency-Key: 8b1f6c0e-2a4d-4c7b-9f3a-5e2d1c0b7a66" \
      -H "Content-Type: application/json" \
      -d '{
        "customerId": "cus_3Nf8a2kLmPq9",
        "daysUntilDue": 7,
        "defaultTaxRateIds": ["txr_3Nf8a2kLmPq9"],
        "lines": [
          { "description": "Website design", "quantity": 2, "unitAmount": 150000, "unitLabel": "day" }
        ],
        "delivery": { "channels": ["email"] },
        "metadata": { "order_id": "ord_42" }
      }'
    ```
  </Tab>

  <Tab value="Node.js">
    ```typescript
    const res = await fetch("https://api.xpay.app/invoices", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.XPAY_SECRET_KEY}`,
        "Idempotency-Key": crypto.randomUUID(),
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        customerId: "cus_3Nf8a2kLmPq9",
        daysUntilDue: 7,
        defaultTaxRateIds: ["txr_3Nf8a2kLmPq9"],
        lines: [
          // 2 days at 1,500.00 EGP, in minor units
          { description: "Website design", quantity: 2, unitAmount: 150000, unitLabel: "day" },
        ],
        delivery: { channels: ["email"] },
        metadata: { order_id: "ord_42" },
      }),
    });

    const invoice = await res.json();
    ```
  </Tab>

  <Tab value="Python">
    ```python
    import os, uuid, requests

    res = requests.post(
        "https://api.xpay.app/invoices",
        headers={
            "Authorization": f"Bearer {os.environ['XPAY_SECRET_KEY']}",
            "Idempotency-Key": str(uuid.uuid4()),
            "Content-Type": "application/json",
        },
        json={
            "customerId": "cus_3Nf8a2kLmPq9",
            "daysUntilDue": 7,
            "defaultTaxRateIds": ["txr_3Nf8a2kLmPq9"],
            "lines": [
                {"description": "Website design", "quantity": 2, "unitAmount": 150000, "unitLabel": "day"}
            ],
            "delivery": {"channels": ["email"]},
            "metadata": {"order_id": "ord_42"},
        },
        timeout=10,
    )

    invoice = res.json()
    ```
  </Tab>
</Tabs>

The main request fields:

| Field                       | Notes                                                                                                                                                                   |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customerId`                | Required. The customer needs a name and an email or a phone number before the invoice can be finalized.                                                                 |
| `lines`                     | Up to 250. A line takes a catalog `priceId`, or a `description` with a `unitAmount`. `quantity` is at least 0.001, with up to 3 decimal places.                         |
| `dueDate` or `daysUntilDue` | A date (`YYYY-MM-DD`), or days after finalization (0 to 365). Send one, not both. With neither, the invoice is due on receipt.                                          |
| `defaultTaxRateIds`         | Tax rates for lines that set none of their own. A line can carry its own `taxRateIds`, up to 5.                                                                         |
| `discounts`                 | Up to 5 on the invoice and 5 on each line. `{ "type": "percent", "percent": 10 }`, `{ "type": "amount", "amount": 5000 }` or `{ "type": "coupon", "couponId": "..." }`. |
| `shipping`                  | `{ "amount": 5000, "taxRateIds": [] }`.                                                                                                                                 |
| `allowPartialPayments`      | Let the customer pay part of the amount. `minimumPartialAmount` sets the smallest part payment.                                                                         |
| `paymentMethodTypes`        | The payment methods the invoice accepts. `null` means your account default.                                                                                             |
| `delivery`                  | `channels` (`email`, `sms`, or empty to share the link yourself), `additionalRecipients` (up to 5), `message`.                                                          |
| `locale`, `pdfLanguage`     | `locale` is `auto`, `ar` or `en` for the email, SMS and pay page. `pdfLanguage` is `ar`, `en` or `bilingual`.                                                           |
| `description`, `footer`     | The memo and the footer. `customFields` takes up to 4 `{ name, value }` pairs.                                                                                          |
| `automaticallyFinalizesAt`  | Finalize and send the draft at this time (ISO 8601 with an offset). `null` cancels the schedule.                                                                        |
| `autoAdvance`               | Whether XPay sends reminders and handles overdue for this invoice.                                                                                                      |
| `metadata`                  | Your own key-value bag.                                                                                                                                                 |

To change the lines of a draft without resending them all, use `POST /invoices/:id/add-lines`, `update-lines` and `remove-lines`, up to 50 lines per request. `POST /invoices/preview` returns the totals for an invoice without saving it.

For a payment plan, call `PUT /invoices/:id/installments` with the whole plan: 2 to 24 installments, each with an `amount` and a `dueDate`. On a draft they add up to the `total`, because an invoice on a plan uses no customer credit. On a finalized invoice they add up to `amountDue` less its credit notes. An empty list removes the plan.

### 2. Finalize it [#2-finalize-it]

```bash
curl -X POST https://api.xpay.app/invoices/in_3Nf8a2kLmPq9/finalize \
  -H "Authorization: Bearer sk_test_..." \
  -H "Idempotency-Key: 0d7c2f4a-91b3-4e58-a6c1-3f8e2b9d4c10"
```

Finalizing assigns the next number in your sequence, copies the customer's and your business details onto the invoice, applies any customer credit, and creates the pay link. The optional body `{ "issueDate": "2026-05-01" }` sets the date shown on the invoice; it defaults to today.

An invoice with nothing left to pay after customer credit goes straight to `paid`.

From here the invoice is not edited. To correct it, issue a [credit note](#credit-notes), or [revise it](#revise-or-cancel-an-invoice).

### 3. Send it [#3-send-it]

```bash
curl -X POST https://api.xpay.app/invoices/in_3Nf8a2kLmPq9/send \
  -H "Authorization: Bearer sk_test_..." \
  -H "Idempotency-Key: 6a3e9d1c-5b72-4f0e-8c4d-1e7a2b3c9f55" \
  -H "Content-Type: application/json" \
  -d '{ "channels": ["email", "sms"], "message": "Thank you for your order." }'
```

The body is optional. Without it the invoice's saved `delivery` settings are used; with it, the settings are saved for the next send too. Calling `send` on a draft finalizes it first. Calling it on an open invoice sends it again.

The response returns before the message is delivered. `invoice.sent` fires the first time the invoice reaches the customer, not on a resend. To follow every send, read `GET /invoices/:id/activity`. If you prefer to deliver the invoice yourself, skip this call and share `hostedInvoiceUrl`.

In test mode, nothing reaches the customer. The invoice still moves on as it would in live mode, and `invoice.sent` still fires.

### 4. Read the response [#4-read-the-response]

Every call above returns the invoice. This is the object after step 2, trimmed to the main fields:

```json
{
  "id": "in_3Nf8a2kLmPq9",
  "object": "invoice",
  "livemode": false,
  "status": "open",
  "displayStatus": "open",
  "number": "INV-000127",
  "collectionMethod": "send_invoice",
  "currency": "EGP",
  "customerId": "cus_3Nf8a2kLmPq9",
  "customerName": "Mona Adel",
  "customerEmail": "mona@example.com",
  "issueDate": "2026-05-01",
  "dueDate": "2026-05-08",
  "isOverdue": false,
  "subtotal": 300000,
  "totalTaxes": [
    {
      "amount": 42000,
      "taxableAmount": 300000,
      "taxBehavior": "exclusive",
      "taxRateDetails": {
        "taxRateId": "txr_3Nf8a2kLmPq9",
        "displayName": "VAT",
        "displayNameAr": null,
        "percentage": 14
      }
    }
  ],
  "total": 342000,
  "amountDue": 342000,
  "amountPaid": 0,
  "amountRemaining": 342000,
  "lines": [
    {
      "id": "il_3Nf8a2kLmPq9",
      "object": "line_item",
      "description": "Website design",
      "quantity": 2,
      "unitLabel": "day",
      "pricing": { "unitAmount": 150000, "priceDetails": null },
      "amount": 300000,
      "amountTotal": 342000
    }
  ],
  "installments": [],
  "payments": [],
  "allowPartialPayments": false,
  "delivery": {
    "channels": ["email"],
    "additionalRecipients": [],
    "message": null
  },
  "statusTransitions": {
    "finalizedAt": "2026-05-01T09:12:00.000Z",
    "paidAt": null,
    "markedUncollectibleAt": null,
    "voidedAt": null
  },
  "sentAt": null,
  "hostedInvoiceUrl": "https://checkout.xpay.app/i/ilink_test_...",
  "hostedInvoiceUrlExpiresAt": null,
  "metadata": { "order_id": "ord_42" }
}
```

The fields you will use most:

| Field                                         | Meaning                                                                                        |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `status`, `displayStatus`                     | The stored status, and the one to show people.                                                 |
| `number`                                      | Assigned at finalization. `null` on a draft.                                                   |
| `total`                                       | What the invoice is worth.                                                                     |
| `amountDue`                                   | What the customer must pay in total, after customer credit. Credit notes do not change it.     |
| `amountPaid`, `amountRemaining`               | Received so far, and still to pay.                                                             |
| `dueDate`, `isOverdue`, `daysOverdue`         | The due date (`null` means due on receipt) and whether it has passed with an amount remaining. |
| `lines`, `totalTaxes`, `totalDiscountAmounts` | What is billed, with tax and discounts worked out.                                             |
| `payments`                                    | Every payment on the invoice, online or recorded.                                              |
| `installments`                                | The payment plan. Empty when there is none.                                                    |
| `hostedInvoiceUrl`                            | The page where the customer views and pays the invoice.                                        |
| `startingBalance`, `endingBalance`            | The customer's balance before and after the invoice used it. Negative is credit.               |
| `fromInvoice`, `latestRevisionId`             | Set on an invoice that revises another, and on the invoice that was replaced.                  |

`GET /invoices/:id` returns the same object. `GET /invoices` lists invoices as `{ "data": [...], "totalCount": 0 }`, with `page` and `limit` (up to 100), and filters such as `status`, `customerId`, `overdue`, `dueDate`, `created` and `search`. `GET /invoices/:id/pdf` returns the PDF; add `?language=ar`, `en` or `bilingual` to choose its language.

## Listen for invoice events [#listen-for-invoice-events]

Subscribe to the events you need on your webhook endpoint. The `data.object` of every `invoice.*` event is the full Invoice, identical to `GET /invoices/:id`.

| Event                          | Fires when                                                                                                                                          | `data.object`   |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- |
| `invoice.created`              | A draft is created, including a duplicate or a revision.                                                                                            | Invoice         |
| `invoice.updated`              | An invoice changes outside its other events: a draft is edited, the due date, payment plan or link changes, or a recorded payment is removed.       | Invoice         |
| `invoice.deleted`              | A draft is deleted.                                                                                                                                 | Invoice         |
| `invoice.finalized`            | A draft is finalized and gets its number.                                                                                                           | Invoice         |
| `invoice.finalization_failed`  | A scheduled draft could not be finalized at its time. It stays a draft and its schedule is cancelled.                                               | Invoice         |
| `invoice.sent`                 | The invoice is first delivered to the customer.                                                                                                     | Invoice         |
| `invoice.will_be_due`          | 3 days before the due date, while an amount remains.                                                                                                | Invoice         |
| `invoice.overdue`              | The due date passes with an amount remaining. On a payment plan, once for each installment.                                                         | Invoice         |
| `invoice.payment_succeeded`    | A payment is received on the invoice, online or recorded. Fires for every payment.                                                                  | Invoice         |
| `invoice.payment_failed`       | An online payment attempt is declined, or a payment reference expires unpaid.                                                                       | Invoice         |
| `invoice.paid`                 | Nothing remains to pay, from payments, customer credit or a credit note. Fires again if a removed payment reopens the invoice and it is paid again. | Invoice         |
| `invoice.overpaid`             | A payment brought in more than was owed. The extra became customer credit.                                                                          | Invoice         |
| `invoice.marked_uncollectible` | The invoice is written off, by you or by automatic write-off.                                                                                       | Invoice         |
| `invoice.voided`               | The invoice is voided, including when a revision replaces it.                                                                                       | Invoice         |
| `invoice_payment.paid`         | One payment on an invoice is received.                                                                                                              | Invoice Payment |
| `credit_note.created`          | A credit note is issued, including one written for a direct refund.                                                                                 | Credit Note     |
| `credit_note.updated`          | A credit note's memo or metadata changes.                                                                                                           | Credit Note     |
| `credit_note.voided`           | A credit note is voided.                                                                                                                            | Credit Note     |
| `customer.updated`             | The customer's `balance` changes: credit was given, used or returned.                                                                               | Customer        |

### Which event to fulfil on [#which-event-to-fulfil-on]

**Fulfil on `invoice.paid`.** It fires when nothing remains to pay: the money came online, from a recorded payment or from customer credit. It also fires when a [credit note](#credit-notes) clears what was left, with no new money received. If you remove a recorded payment, the invoice opens again and `invoice.paid` fires again when it is paid. Fulfil each invoice only once, by its `id`.

To tell the two apart, compare `amountPaid` with `amountDue`. When a credit note cleared the rest, `amountPaid` is below `amountDue` and `prePaymentCreditNotesAmount` holds the credited part. If you fulfil only once money arrives, check this before you fulfil.

If you deliver in stages, as with part payments or installments, use `invoice.payment_succeeded` or `invoice_payment.paid`. They fire for each payment. Read `amountPaid` and `amountRemaining` on the invoice, or `amountPaid` and `installmentId` on the Invoice Payment.

On one successful payment, events arrive in this order: `invoice_payment.paid`, `invoice.payment_succeeded`, then `invoice.paid` if nothing remains, then `invoice.overpaid` and `customer.updated` if the payment was above what was owed. Do not rely on delivery order across retries; handle each event idempotently by its `id`.

For the signature-verification recipe, see [Webhooks → Verifying signatures](/integrate/webhooks/verifying-signatures).

## Record a payment [#record-a-payment]

When the customer pays you outside XPay, attach a payment record to the invoice:

```bash
curl -X POST https://api.xpay.app/invoices/in_3Nf8a2kLmPq9/attach-payment \
  -H "Authorization: Bearer sk_test_..." \
  -H "Idempotency-Key: 2c9a7e4b-6d18-4b3f-b5a0-9e1f3d7c8a21" \
  -H "Content-Type: application/json" \
  -d '{
    "paymentRecord": {
      "amount": 100000,
      "method": "bank_transfer",
      "paidAt": "2026-05-03",
      "reference": "TRX-88231"
    }
  }'
```

`method` is `cash`, `bank_transfer`, `cheque` or `other`. `paidAt` defaults to today and cannot be in the future. `reference` is printed on the receipt; `note` is for your team only.

The response is the invoice after the payment. The invoice must be `open` or `uncollectible`. An amount above what remains becomes customer credit, and `invoice.overpaid` fires.

Online payments attach themselves when the customer pays, so this endpoint only takes a payment record.

Each payment is an Invoice Payment (`inpay_*`):

```json
{
  "id": "inpay_3Nf8a2kLmPq9",
  "object": "invoice_payment",
  "invoiceId": "in_3Nf8a2kLmPq9",
  "status": "paid",
  "amountRequested": 100000,
  "amountPaid": 100000,
  "amountRefunded": 0,
  "currency": "EGP",
  "payment": {
    "type": "payment_record",
    "paymentIntentId": null,
    "checkoutSessionId": null,
    "paymentRecord": { "method": "bank_transfer", "reference": "TRX-88231", "note": null }
  },
  "statusTransitions": { "paidAt": "2026-05-02T21:00:00.000Z", "canceledAt": null },
  "installmentId": null,
  "receiptNumber": "2830-5289",
  "receiptUrl": "https://checkout.xpay.app/r/rlink_live_..."
}
```

An online payment has `payment.type` of `payment_intent` with its `paymentIntentId` and `checkoutSessionId`.

* `GET /invoice-payments?invoiceId=in_...` lists an invoice's payments, and `GET /invoice-payments/:id` reads one.
* `DELETE /invoice-payments/:id` removes a payment you recorded by mistake. Online payments are refunded instead.
* `receiptUrl` is the receipt's page, with its PDF. `POST /invoice-payments/:id/send-receipt` emails the receipt again (live mode only).

## Credit notes [#credit-notes]

A Credit Note lowers a finalized invoice without changing it. It first reduces what the customer still owes (`prePaymentAmount`). Anything beyond that was already paid (`postPaymentAmount`) and must go back to the customer.

```bash
curl -X POST https://api.xpay.app/credit-notes \
  -H "Authorization: Bearer sk_test_..." \
  -H "Idempotency-Key: 4f2b8d6a-3c91-4e7f-a2d5-7b0c1e9f6a34" \
  -H "Content-Type: application/json" \
  -d '{
    "invoiceId": "in_3Nf8a2kLmPq9",
    "lines": [
      { "type": "invoice_line_item", "invoiceLineItemId": "il_3Nf8a2kLmPq9", "quantity": 1 }
    ],
    "reason": "order_change",
    "memo": "One day cancelled"
  }'
```

This credits one day, 171000 with tax. The invoice above still has 242000 to pay, so all of the credit lowers what is owed and nothing was paid back: the three fields below are left out.

Say what to credit with `lines` or with `amount`, not both:

* `lines` credits invoice lines (`invoice_line_item`, by `quantity` or by an `amount` before tax) or adds lines of its own (`custom_line_item`, with `description` and `unitAmount`). Tax on an invoice line is credited in proportion.
* `amount` credits one total with no tax, as a single line.

Then say how the part that was already paid goes back. These three must add up to `postPaymentAmount`:

| Field             | What it does                                                                                         |
| ----------------- | ---------------------------------------------------------------------------------------------------- |
| `refundAmount`    | Refunds the invoice's online payments, newest first. Needs the refunds write permission on your key. |
| `creditAmount`    | The customer keeps it as credit, used on their next invoice.                                         |
| `outOfBandAmount` | You returned it outside XPay.                                                                        |

Call `POST /credit-notes/preview` with the same body first to read `prePaymentAmount` and `postPaymentAmount` before you decide the split. Nothing is saved.

Rules worth knowing:

* The invoice must be `open`, `paid` or `uncollectible`, with no online payment in progress.
* All credit notes on an invoice together cannot be more than its `total` (`credit_note_amount_too_large`).
* The part the customer paid with their credit balance can only go back as `creditAmount`.
* `refundAmount` works on invoices in EGP. On an invoice in another currency, refund the payment with `POST /refunds`.
* `POST /credit-notes/:id/void` works only while the invoice is `open` and the credit note gave nothing back.
* `PATCH /credit-notes/:id` changes the `memo` and `metadata` only.

### Refunding an invoice payment directly [#refunding-an-invoice-payment-directly]

You can also refund an invoice's online payment with [`POST /refunds`](/integrate/refunds) and its `paymentIntentId`.

* If the invoice is `paid`, the refund first returns anything the customer paid above the invoice. XPay writes a credit note for the rest and posts `credit_note.created`. The invoice stays `paid`.
* If the invoice is still `open`, the payment is taken back: `amountPaid` goes down and `amountRemaining` goes up by the amount refunded, and no credit note is written.

Either way, the Invoice Payment keeps `status: "paid"` and shows the money returned in `amountRefunded`.

## Customer credit [#customer-credit]

A customer's `balance` is their credit with you. A negative balance is credit. It is used automatically when their next invoice is finalized.

* `GET /customers/:id/balance-transactions` lists every change to the balance.
* `POST /customers/:id/balance-transactions` adjusts it by hand: `{ "amount": -5000, "description": "Goodwill credit" }`. A negative `amount` gives credit; a positive one takes it back.

Each change posts `customer.updated`.

## Tax rates [#tax-rates]

A Tax Rate is a reusable tax you apply to lines, such as 14% VAT.

```bash
curl -X POST https://api.xpay.app/tax-rates \
  -H "Authorization: Bearer sk_test_..." \
  -H "Content-Type: application/json" \
  -d '{
    "displayName": "VAT",
    "displayNameAr": "ضريبة القيمة المضافة",
    "percentage": 14,
    "inclusive": false
  }'
```

```json
{
  "id": "txr_3Nf8a2kLmPq9",
  "object": "tax_rate",
  "displayName": "VAT",
  "displayNameAr": "ضريبة القيمة المضافة",
  "percentage": 14,
  "inclusive": false,
  "active": true
}
```

* `inclusive: false` adds the tax on top of the price. `inclusive: true` means the price already contains it.
* `percentage` is above 0 and up to 100, with up to 4 decimal places.
* `percentage` and `inclusive` cannot change after creation, so finalized invoices never change. `PATCH /tax-rates/:id` changes the names, the `description` and `active`.
* Set `active: false` to archive a rate. It stays on existing invoices, and adding it to a new one returns `tax_rate_archived`.

`GET /tax-rates` lists your rates and accepts `active` and `inclusive` filters.

## Revise or cancel an invoice [#revise-or-cancel-an-invoice]

| To                          | Call                                                                                                                                                                                               |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Correct a finalized invoice | `POST /invoices` with `{ "fromInvoice": { "action": "revision", "invoiceId": "in_..." } }`. The invoice must be `open` or `uncollectible`. You get a draft copy. Finalizing it voids the original. |
| Change the due date         | `POST /invoices/:id/due-date` with `{ "dueDate": "2026-06-01" }`, or `null` for due on receipt.                                                                                                    |
| Remind the customer         | `POST /invoices/:id/send-reminder`.                                                                                                                                                                |
| Cancel it                   | `POST /invoices/:id/void`. Only while no payment has been received.                                                                                                                                |
| Write it off                | `POST /invoices/:id/mark-uncollectible`.                                                                                                                                                           |
| Replace the pay link        | `POST /invoices/:id/rotate-link`. The old link stops working at once.                                                                                                                              |
| Copy it                     | `POST /invoices/:id/duplicate`.                                                                                                                                                                    |
| Delete a draft              | `DELETE /invoices/:id`.                                                                                                                                                                            |

An invoice with a payment cannot be voided or revised (`invoice_has_payments`). Issue a credit note instead.

## Idempotency [#idempotency]

Send an `Idempotency-Key` on every invoice write you might retry: creating and updating an invoice, changing its lines, `finalize`, `send`, `send-reminder`, `void`, `mark-uncollectible`, `due-date`, `duplicate`, `rotate-link`, `attach-payment`, `POST /credit-notes`, `POST /credit-notes/:id/void` and `POST /customers/:id/balance-transactions`.

It matters most on `finalize`, `attach-payment` and `POST /credit-notes`. A blind retry after a timeout would otherwise use a second invoice number, record the same payment twice, or refund the customer twice. With a key, the retry returns the original result. See [Idempotency](/integrate/idempotency).

## Production checklist [#production-checklist]

* **Fulfil from the webhook, not the redirect.** `invoice.paid` is the source of truth. A customer can close the page before it reloads.
* **Handle events idempotently.** Store the event `id` and skip one you have already processed.
* **Scope the API key.** The key needs the **Invoices** permission, **Tax rates** if it manages them, and **Refunds** write only if it sends `refundAmount`.
* **Check the customer first.** Finalizing fails with `invoice_customer_incomplete` when the customer has no name, or neither an email nor a phone number.
* **Expect limits on sending.** SMS is limited per invoice, per phone number and per month, and manual emails are limited per day. A message that was skipped shows on the invoice's activity in the dashboard.
* **Read the error code.** Invoice errors carry codes such as `invoice_not_editable` and `invoice_payment_in_progress`. See [API error codes](/integrate/errors/api-error-codes#invoices).

## Where to next [#where-to-next]

<Cards>
  <Card icon="<FileText />" title="Invoices in the dashboard" href="/features/invoices/overview">
    The flow your team uses without writing code.
  </Card>

  <Card icon="<Webhook />" title="Set up a webhook endpoint" href="/integrate/webhooks/setting-up-an-endpoint">
    Receive `invoice.paid` and verify its signature.
  </Card>

  <Card icon="<ShieldCheck />" title="Idempotency" href="/integrate/idempotency">
    Retry invoice writes safely.
  </Card>

  <Card icon="<TriangleAlert />" title="API error codes" href="/integrate/errors/api-error-codes">
    Every invoice, credit note and tax rate error code.
  </Card>

  <Card icon="<Network />" title="Object model" href="/integrate/object-model">
    How Payment Intents, Charges and Refunds sit behind an invoice payment.
  </Card>
</Cards>