# Orders

Orders are the foundation for creating payment flows and managing user interactions in FarPay. They control the user interface flow and enable customers to handle payments and create payment agreements.

## Overview

An **Order** is a container that manages the user interface flow for payments and agreements. When you create an order, you receive a unique token and a URL to the Payment Window where customers can complete their transactions.

## Order Flow

1. **Create Order** - POST to create an order with payment/agreement details
2. **Redirect Customer** - Send customer to the `UserInputUrl` from the response
3. **Customer Completes** - Customer completes payment/agreement in Payment Window
4. **Redirect Back** - Customer is redirected to your `AcceptUrl` or `CancelUrl`

## Order States

| State                     | Value | Description                                                  |
| ------------------------- | ----- | ------------------------------------------------------------ |
| **New**                   | 100   | Initial state when order is created                          |
| **PendingPayment**        | 200   | Payment received and matches invoice                         |
| **PendingCustomerNumber** | 300   | Customer has agreement, invoice scheduled                    |
| **Ok**                    | 400   | Scheduled payment being processed                            |
| **Error**                 | 500   | Payment rejected by user, creditor, or financial institution |
| **Canceled**              | 600   | Amount charged back, transaction reversed                    |
| **Expired**               | 700   | Payment failed due to agreement removal or low balance       |

![Order State Diagram](../images/uml-order/UML-Order-state.png)

## API Endpoints

### Get All Orders

Retrieve all orders with optional status filtering.

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

**Query Parameters:**

* `status` (optional) - Filter by order status (100, 160, 170, 190, 200, 300, 400)

- `status` (optional) - Filter by order status (100, 200, 300, 400, 500, 600, 700)

**Response Example:**

```json
[
  {
    "Token": "abc123",
    "ExternalID": "your-reference-001",
    "AcceptUrl": "https://company.com/accept",
    "CancelUrl": "https://company.com/cancel",
    "CallbackUrl": "https://company.com/callback",
    "Lang": "en",
    "Status": "New",
    "Customer": {
      "CustomerNumber": "12345",
      "CustomerName": "John Smith",
      "CustomerEmail": "john@example.com"
    },
    "Payment": {
      "Amount": 49.95,
      "Currency": "DKK",
      "Description": "Monthly subscription",
      "Reference": "PAY-REF-001",
      "AutoCapture": true
    },
    "Created": "2023-01-15T10:30:00Z"
  }
]
```

### Get Single Order

Retrieve detailed information for a specific order.

```http
GET https://api.farpay.io/v2/orders/{token}
```

**Parameters:**

* `token` (path) - The order's unique token

- `token` (path) - The order's unique token

### Create Order

Create a new order for payment or agreement creation.

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

## Order Scenarios

### Scenario 1: Payment Only

Use when customer should pay an amount without creating an agreement.

**Request Body:**

```json
{
  "ExternalID": "ORDER-001",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "Lang": "da",
  "Agreement": 0,
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  },
  "Payment": {
    "Amount": 49.95,
    "Currency": "DKK",
    "Description": "Monthly subscription payment",
    "Reference": "PAY-REF-001",
    "AutoCapture": true
  }
}
```

### Scenario 2: Agreement Required

Use when customer must create an agreement (with or without payment).

**With Payment:**

```json
{
  "ExternalID": "ORDER-002",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "Lang": "da",
  "Agreement": 1,
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  },
  "Payment": {
    "Amount": 49.95,
    "Currency": "DKK",
    "Description": "Initial payment",
    "Reference": "PAY-REF-002",
    "AutoCapture": true
  }
}
```

**Agreement Only:**

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

### Scenario 3: Optional Agreement

Use when customer should pay an amount with the option to create an agreement.

```json
{
  "ExternalID": "ORDER-004",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "Lang": "da",
  "Agreement": 2,
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  },
  "Payment": {
    "Amount": 49.95,
    "Currency": "DKK",
    "Description": "Monthly payment",
    "Reference": "PAY-REF-004",
    "AutoCapture": true
  }
}
```

### Scenario 4: Manual Capture

Use when you want to control when the payment is processed.

