# Invoices

Manage invoices, track payment status, and handle the complete invoice lifecycle in FarPay. This section covers creating, updating, and monitoring invoices with their payment states.

## Overview

Invoices represent bills sent to customers for payment. Each invoice has a payment state that tracks its progress through the payment lifecycle, from creation to completion or failure.

## Invoice Payment States

| State              | Value | Description                                                  |
| ------------------ | ----- | ------------------------------------------------------------ |
| **Not Paid**       | 100   | Initial state when invoice is created                        |
| **Paid**           | 200   | Payment received and matches invoice amount                  |
| **Scheduled**      | 300   | Customer has agreement, payment scheduled                    |
| **Pending**        | 400   | Scheduled payment being processed                            |
| **Rejected**       | 500   | Payment rejected by user, creditor, or financial institution |
| **Chargeback**     | 600   | Amount charged back, transaction reversed                    |
| **Refund**         | 650   | Refund executed                                              |
| **Payment Failed** | 700   | Payment failed due to agreement removal or low balance       |
| **N/A**            | 1000  | System errors or payment system errors                       |

<Image alt="Invoice State Diagram" border={false} src="../images/invoiceStates/invoiceStates.png" />

## API Endpoints

### Get All Invoices

Retrieve all invoices with optional filtering.

```http
GET https://api.farpay.io/v2/invoices
```

**Query Parameters:**

* `fromDueDate` (optional) - Filter from due date (YYYY-MM-DD)
* `toDueDate` (optional) - Filter to due date (YYYY-MM-DD)
* `paymentStatus` (optional) - Filter by payment status (100, 200, 300, 400, 500, 600, 700)

**Response Example:**

```json
[
  {
    "Id": 123,
    "Created": "2025-09-15T10:30:00Z",
    "InvoiceNumber": "INV-001",
    "PaymentDueDate": "2025-09-15T00:00:00Z",
    "InvoiceAmount": 125.00,
    "ToBePaidAmount": 125.00,
    "PaymentReferenceStatus": "Ok",
    "PaymentType": "MobilePayInvoice",
    "SendStatus": "Queue",
    "ErrorDescription": ""
  }
]
```

### Get Single Invoice

Retrieve detailed information for a specific invoice.

```http
GET https://api.farpay.io/v2/invoices/{invoiceId}
```

**Parameters:**

* `invoiceId` (path) - The invoice's unique identifier

**Response Example:**

```json
{
  "Send": {
    "SentDate": "0001-01-01T00:00:00",
    "ErrorCode": 0,
    "ErrorDescription": "",
    "Channel": "",
    "Status": "Queue",
    "ScheduleSendDate": null,
    "ToAddress": "",
    "Note": ""
  },
  "Id": 74836045,
  "Token": "wN0BNaBoW2DMfx5DeVasQMgs508JbuO8",
  "PaymentDetails": "+71 <000004561237944 +42426240<",
  "MarkedAsPaid": null,
  "Created": "2025-09-24T09:54:57.57",
  "InvoiceTypeCode": "PIE",
  "InvoiceDate": "24-09-2025",
  "InvoiceAmount": 125,
  "TaxAmount": 25,
  "ToBePaidAmount": 125,
  "Ean": null,
  "InvoiceNote": null,
  "InvoiceWasPaidManually": null,
  "InvoiceNumber": "2525",
  "PaymentDueDate": "2025-09-24T00:00:00",
  "Currency": "DKK",
  "Recepient": {
    "CustomerNumber": "1",
    "CompanyNo": null,
    "Gln": null,
    "Name": "John Doe",
    "Email": "john@example.com",
    "Street": null,
    "PostCode": null,
    "PoBox": null,
    "City": null,
    "Country": null,
    "ContactId": null,
    "ContactName": null,
    "ContactPhone": null,
    "ContactEmail": null
  },
  "Buyer": null,
  "Destination": null,
  "SchedulePayment": 0,
  "PaymentReference": null,
  "PaymentStatus": 100,
  "PaymentType": null,
  "InvoiceStatus": "Ok",
  "PaymentRejectedBy": null,
  "PdfInvoice": null,
  "PdfAttachments": null,
  "InvoiceLines": [
    {
      "LineNumber": 1,
      "ProductNumber": null,
      "Description": "Monthly subscription",
      "BasePrice": 100,
      "Quantity": 1,
      "UnitCode": null,
      "DiscountRate": 0,
      "DiscountedPrice": 0,
      "TaxRate": 0.25,
      "TaxAmount": 25,
      "Amount": 125
    }
  ],
  "TextLines": null,
  "Template": null,
  "OrderToken": null
}
```

### Create Invoice

Create a new invoice for a customer.

```http
POST https://api.farpay.io/v2/invoices
```

