# Bill Deliveries

Upload bill files for batch processing using the FarPay Bill format. This section covers creating and uploading bill files, including Overførselsservice (OS) bills for payouts.

## Overview

The Bill format is a business-driven format designed to encapsulate bill data with payment instructions. It can handle both single bills and bulk bill processing, using a proprietary XML format specific to the FarPay system.

## Bill Format Requirements

### Prerequisites

* **X-API-KEY**: Merchant API key from FarPay settings page
* **XSD Schema**: Available at `https://app.farpay.io/xsd/bills/bills.xsd`
* **Base64 Encoding**: Bill files must be base64 encoded

## Creating Bill Deliveries

### Step-by-Step Process

1. **Get the XSD document** and create a bill file
2. **Encode the PDF document** into base64 format
3. **Put the base64 string** into the `EncodedDocument` container
4. **Convert the entire XML document** into base64 string
5. **Create a Delivery** with the following data:
   * `DeliveryType` = `Bill`
   * `DeliveryFormat` = `XML`
   * `File` containing the base64 encoded bill

### Basic Bill Example

```xml
<?xml version="1.0" encoding="UTF-8"?>
<FarPayXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://app.farpay.io/xsd/bills.xsd">
    <Delivery>
        <Count>1</Count>
    </Delivery>
    <Bills>
        <Bill>
            <InvoiceTypeCode>PCM</InvoiceTypeCode>
            <InvoiceNumber>CRED-12345</InvoiceNumber>
            <EncodedDocument>JVBERi0xLjcNCiW1t......olJUVPRg==</EncodedDocument>
            <CustomerNumber>CUST-67890</CustomerNumber>
            <Name>John Doe</Name>
            <Street>Main Street</Street>
            <HouseNumber>42</HouseNumber>
            <PostalZone>12345</PostalZone>
            <CityName>Example City</CityName>
            <Country>CountryName</Country>
            <EmailAddress>johndoe@example.com</EmailAddress>
            <PaymentDueDate>2025-02-01</PaymentDueDate>
            <Currency>DKK</Currency>
            <ToBePayedAmount>123.45</ToBePayedAmount>
        </Bill>
    </Bills>
</FarPayXml>
```

### API Request

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

**Request Body:**

```json
{
  "DeliveryType": "Bill",
  "DeliveryFormat": "XML",
  "File": {
    "Filename": "MyFile.xml",
    "Data": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbm......+DQo8L0ZhclBheVhtbD4="
  }
}
```

## Overførselsservice (OS) Bills

Overførselsservice bills are used for payout scenarios where you need to send money to customers or partners.

### OS Bill Example

```xml
<?xml version="1.0" encoding="UTF-8"?>
<FarPayXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://app.farpay.io/xsd/bills.xsd">
    <Delivery>
        <Count>1</Count>
    </Delivery>
    <Bills>
        <Bill>
            <InvoiceTypeCode>PCM</InvoiceTypeCode>
            <InvoiceNumber>INV-12345</InvoiceNumber>
            <EncodedDocument>JVBERi0xLjcNCiW1t......olJUVPRg==</EncodedDocument>
            <CustomerNumber>CUST-67890</CustomerNumber>
            <Name>John Doe</Name>
            <Street>Main Street</Street>
            <HouseNumber>42</HouseNumber>
            <PostalZone>12345</PostalZone>
            <CityName>Example City</CityName>
            <Country>CountryName</Country>
            <EmailAddress>johndoe@example.com</EmailAddress>
            <PaymentDueDate>2025-02-01</PaymentDueDate>
            <Currency>DKK</Currency>
            <ToBePayedAmount>123.45</ToBePayedAmount>
            <PaymentMeans>
                <TypeCodeID>BankTransfer</TypeCodeID>
                <PaymentChannelCode>OVERFØRSELSSERVICE</PaymentChannelCode>
                <ExtensibleContent>
                    <FarPay>
                        <PaymentMethod>Payout</PaymentMethod>
                        <Payout>
                            <SenderIdentifier scheme="BANK">rrrr:nnnnnnnn</SenderIdentifier>
                            <ReceiverIdentifier scheme="BANK">rrrr:nnnnnnnn</ReceiverIdentifier>
                        </Payout>                         
                    </FarPay>
                </ExtensibleContent>
            </PaymentMeans>
        </Bill>
    </Bills>
</FarPayXml>
```