```json
{
  "ExternalID": "ORDER-005",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "Lang": "da",
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  },
  "Payment": {
    "Amount": 49.95,
    "Currency": "DKK",
    "Description": "Manual capture payment",
    "Reference": "PAY-REF-005",
    "AutoCapture": false
  }
}
```

## Order Properties

### Required Properties

| Property      | Type   | Description                   | Example                          |
| ------------- | ------ | ----------------------------- | -------------------------------- |
| `ExternalID`  | string | Your reference to the order   | "ORDER-001"                      |
| `AcceptUrl`   | string | URL for successful completion | "<https://company.com/accept>"   |
| `CancelUrl`   | string | URL for cancelled orders      | "<https://company.com/cancel>"   |
| `CallbackUrl` | string | URL for webhook notifications | "<https://company.com/callback>" |
| `Lang`        | string | Language code                 | "da", "en", "fo"                 |
| `Customer`    | object | Customer information          | See Customer object              |

### Optional Properties

| Property       | Type    | Description              | Values                               |
| -------------- | ------- | ------------------------ | ------------------------------------ |
| `Agreement`    | integer | Agreement requirement    | 0 (none), 1 (required), 2 (optional) |
| `Payment`      | object  | Payment information      | See Payment object                   |
| `PaymentTypes` | string  | Restrict payment methods | "bs,card", "mp", etc.                |

### Customer Object

| Property         | Type   | Description                |
| ---------------- | ------ | -------------------------- |
| `CustomerNumber` | string | Unique customer identifier |
| `CustomerName`   | string | Customer's full name       |
| `CustomerEmail`  | string | Customer's email address   |

### Payment Object

| Property      | Type    | Description                            | Default  |
| ------------- | ------- | -------------------------------------- | -------- |
| `Amount`      | decimal | Payment amount (use . for decimals)    | Required |
| `Currency`    | string  | Currency in ISO 4217 format            | Required |
| `Description` | string  | Payment description                    | Required |
| `Reference`   | string  | Your payment reference                 | Required |
| `AutoCapture` | boolean | Whether to capture payment immediately | true     |

## AutoCapture Property

The `AutoCapture` property controls when payments are processed:

* **`AutoCapture: true`** (default) - Payment is captured immediately when customer enters payment details
* **`AutoCapture: false`** - Payment is only authorized/reserved, requiring manual capture

### Manual Capture Flow

When `AutoCapture: false` is set:

1. **Create Order** with `AutoCapture: false`
2. **Customer completes payment** - Order status becomes `PendingCapture`
3. **Manual Capture** - Call capture endpoint to process payment
4. **Payment processed** - Order status becomes `Processing` then `Ok`

For detailed information about manual capture, see [Capture Orders](capture-orders.md).

## Payment Type Filtering

Restrict available payment methods using the `PaymentTypes` property:

| Type   | Description                                           |
| ------ | ----------------------------------------------------- |
| `bs`   | Betalingsservice (direct debit for private customers) |
| `ls`   | Leverandørservice (direct debit for businesses)       |
| `mp`   | MobilePay (both Invoice and Subscriptions)            |
| `card` | Dankort, Visa, MasterCard                             |

**Example:** `"PaymentTypes": "bs,card"` - Only Betalingsservice and cards available

## Order Response

All order creation requests return the same response structure:

```json
{
  "Status": "New",
  "Token": "abc123def456",
  "ExternalID": "ORDER-001",
  "AcceptUrl": "https://company.com/accept",
  "CancelUrl": "https://company.com/cancel",
  "CallbackUrl": "https://company.com/callback",
  "UserInputUrl": "https://app.farpay.io/payment/abc123def456",
  "Lang": "da",
  "PaymentTypes": "Mp,Invoice,Bs",
  "Agreement": 1,
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  },
  "Payment": {
    "Amount": 49.95,
    "Currency": "DKK",
    "Description": "Monthly subscription",
    "Reference": "PAY-REF-001",
    "AutoCapture": true
  },
  "Created": "2023-01-15T10:30:00Z"
}
```

## Update Order

Update customer information for an existing order in "PendingCustomerNumber" state.

```http
PUT https://api.farpay.io/v2/orders
```

**Request Body:**