**InvoiceTypecode**

The invoice typecode value determins the class of the document, wether it is an Invoice or a Creditnote.

| InvoiceTypeCode | Description |
| :-------------- | :---------- |
| `PIE`           | Invoice     |
| `PCM`           | Creditnote  |

**Please note** that all types of amounts are always given in positive numbers, regardless of `InvoiceTypeCode`.

**Request Body:**

Example values, with added comments

```json
{
  "InvoiceTypeCode": "PIE",
  "InvoiceDate": "2024-02-29",
  "InvoiceAmount": 100,
  "TaxAmount": 25,
  "ToBePaidAmount": 125,
  "Ean": "EAN238273273828",
  "InvoiceNote": "A note to the invoice",
  "InvoiceWasPaidManually": "2024-02-29T20:33:03.022Z", // optional, should be only be set, when the invoice was paid manually
  "InvoiceNumber": "K23119", // If set, it must be unique. In some cases, FarPay or the attached accounting system will generate the number
  "PaymentDueDate": "2024-02-29T20", // The future due date. When "instant" todays date can be used.
  "Currency": "dkk", // Must always be set, DKK is the default for Danish companies. Se more info in the currencies section.
  "Recepient": {  // The customer, that is being invoiced
    "CustomerNumber": "C1234x", // The customer number, if the customer already exists, this number is the only property needed to identify the customer.
    "CompanyNo": "string",
    "Gln": "string",
    "Name": "string",
    "Email": "string",
    "Street": "string",
    "PostCode": "string",
    "PoBox": "string",
    "City": "string",
    "Country": "string",
    "ContactId": "string",
    "ContactName": "string",
    "ContactPhone": "string",
    "ContactEmail": "string"
  },
  "Buyer": { // Optional
    "CompanyNo": "string",
    "Gln": "string",
    "Name": "string",
    "Street": "string",
    "PostCode": "string",
    "City": "string",
    "Country": "string",
    "ContactInformation": {
      "Identifier": "string",
      "Name": "string",
      "Phone": "string",
      "Email": "string",
      "Role": "string"
    }
  },
  "Destination": { // Optional
    "CompanyNo": "string",
    "Gln": "string",
    "Name": "string",
    "Street": "string",
    "PostCode": "string",
    "City": "string",
    "Country": "string",
    "ContactInformation": {
      "Identifier": "string",
      "Name": "string",
      "Phone": "string",
      "Email": "string",
      "Role": "string"
    }
  },
  "SchedulePayment": "Default",
  "PaymentReference": "string",
  "PaymentStatus": "NotPaid",
  "PaymentType": "string",
  "InvoiceStatus": "string",
  "PaymentRejectedBy": "string",
  "PdfInvoice": {
    "Filename": "string",
    "Data": "string"
  },
  "PdfAttachments": [
    {
      "Filename": "string",
      "Data": "string"
    }
  ],
  "InvoiceLines": [
    {
      "LineNumber": 0,
      "ProductNumber": "string",
      "Description": "string",
      "BasePrice": 0,
      "Quantity": 0,
      "UnitCode": "string",
      "DiscountRate": 0,
      "DiscountedPrice": 0,
      "TaxRate": 0,
      "TaxAmount": 0,
      "Amount": 0
    }
  ],
  "TextLines": "string",
  "Template": "string",
  "Send": {
    "Channel": "string",
    "Status": "string",
    "ScheduleSendDate": "2024-02-29T20:33:03.022Z",
    "ToAddress": "string",
    "Note": "string"
  }
}
```

<br />

### Update Invoice

Update an existing invoice.

```http
PUT https://api.farpay.io/v2/invoices/{invoiceId}
```

**Request Body:**

```json
{
  "PaymentDueDate": "2025-09-15",
  "InvoiceLines": [
    {
      "Description": "Updated subscription",
      "Quantity": 1,
      "BasePrice": 150.00,
      "Amount": 150.00
    }
  ]
}
```

### Delete Invoice

Delete an invoice (only possible in certain states).

```http
DELETE https://api.farpay.io/v2/invoices/{invoiceId}
```

## Invoice Properties

### Core Properties

| Property                 | Type     | Description                      | Constraints         |
| ------------------------ | -------- | -------------------------------- | ------------------- |
| `Id`                     | integer  | FarPay unique invoice identifier | Auto-generated      |
| `Created`                | datetime | Invoice creation timestamp       | ISO 8601 format     |
| `InvoiceNumber`          | string   | Your invoice number              | Required, unique    |
| `PaymentDueDate`         | date     | When payment is due              | YYYY-MM-DD format   |
| `InvoiceAmount`          | decimal  | Total invoice amount             | 2 decimal places    |
| `ToBePaidAmount`         | decimal  | Remaining amount to be paid      | 2 decimal places    |
| `PaymentReferenceStatus` | string   | Payment reference status         | "Ok", "Error", etc. |
| `PaymentType`            | string   | Payment method type              | See Payment Types   |
| `SendStatus`             | string   | Communication status             | See Send Status     |
| `ErrorDescription`       | string   | Error details if any             | Optional            |