### Payout Identifier Schemes

| Scheme | Description                    | Format          | Example         |
| ------ | ------------------------------ | --------------- | --------------- |
| `BANK` | Bank account details           | `rrrr:aaaaaaaa` | `1234:12345678` |
| `CVR`  | Company registration number    | 8 digits        | `12345678`      |
| `CPR`  | Personal identification number | 10 digits       | `0102889999`    |

### Payout Details

* **SenderIdentifier**: Optional - specify if you have multiple Overførselsservice creditors
* **ReceiverIdentifier**: Required - specifies where to send the money
* **Scheme**: Determines the format of the identifier

## Bill Properties

### Core Bill Properties

| Property          | Type    | Description                   | Required |
| ----------------- | ------- | ----------------------------- | -------- |
| `InvoiceTypeCode` | string  | Invoice type code             | Yes      |
| `InvoiceNumber`   | string  | Unique invoice number         | Yes      |
| `EncodedDocument` | string  | Base64 encoded PDF document   | Yes      |
| `CustomerNumber`  | string  | Customer reference number     | Yes      |
| `Name`            | string  | Customer name                 | Yes      |
| `Street`          | string  | Street address                | Yes      |
| `HouseNumber`     | string  | House/building number         | Yes      |
| `PostalZone`      | string  | Postal code                   | Yes      |
| `CityName`        | string  | City name                     | Yes      |
| `Country`         | string  | Country name                  | Yes      |
| `EmailAddress`    | string  | Customer email                | Yes      |
| `PaymentDueDate`  | date    | Payment due date (YYYY-MM-DD) | Yes      |
| `Currency`        | string  | Currency code                 | Yes      |
| `ToBePayedAmount` | decimal | Amount to be paid             | Yes      |

### Payment Means Properties (OS Bills)

| Property             | Type   | Description                          |
| -------------------- | ------ | ------------------------------------ |
| `TypeCodeID`         | string | Payment type (BankTransfer)          |
| `PaymentChannelCode` | string | Payment channel (OVERFØRSELSSERVICE) |
| `PaymentMethod`      | string | Method (Payout)                      |
| `SenderIdentifier`   | object | Sender bank details                  |
| `ReceiverIdentifier` | object | Receiver identification              |

## File Upload Process

### Two-Step Upload for Large Files

For large bill files, use the two-step upload process:

**Step 1: Create Delivery**

```json
{
  "DeliveryType": "Bill",
  "DeliveryFormat": "XML",
  "File": {
    "Filename": "large_bills.xml"
  }
}
```

**Step 2: Upload File**

```http
PUT {FileUploadUri}
```

**Required Headers:**

```
x-ms-blob-type: blockblob
Content-Type: application/octet-stream
```

## Implementation Examples

### JavaScript Example

```javascript
// Convert PDF to base64
const fs = require('fs');
const pdfContent = fs.readFileSync('invoice.pdf');
const base64Pdf = pdfContent.toString('base64');

// Create bill XML
const billXml = `<?xml version="1.0" encoding="UTF-8"?>
<FarPayXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://app.farpay.io/xsd/bills.xsd">
    <Delivery>
        <Count>1</Count>
    </Delivery>
    <Bills>
        <Bill>
            <InvoiceTypeCode>PCM</InvoiceTypeCode>
            <InvoiceNumber>INV-${Date.now()}</InvoiceNumber>
            <EncodedDocument>${base64Pdf}</EncodedDocument>
            <CustomerNumber>CUST-67890</CustomerNumber>
            <Name>John Doe</Name>
            <Street>Main Street</Street>
            <HouseNumber>42</HouseNumber>
            <PostalZone>12345</PostalZone>
            <CityName>Example City</CityName>
            <Country>Denmark</Country>
            <EmailAddress>johndoe@example.com</EmailAddress>
            <PaymentDueDate>2025-02-01</PaymentDueDate>
            <Currency>DKK</Currency>
            <ToBePayedAmount>123.45</ToBePayedAmount>
        </Bill>
    </Bills>