```json
{
  "Token": "abc123def456",
  "Customer": {
    "CustomerNumber": "12345",
    "CustomerName": "John Smith",
    "CustomerEmail": "john@example.com"
  }
}
```

## Order Management

### Capture Orders

For orders created with `AutoCapture: false`, you can manually capture payments when ready.

```http
GET https://api.farpay.io/v2/orders/{token}/capture
```

See [Capture Orders](capture-orders.md) for detailed information.

### Cancel Orders

Cancel orders that are in specific states to roll back transactions.

```http
GET https://api.farpay.io/v2/orders/{token}/cancel
```

See [Cancel Orders](cancel-orders.md) for detailed information.

## Best Practices

1. **External IDs**: Use meaningful, unique identifiers for tracking orders
2. **URLs**: Ensure AcceptUrl and CancelUrl are accessible and handle responses properly
3. **Language**: Set appropriate language for your customer base
4. **Payment Types**: Restrict payment methods when appropriate to simplify customer choice
5. **AutoCapture**: Use manual capture when you need control over payment timing
6. **Error Handling**: Implement proper error handling for all redirect URLs

## Integration Flow

1. **Create Order** - POST order details to create payment flow
2. **Redirect Customer** - Send customer to `UserInputUrl` from response
3. **Customer Completes** - Customer completes payment/agreement in Payment Window
4. **Handle Response** - Customer redirected to AcceptUrl or CancelUrl
5. **Process Result** - Handle success/failure in your application
6. **Manual Actions** - Capture or cancel orders as needed

## Related Resources

