# Agreements

Manage recurring payment instruments (agreements) that enable automatic payments from your customers. This section covers creating, monitoring, and canceling payment agreements for various payment methods.

## Overview

**Agreements** are recurring payment instruments that allow customers to pay invoices automatically. They can be created for bank-based direct debits (Betalingsservice/Leverandørservice) via API, while card agreements require secure customer interaction.

## Agreement Types

| Type                  | Code | Description                        | Customer Type       |
| --------------------- | ---- | ---------------------------------- | ------------------- |
| **Betalingsservice**  | BS   | Direct debit for private customers | Private individuals |
| **Leverandørservice** | LS   | Direct debit for businesses        | Businesses only     |
| **Card**              | Card | Credit/debit card agreements       | All customers       |
| **MobilePay**         | MP   | MobilePay subscription agreements  | All customers       |

## Agreement States

| State       | Description                                      |
| ----------- | ------------------------------------------------ |
| **Pending** | Initial state while agreement is being processed |
| **Ok**      | Agreement is active and ready for payments       |
| **Cancel**  | Agreement has been canceled                      |
| **Error**   | Agreement creation failed                        |

![Agreement States](../images/api_agreement_states.jpg)

**Note:** Processing time varies by agreement type:

* **Cards & MobilePay**: Created instantly
* **BS/LS**: Processed in batches during evening/night hours

## API Endpoints

### Get All Agreements

Retrieve all payment agreements for your customers.

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

**Response Example:**

```json
[
  {
    "Id": 1,
    "Type": "Card",
    "Status": "Ok",
    "CustomerNumber": "12345",
    "PayerID": "",
    "Details": "Card|Visa|4444xxxxxxxx1234|12/25",
    "StartDate": "2023-01-15T10:30:00Z",
    "ExpireDate": "2025-12-31T23:59:59Z"
  },
  {
    "Id": 2,
    "Type": "BS",
    "Status": "Ok",
    "CustomerNumber": "67890",
    "PayerID": "1234567890",
    "Details": "12345678",
    "StartDate": "2023-01-15T10:30:00Z",
    "ExpireDate": ""
  }
]
```

### Get Single Agreement

Retrieve detailed information for a specific agreement.

```http
GET https://api.farpay.io/v2/agreements/{id}
```

**Parameters:**

* `id` (path) - The agreement's unique identifier

### Create Agreement

Create a new bank-based agreement (BS or LS only).

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

**Request Body:**

```json
{
  "BankRegNumber": "1234",
  "BankAccountNumber": "12345678",
  "Type": "BS",
  "CustomerNumber": "12345",
  "PayerID": "1234567890"
}
```

### Cancel Agreement

Cancel an existing agreement.

```http
DELETE https://api.farpay.io/v2/agreements/{id}
```

**Parameters:**

* `id` (path) - The agreement's unique identifier

## Agreement Properties

### Core Properties

| Property         | Type     | Description                               |
| ---------------- | -------- | ----------------------------------------- |
| `Id`             | integer  | Unique agreement identifier               |
| `Type`           | string   | Agreement type (BS, LS, Card, MP)         |
| `Status`         | string   | Current agreement status                  |
| `CustomerNumber` | string   | Associated customer number                |
| `PayerID`        | string   | Payer identification number               |
| `Details`        | string   | Agreement details (format varies by type) |
| `StartDate`      | datetime | Agreement start date                      |
| `ExpireDate`     | datetime | Agreement expiration date (if applicable) |

### Agreement Details by Type

| Type     | PayerID      | Details Format      | Example    |              |       |                  |        |
| :------- | :----------- | :------------------ | :--------- | :----------- | :---- | :--------------- | :----- |
| **BS**   | CPR number   | Bank account number | "12345678" |              |       |                  |        |
| **LS**   | CVR number   | Bank account number | "12345678" |              |       |                  |        |
| **Card** | Not required | CardType            | Mask       | Expiry       | "Visa | 4444xxxxxxxx1234 | 12/25" |
| **MP**   | Not required | MobilePay info      | "MobilePay | +4512345678" |       |                  |        |

## Creating Bank Agreements

### Betalingsservice (BS) Agreement

For private customers with Danish CPR numbers.

**Request Body:**

```json
{
  "BankRegNumber": "1234",
  "BankAccountNumber": "12345678",
  "Type": "BS",
  "CustomerNumber": "12345",
  "PayerID": "1234567890"
}
```

**Requirements:**

* `BankRegNumber`: 4-digit Danish bank registration number
* `BankAccountNumber`: 7-8 digit account number
* `PayerID`: Danish CPR number (10 digits)
* `CustomerNumber`: Must match existing customer

### Leverandørservice (LS) Agreement

For businesses with Danish CVR numbers.

**Request Body:**