</FarPayXml>`;

// Convert XML to base64
const base64Xml = Buffer.from(billXml).toString('base64');

// Create delivery
const delivery = {
  DeliveryType: "Bill",
  DeliveryFormat: "XML",
  File: {
    Filename: "bills.xml",
    Data: base64Xml
  }
};

const response = await fetch('https://api.farpay.io/v2/deliveries', {
  method: 'POST',
  headers: {
    'X-API-KEY': 'your-api-key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(delivery)
});
```

### Python Example

```python
import base64
import requests

# Read PDF file
with open('invoice.pdf', 'rb') as pdf_file:
    pdf_content = pdf_file.read()
    base64_pdf = base64.b64encode(pdf_content).decode('utf-8')

# Create bill XML
bill_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<FarPayXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://app.farpay.io/xsd/bills.xsd">
    <Delivery>
        <Count>1</Count>
    </Delivery>
    <Bills>
        <Bill>
            <InvoiceTypeCode>PCM</InvoiceTypeCode>
            <InvoiceNumber>INV-12345</InvoiceNumber>
            <EncodedDocument>{base64_pdf}</EncodedDocument>
            <CustomerNumber>CUST-67890</CustomerNumber>
            <Name>John Doe</Name>
            <Street>Main Street</Street>
            <HouseNumber>42</HouseNumber>
            <PostalZone>12345</PostalZone>
            <CityName>Example City</CityName>
            <Country>Denmark</Country>
            <EmailAddress>johndoe@example.com</EmailAddress>
            <PaymentDueDate>2025-02-01</PaymentDueDate>
            <Currency>DKK</Currency>
            <ToBePayedAmount>123.45</ToBePayedAmount>
        </Bill>
    </Bills>
</FarPayXml>'''

# Convert XML to base64
base64_xml = base64.b64encode(bill_xml.encode('utf-8')).decode('utf-8')

# Create delivery
delivery = {
    "DeliveryType": "Bill",
    "DeliveryFormat": "XML",
    "File": {
        "Filename": "bills.xml",
        "Data": base64_xml
    }
}

response = requests.post(
    'https://api.farpay.io/v2/deliveries',
    headers={
        'X-API-KEY': 'your-api-key',
        'Content-Type': 'application/json'
    },
    json=delivery
)
```

## Error Handling

### Common Error Responses

| Status Code | Description                        |
| ----------- | ---------------------------------- |
| `400`       | Bad request - Invalid bill format  |
| `401`       | Unauthorized - Invalid API key     |
| `404`       | Not found - Delivery doesn't exist |

### Common Bill Errors

| Error                     | Description              | Solution                      |
| ------------------------- | ------------------------ | ----------------------------- |
| `Invalid XML structure`   | Malformed XML content    | Validate against XSD schema   |
| `Missing required fields` | Required data missing    | Check all required properties |
| `Invalid base64 encoding` | PDF not properly encoded | Ensure proper base64 encoding |
| `File too large`          | Bill file exceeds limits | Use two-step upload process   |

## Best Practices

1. **Validate XML structure** - Use the XSD schema for validation
2. **Proper base64 encoding** - Ensure PDF documents are correctly encoded
3. **Unique invoice numbers** - Use unique identifiers for each bill
4. **Handle large files** - Use two-step upload for files > 10MB
5. **Monitor processing** - Check delivery status after upload
6. **Test thoroughly** - Test with small files before production

## Related Endpoints

* [Deliveries](deliveries#) - General delivery management
* [Invoices](invoices#) - Invoice creation and management
* [Payments](payments#) - Payment tracking and processing

<br />