* [Capture Orders](capture-orders.md) - Manual payment capture
* [Cancel Orders](cancel-orders.md) - Order cancellation
* [Customers](customers.md) - Manage customer information
* [Agreements](agreements.md) - Handle payment instruments
* [Payments](payments.md) - Track payment history
* [Payment Window](https://github.com/FarPay/PaymentWindow) - Custom payment interface
* [Customers](customers#) - Manage customer information
* [Agreements](agreements#) - Handle payment instruments
* [Payments](payments#) - Track payment history

# Orders

The Orders-endpoint is used to manage the creation and maintainance of Agreements and Payments that require a user/customer interaction.

The order is the term, that controls the user-interface-flow, enabling the user to handle the given task at hand. A full screen-to-process flow is found in [FarPay Payment Window](https://github.com/FarPay/PaymentWindow/blob/master/README.md).

To have a user create a new Agreement or Payment, you must first create an `Order` by posting a model to this endpoint. The returned result is an `Order`-result model, that includes a unique Token to reference the `Order`, and  the `UserInputUrl` to the Payment Window.

Subsequently after the order has been created, the user must be redirect to this Payment Window, specified in the `UserInputUrl`.

Now, after the user completion of the Agreement and/or the Payment, in the PaymentWindow, the user will be redirected back the the `AcceptUrl` that was defined when creating the Order. If the user cancels the process before it is compleated, FarPay will redirect the user to the `CancelUrl`.

The invoice endpoint `https://api.farpay.io/{version}/orders` gives you access to all your orders, and their state. Use Case scenarios are:

* List orders with optional status filter
* Single order (deep view)
* Create an order
* Update the order (With customer data)

**Remark!** that [all requests must have](how-to-use) an `X-API-KEY` and `Accept` mentioned in the header requests.

# Order status

![State diagram of the order](../images/uml-order/UML-Order-state.png)

| State                 | value | Brief description                                                                                        |
| --------------------- | ----- | -------------------------------------------------------------------------------------------------------- |
| New                   | 100   | Initial state                                                                                            |
| PendingPayment        | 200   | When a payment as been received and matches the invoice                                                  |
| PendingCustomerNumber | 300   | The customer has an agreement, and the invoice will be marked as scheduled                               |
| Ok                    | 400   | The scheduled payment is now being processed                                                             |
| Error                 | 500   | The payment is being rejected by user, creditor or financial institution                                 |
| Canceled              | 600   | The amount is charged back, as the monitary transaction is reversed by creditor or finansial institution |
| Expired               | 700   | Paymnet failed of various causes such as, agreement was removed, or due to low account balance           |

# Get all orders

The endpoint is available from an`HTTP_GET` at `https://api.farpay.io/{version}/orders`, and can be filtered statusvalues mentioned in the table above.

Here is an example of a collection with an order - Remark that this is an example presented in JSON, and that the data can be presented as SOAP XML if requested...

```javascript
[
  {
    "Token": "abc123",
    "ExternalID": "your reference",
    "AcceptUrl": "https://companyName.com/acceptUrl",
    "CancelUrl": "https://companyName.com/cancelUrl",
    "CallbackUrl": "https://companyName.com/callbackUrl",
    "Lang": "en",
    "Customer": {
       "CustomerNumber": "1234567890",
       "CustomerName": "Customer Name",
       "CustomerEmail": "email@address.com"
    },
    "Payment": {
      "Amount": 49.95,
      "Currency": "DKK",
      "Description": "First half month payment",
      "Reference": "YourPaymentReference"
    }
  }
]
```

| Property            | Description                                                                       | Valid values |
| ------------------- | --------------------------------------------------------------------------------- | ------------ |
| Token               | FarPay unique token to the order                                                  | `string`     |
| ExternalID          | Your domain reference to the order in FarPay                                      | `string`     |
| AcceptUrl           | Url, when the order is successfully completed                                     | `string`     |
| CancelUrl           | Url, when the user cancels the order                                              | `string`     |
| CallbackUrl         | Url for delivery data when the user completes the registration                    | `string`     |
| Lang                | Language specification can be `en` for english, `da` for danshh, `fo` for faroese | `string`     |
| CustomerNumber      | Customer number                                                                   | `string`     |
| CustomerName        | Name (first and last) of the customer                                             | `string`     |
| CustomerEmail       | Customer E-mail                                                                   | `string`     |
| Payment-Amount      | Payment with . seperator for decimals                                             | `decimal`    |
| Payment-Currency    | Currency in standard ISO 4217 format                                              | `string`     |
| Payment-Description | Describe what the customer is paying for                                          | `string`     |
| Payment-Reference   | Your domain reference to the payment                                              | `string`     |

# Single order

Get an `Order`-object, based on a `Token` from an `HTTP_GET` at `https://api.farpay.io/{version}/orders/{token}`
The order properties are the same as mentioned in the property table above.

# Create order

When creating an Order, there are two properties that will manage the outcome of how the PaymentWindow render. First is the presence of an agreement that will hold the values:

* 0 - Meaning not applicable
* 1 - Required
* 2 - Optional

Remark that when an existing customer already has an agreement (with a specific type) attached, the Optional value (2), will not result in a render of the agreement possibility, when the agreement type wanted is the *same type* as the current. This precaution is made to mitigate the behavior that customers repeatedly complete the same registration over and over again.

Second property is the `PaymentType` that can reduce the flow options accordingly. When not specified, all available PaymentTypes will be exposed as valid options.
A reduction can be specified with a comma seperated string with the wanted payment types:

```
  PaymentTypes = 'bs,card'
```

For Betalingsservice and MobilePay.

The available paymentTypes filters are:

* bs - Betalingsservice
* ls - Leverandørservice
* mp - MobilePay (both MobilePay Invoice and MobilePay Subscriptions)
* card - Dankort, Visa and/or MasterCard.

A `Payment` can also be You can also be include inside the Order, where you specify an Amount and Currency.

An Order can have the following combinations of Agreement and Payment:

| Scenario | Agreement                    | Payment                        | No payment       |
| -------- | ---------------------------- | ------------------------------ | ---------------- |
| 1        | Agreement not applicable (0) | Single Payment                 | N/A              |
| 2        | Agreement required (1)       | Create Agreement and Payment   | Create Agreement |
| 3        | Agreement optional (2)       | Payment and optional Agreement | N/A              |

A new `Order` can be created an `HTTP_POST` at `https://api.farpay.io/{version}/orders`.
The order is created, and returned with a `Token`, as well as a link to the form, that the user can input the payment information in.

Here are the examples, from the scenarios above:

## Scenario 1: Create order for a payment

This scenario should be used, when the customer should pay an amout, and not create an agreement.

A JSON payload:

```javascript
{
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "Lang": "da",
  Agreement: 0,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  },
  "Payment": {
    "Amount": 4.50,
    "Currency": "DKK",
    "Description": "Betaling for den første måned",
    "Reference": "DOMAIN_BETALING_123456"
  }
}
```

## Scenario 2: The agreement required, with a payment

This scenario covers two scenarios. In both cases the agreement is required, but in the first, the payment is required too.

**JSON Payload, required agreement and required payment**

This is typically used when the customer must create an agreement, as well as handling a payment - In some cases the initial payment.

```javascript
{
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "Lang": "da",
  "Agreement": 1,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  },
  "Payment": {
    "Amount": 4.50,
    "Currency": "DKK",
    "Description": "Betaling for den første måned",
    "Reference": "DOMAIN_BETALING_123456"
  }
}
```

**JSON Payload, required agreement and no payment:**

This typically holds the scenario, where the customer must create an agreement only.

```javascript
{
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "Lang": "da",
  "Agreement": 1,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  }
}
```

## Scenario 3: Optional Agreement and Payment

This scenario plays out when there is an amount that must be paid. The user is presented with the option, in addition to the payment, also to create an agreement.

```javascript
{
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "Lang": "da",
  "Agreement": 2,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  },
  "Payment": {
    "Amount": 4.50,
    "Currency": "DKK",
    "Description": "Betaling for den første måned",
    "Reference": "DOMAIN_BETALING_123456"
  }
}
```

## Scenario 4: Amdatory Agreement, no payment

Use this when you only want the customer to create an agreement.

Remark, if you want to manage the process, and give the customer a single option - e.g. payment card, you would add the `"PaymentTypes" = "card"` to the root note.
When `"PaymenTypes"` are not set, the customer will select between the available payment options, and then create the agreement on the selected type.

```javascript
{
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "Lang": "da",
  "Agreement": 1,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  }
}
```

## Result (all scenarios above)

Bear in mind that this result represents all the scenarios where the agreement can be present as an optional or a mandatory property, to that the Payment is only present when initially requested.

```Javascript
{
  "Status": "New | PendingPayment | PendingCustomer | Ok | Error | Canceled | Expired",
  "Token": "<token>",
  "ExternalID": "DOMAIN_REFERENCE-002",
  "AcceptUrl": "https://myCompany.com/accept",
  "CancelUrl": "https://myCompany.com/cancel",
  "CallbackUrl": "https://myCompany.com/callback",
  "UserInputUrl": "https://app.farpay.io/payment/<token>",
  "Lang": "da",
  "PaymentTypes": "Mp,Invoice,Bs",
  "Agreement": 0 | 1 | 2,
  "Customer": {
     "CustomerNumber": "999918",
     "CustomerName": "My name and lastname",
     "CustomerEmail": "person@myCompany.dk"
  },
  "Payment": {
    "Amount": 4.50,
    "Currency": "DKK",
    "Description": "Betaling for den første måned",
    "Reference": "DOMAIN_BETALING_123456"
  },
  "Created": "2018-10-30T10:36:09.115Z"
}
```

# Update Order

For clarity, earlier examples the `Customer` was included in the [Create Order](orders#) documentation above. But in fact, the customer is not required to be known at the point when the `Order` is created.

In these scenarios, the domain system will have the customer information later on the process and can therefore also propagate these information to the order for final completion.
In this state (`Pending Customer Number`), which means that the order might be completed with the user interaction, relating to both payment and creating an agreement, it still lacks the actual customer. This endpoint provides exactly that!
When the customer is updated, the order is processed as planned. The agreement data, and the paymentdata (if any) are propagated into the formal model and structure of a `Customer`, `Agreement` and `Payment` when applicable in the order.

The endpoint is available as a `HTTP_PUT` from `https://api.farpay.io/{version}/orders` where the the order must contain a customer, that can be formalized into a strong type customer.
The values, that are received are:

* CustomerNumber
* CustomerName
* CustomerEmail

```
{
  "Token": "<token>",
  "Customer": {
    "CustomerNumber": "999918",
    "CustomerName": "My name and lastname",
    "CustomerEmail": "person@myCompany.dk"
  }
}
```