```json
{
  "BankRegNumber": "1234",
  "BankAccountNumber": "12345678",
  "Type": "LS",
  "CustomerNumber": "12345",
  "PayerID": "12345678"
}
```

**Requirements:**

* `BankRegNumber`: 4-digit Danish bank registration number
* `BankAccountNumber`: 7-8 digit account number
* `PayerID`: Danish CVR number (8 digits)
* `CustomerNumber`: Must match existing customer

## Card and MobilePay Agreements

Card and MobilePay agreements cannot be created directly via API due to security requirements. They must be created through:

1. **Customer interaction** in the Payment Window
2. **Email invitations** sent to customers
3. **Order creation** with agreement requirements

### Creating Card Agreements via Orders

```json
{
  "ExternalID": "AGREEMENT-001",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "Lang": "da",
  "Agreement": 1,
  "PaymentTypes": "card",
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  }
}
```

## Agreement Management

### Finding Customer Agreements

Agreements are linked to customers and can be found in the customer endpoint:

```http
GET https://api.farpay.io/v2/customers/{customerNumber}
```

**Response includes agreements:**

```json
{
  "CustomerNumber": "12345",
  "Name": "John Smith",
  "Email": "john@example.com",
  "Agreements": [
    {
      "Id": 1,
      "Type": "Card",
      "Status": "Ok",
      "Details": "Visa|4444xxxxxxxx1234|12/25"
    }
  ]
}
```

### Canceling Agreements

When an agreement is canceled:

1. **Future invoices** scheduled for automatic payment become manual invoices
2. **Manual invoices** receive an `FI` (Faktura) payment type
3. **Customer notification** is sent about the cancellation

**Cancel Agreement:**

```http
DELETE https://api.farpay.io/v2/agreements/1
```

## Agreement Validation

### Bank Account Validation

The relationship between bank account and PayerID is critical:

* **BS agreements**: PayerID (CPR) must match the account owner
* **LS agreements**: PayerID (CVR) must match the business account owner
* **Validation**: Financial institutions verify this relationship
* **Rejection**: Agreements are rejected if no match is found

### Business vs Private Accounts

* **Betalingsservice**: Can hold both private and business accounts
* **Leverandørservice**: Business accounts only
* **Account type**: Must match the agreement type

## Best Practices

1. **Customer Verification**: Ensure customer exists before creating agreements
2. **Bank Information**: Verify bank account details with customers
3. **PayerID Validation**: Confirm CPR/CVR numbers are correct
4. **Agreement Monitoring**: Regularly check agreement status
5. **Cancellation Handling**: Implement proper cancellation workflows
6. **Error Handling**: Monitor failed agreement creations

## Error Handling

Common agreement-related errors:

| Error                      | Description                         | Solution                  |
| -------------------------- | ----------------------------------- | ------------------------- |
| `Customer not found`       | Invalid customer number             | Verify customer exists    |
| `Invalid bank information` | Wrong bank account details          | Check with customer       |
| `PayerID mismatch`         | PayerID doesn't match account owner | Verify CPR/CVR number     |
| `Agreement already exists` | Customer already has agreement      | Check existing agreements |
| `Invalid agreement type`   | Unsupported agreement type          | Use BS, LS, Card, or MP   |

## Integration Examples

### Create BS Agreement

```javascript
// Create Betalingsservice agreement
const agreement = {
  BankRegNumber: "1234",
  BankAccountNumber: "12345678",
  Type: "BS",
  CustomerNumber: "12345",
  PayerID: "1234567890"
};

try {
  const response = await fetch('/agreements', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'your-api-key'
    },
    body: JSON.stringify(agreement)
  });
  
  console.log('Agreement created:', response);
} catch (error) {
  console.error('Agreement creation failed:', error);
}
```

### Monitor Agreement Status

```javascript
// Check agreement status
const agreements = await fetch('/agreements');
const activeAgreements = agreements.filter(a => a.Status === 'Ok');

console.log(`Active agreements: ${activeAgreements.length}`);

// Check for pending agreements
const pendingAgreements = agreements.filter(a => a.Status === 'Pending');
if (pendingAgreements.length > 0) {
  console.log('Pending agreements:', pendingAgreements);
}
```

### Cancel Agreement

```javascript
// Cancel agreement
const agreementId = 1;

try {
  await fetch(`/agreements/${agreementId}`, {
    method: 'DELETE',
    headers: {
      'X-API-KEY': 'your-api-key'
    }
  });
  
  console.log('Agreement canceled successfully');
} catch (error) {
  console.error('Agreement cancellation failed:', error);
}
```

## Related Resources

* [Customers](customers#) - Manage customer information
* [Orders](orders#) - Create payment flows and agreements
* [Payments](payments#) - Track payment history
* [Invoices](invoices#) - Generate invoices for customers

<br />