### Customer Information

| Property         | Type   | Description                  |
| ---------------- | ------ | ---------------------------- |
| `CustomerNumber` | string | Customer's unique identifier |
| `Name`           | string | Customer's full name         |
| `Email`          | string | Customer's email address     |

### Invoice Lines

| Property      | Type    | Description           |
| ------------- | ------- | --------------------- |
| `Description` | string  | Line item description |
| `Quantity`    | decimal | Quantity of items     |
| `UnitPrice`   | decimal | Price per unit        |
| `TotalPrice`  | decimal | Total line price      |

## Payment Types

| Type                     | Description                        |
| ------------------------ | ---------------------------------- |
| `MobilePayInvoice`       | MobilePay invoice payment          |
| `MobilePaySubscriptions` | MobilePay subscription             |
| `Betalingsservice`       | Direct debit for private customers |
| `Leverandørservice`      | Direct debit for businesses        |
| `FI`                     | Manual payment (Faktura)           |
| `Dankort`                | Danish debit card                  |
| `Visa`                   | Visa credit/debit card             |
| `MasterCard`             | MasterCard credit/debit card       |

## Send Status

The `SendStatus` indicates how the invoice will be processed regarding customer communication:

| Status    | Description                |
| --------- | -------------------------- |
| `Queue`   | Invoice queued for sending |
| `Sent`    | Invoice sent to customer   |
| `Failed`  | Failed to send invoice     |
| `Pending` | Awaiting processing        |

## Invoice Filtering

### Date Range Filtering

Filter invoices by due date range:

```http
GET https://api.farpay.io/v2/invoices?fromDueDate=2023-01-01&toDueDate=2023-01-31
```

### Payment Status Filtering

Filter invoices by payment status:

```http
GET https://api.farpay.io/v2/invoices?paymentStatus=200
```

**Available status values:** 100, 200, 300, 400, 500, 600, 700

## Invoice Lifecycle

1. **Create Invoice** - POST invoice details to create new invoice
2. **Send to Customer** - Invoice is automatically sent based on SendStatus
3. **Customer Receives** - Customer receives invoice via email/SMS
4. **Payment Processing** - Customer pays through chosen payment method
5. **Status Updates** - Invoice status updates as payment progresses
6. **Completion** - Invoice marked as Paid or other final state

## Best Practices

1. **Invoice Numbers**: Use meaningful, unique identifiers for tracking
2. **Due Dates**: Set realistic payment due dates
3. **Payment Types**: Choose appropriate payment methods for your customers
4. **Invoice Lines**: Provide clear, detailed line item descriptions
5. **Error Handling**: Monitor ErrorDescription for failed invoices
6. **Status Monitoring**: Regularly check invoice status for payment tracking

## Error Handling

Common invoice-related errors:

| Error                           | Description                | Solution                      |
| ------------------------------- | -------------------------- | ----------------------------- |
| `Invoice number already exists` | Duplicate invoice number   | Use unique invoice numbers    |
| `Customer not found`            | Invalid customer number    | Verify customer exists        |
| `Invalid payment type`          | Unsupported payment method | Check available payment types |
| `Invalid due date`              | Due date in the past       | Set future due dates          |
| `Invoice cannot be updated`     | Invoice in locked state    | Check current invoice status  |

## Integration Examples

### Create Invoice with Multiple Lines

```json
{
  "CustomerNumber": "12345",
  "InvoiceNumber": "INV-002",
  "PaymentDueDate": "2025-09-15",
  "PaymentType": "MobilePayInvoice",
  "InvoiceLines": [
    {
      "Description": "Basic subscription",
      "Quantity": 1,
      "BasePrice": 99.00,
      "Amount": 99.00
    },
    {
      "Description": "Premium add-on",
      "Quantity": 1,
      "BasePrice": 26.00,
      "Amount": 26.00
    }
  ]
}
```

### Monitor Invoice Status

```javascript
// Check invoice status
const invoice = await fetch(`/invoices/123`);
const status = invoice.PaymentReferenceStatus;

if (status === 'Ok') {
  console.log('Invoice is active');
} else if (status === 'Error') {
  console.log('Invoice has errors:', invoice.ErrorDescription);
}
```

## Related Resources

* [Customers](customers#) - Manage customer information
* [Payments](payments#) - Track payment history
* [Orders](orders#) - Create payment flows
* [Agreements](agreements#) - Handle recurring payments

<br />