# Payments

Track payment history, process refunds, and monitor payment status across all payment methods. This section covers retrieving payment information and handling refunds for card payments.

## Overview

The Payments endpoint provides access to your complete payment history, allowing you to filter payments by date range, invoice, or payment reference. You can also process refunds for card payments and track payment status changes.

## API Endpoints

### Get All Payments

Retrieve payment history with optional filtering.

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

**Query Parameters:**

* `paymentDateFrom` (optional) - Start date for filtering (YYYY-MM-DD)
* `paymentDateTo` (optional) - End date for filtering (YYYY-MM-DD)
* `invoiceId` (optional) - Filter by specific invoice ID
* `refundId` (optional) - Filter by refund ID
* `paymentReference` (optional) - Filter by payment reference
* `paymentType` (optional) - Filter by payment type
* `pageSize` (optional) - Number of payments to retrieve (default: 100)
* `page` (optional) - Page number (0-based)

**Note:** Use either date range parameters OR invoiceId/refundId/paymentReference, not both.

**Response Example:**

```json
[
  {
    "InvoiceId": 123,
    "PaymentDate": "2023-01-15T10:30:00Z",
    "ToBePaidAmount": 125.50,
    "PaidAmount": 125.50,
    "PaymentType": "Visa",
    "PaymentStatus": "Paid",
    "PaymentId": 456,
    "RefundId": null,
    "PaymentSign": "Payment",
    "PaymentInfo": "Card payment processed",
    "ErrorDesription": null
  }
]
```

### Get Single Payment

Retrieve detailed information for a specific payment.

```http
GET https://api.farpay.io/v2/payments/{paymentId}
```

**Parameters:**

* `paymentId` (path) - The payment's unique identifier

**Response Example:**

```json
{
  "InvoiceId": 123,
  "PaymentDate": "2023-01-15T10:30:00Z",
  "ToBePaidAmount": 125.50,
  "PaidAmount": 125.50,
  "PaymentType": "Visa",
  "PaymentStatus": "Paid",
  "PaymentId": 456,
  "RefundId": null,
  "PaymentSign": "Payment",
  "PaymentInfo": "Card payment processed",
  "ErrorDesription": null
}
```

### Process Refund

Refund a card payment (only available for card payments).

```http
POST https://api.farpay.io/v2/payments/{paymentId}/refund
```

**Parameters:**

* `paymentId` (path) - The payment to refund

**Request Body:**

```json
{
  "Amount": 50.00
}
```

**Note:** Amount is optional. If not specified, a full refund will be processed.

## Payment Properties

### Core Properties

| Property          | Type     | Description                          | Format                |
| ----------------- | -------- | ------------------------------------ | --------------------- |
| `InvoiceId`       | integer  | Associated invoice ID                | Numeric               |
| `PaymentDate`     | datetime | Date payment was processed           | YYYY-MM-DDTHH:mm:ssZ  |
| `ToBePaidAmount`  | decimal  | Original amount to be paid           | 2 decimal places      |
| `PaidAmount`      | decimal  | Actual amount paid                   | 2 decimal places      |
| `PaymentType`     | string   | Payment method used                  | See Payment Types     |
| `PaymentStatus`   | string   | Current payment status               | See Payment Status    |
| `PaymentId`       | integer  | Unique payment identifier            | Numeric               |
| `RefundId`        | integer  | Associated refund ID (if applicable) | Numeric               |
| `PaymentSign`     | string   | Payment or refund indicator          | "Payment" or "Refund" |
| `PaymentInfo`     | string   | Additional payment information       | Text                  |
| `ErrorDesription` | string   | Error description (if any)           | Text                  |

## Payment Types

| Type         | Description                                           |
| ------------ | ----------------------------------------------------- |
| `FI`         | Payment slip (manual payment)                         |
| `BS`         | Betalingsservice (direct debit for private customers) |
| `LS`         | Leverandørservice (direct debit for businesses)       |
| `MP`         | MobilePay Payment or MobilePay Recurring              |
| `MPI`        | MobilePay Invoice                                     |
| `MRV`        | MínRokning Vinna                                      |
| `MRP`        | MínRokning Privat                                     |
| `Visa`       | Visa credit/debit card                                |
| `MasterCard` | MasterCard credit/debit card                          |
| `Dankort`    | Danish debit card                                     |

## Payment Status

| Status                  | Description                        |
| ----------------------- | ---------------------------------- |
| `Paid`                  | Payment successfully completed     |
| `PaymentRejected`       | Payment was rejected               |
| `ReimbursedByBank`      | Payment reimbursed by bank         |
| `PaymentOptionCanceled` | Payment option was canceled        |
| `PaymentFailed`         | Payment failed for various reasons |

## Payment Filtering

### Date Range Filtering

Filter payments by payment date range:

```http
GET https://api.farpay.io/v2/payments?paymentDateFrom=2023-01-01&paymentDateTo=2023-01-31
```

### Invoice Filtering

Filter payments by specific invoice:

```http
GET https://api.farpay.io/v2/payments?invoiceId=123
```

### Refund Filtering

Filter payments by refund ID:

```http
GET https://api.farpay.io/v2/payments?refundId=789
```

### Payment Reference Filtering

Filter payments by payment reference:

```http
GET https://api.farpay.io/v2/payments?paymentReference=PAY-REF-001
```

### Payment Type Filtering

Filter payments by payment type:

```http
GET https://api.farpay.io/v2/payments?paymentType=Visa
```

### Pagination

Use pagination for large result sets:

```http
GET https://api.farpay.io/v2/payments?pageSize=50&page=0
```

## Refund Processing

### Refund Requirements

* **Only card payments** can be refunded (Visa, MasterCard, Dankort)
* **Refund amount** must be less than or equal to the original payment amount
* **Refund amount** must be less than the remaining refundable amount
* **Amount format** must be in decimal format (e.g., 50.00)

### Refund Amount Calculation

| Currency | Format  | Example   |
| -------- | ------- | --------- |
| DKK      | Decimal | 50.00 DKK |
| EUR      | Decimal | 25.50 EUR |

### Refund Example

**Original Payment:** 125.50 DKK

**Partial Refund:** 50.00 DKK

```json
{
  "Amount": 50.00
}
```

**Full Refund:** 125.50 DKK

```json
{
  "Amount": 125.50
}
```

**Full Refund (no amount specified):**

```json
{}
```

### Refund Response

Successful refund returns the refund payment object:

```json
{
  "InvoiceId": 123,
  "PaymentDate": "2023-01-16T14:30:00Z",
  "ToBePaidAmount": 125.50,
  "PaidAmount": -50.00,
  "PaymentType": "Visa",
  "PaymentStatus": "Paid",
  "PaymentId": 789,
  "RefundId": 456,
  "PaymentSign": "Refund",
  "PaymentInfo": "Partial refund processed",
  "ErrorDesription": null
}
```

## Error Handling

### Common HTTP Status Codes

| Status Code | Description                                  |
| ----------- | -------------------------------------------- |
| `200`       | Success                                      |
| `400`       | Bad Request - Invalid parameters or amount   |
| `401`       | Unauthorized - Invalid or missing API key    |
| `403`       | Forbidden - Invoice not authorized           |
| `404`       | Not Found - Payment or invoice doesn't exist |
| `502`       | Bad Gateway - PSP or acquirer error          |

### Detailed Error Codes

| Error Code | Description                                                             |
| ---------- | ----------------------------------------------------------------------- |
| `20012`    | No amount to refund                                                     |
| `20013`    | No payments received                                                    |
| `20014`    | Payment was not found                                                   |
| `20050`    | Payment is not refundable                                               |
| `20040`    | PSP/Acquirer error (format: PSP: nnnn:message or Acquire: nnnn:message) |

### Error Response Examples

**Invalid refund amount:**

```json
{
  "error": "No amount to refund",
  "errorCode": 20012
}
```

**Payment not found:**

```json
{
  "error": "Payment was not found",
  "errorCode": 20014
}
```

**PSP Error:**

```json
{
  "error": "20040::PSP: 1001:Invalid card number",
  "errorCode": 20040
}
```

## Best Practices

### Payment Retrieval

1. **Use appropriate filters** - Filter by date range or specific criteria to reduce response size
2. **Implement pagination** - Use pageSize and page parameters for large datasets
3. **Cache payment data** - Payment information doesn't change frequently
4. **Handle empty responses** - Check for 204 status when no payments are found

### Refund Processing

1. **Validate refund eligibility** - Only card payments can be refunded
2. **Check refundable amount** - Ensure refund amount doesn't exceed original payment
3. **Handle partial refunds** - You can refund multiple times until amount is exhausted
4. **Monitor refund status** - Check payment status after refund processing

### Error Handling

1. **Implement retry logic** - Use exponential backoff for transient errors
2. **Log error details** - Include error codes and descriptions in logs
3. **Handle gateway errors** - PSP and acquirer errors may be temporary
4. **Validate responses** - Always check HTTP status codes and response content

## Use Cases

### Payment Reconciliation

```javascript
// Get all payments for a specific date range
const response = await fetch('https://api.farpay.io/v2/payments?paymentDateFrom=2023-01-01&paymentDateTo=2023-01-31', {
  headers: {
    'X-API-KEY': 'your-api-key',
    'Accept': 'application/json'
  }
});

const payments = await response.json();
const totalAmount = payments.reduce((sum, payment) => sum + payment.PaidAmount, 0);
console.log(`Total payments: ${totalAmount}`);
```

### Refund Processing

```javascript
// Process a partial refund
async function processRefund(paymentId, amount) {
  const response = await fetch(`https://api.farpay.io/v2/payments/${paymentId}/refund`, {
    method: 'POST',
    headers: {
      'X-API-KEY': 'your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ Amount: amount })
  });
  
  if (response.ok) {
    const refund = await response.json();
    console.log(`Refund processed: ${refund.PaymentId}`);
    return refund;
  } else {
    const error = await response.json();
    throw new Error(`Refund failed: ${error.error}`);
  }
}
```

### Payment Monitoring

```javascript
// Monitor failed payments
const response = await fetch('https://api.farpay.io/v2/payments?paymentType=Visa');
const payments = await response.json();
const failedPayments = payments.filter(payment => payment.PaymentStatus === 'PaymentFailed');

failedPayments.forEach(payment => {
  console.log(`Failed payment: ${payment.PaymentId} - ${payment.ErrorDesription}`);
});
```

## Related Endpoints

* [Payment Sets](payment-sets#) - Aggregated payment information
* [Invoices](invoices#) - Invoice and payment tracking
* [Agreements](agreements#) - Payment agreement management
* [Customers](customers#) - Customer information