> For the complete documentation index, see [llms.txt](https://developer.esw.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/checkout.md).

# Checkout

Send a PreOrder, redirect to ESW Checkout, and handle the Order Confirmation webhook.

In the Checkout flow, your site sends a cart to ESW as a **PreOrder**. ESW returns a checkout URL. After payment, ESW sends an **Order Confirmation** webhook to your server. This quick start runs the full flow in sandbox.

**Time:** 30 to 45 minutes

**Environment:** sandbox

### Before you begin

* Your `tenantCode`
* Sandbox client credentials with the `checkout.preorder.api.all` scope. If you have not requested a token yet, follow [Quick start: Authentication](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/authentication.md)
* A publicly reachable HTTPS endpoint that can receive a `POST` from ESW. In sandbox you can point ESW at it per request, so no ESW configuration is needed

{% stepper %}
{% step %}

#### Get an access token

Use the request from [Quick start: Authentication](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/authentication.md), but replace its `scope` value with `checkout.preorder.api.all`. Store the returned token and tenant code:

```sh
export ESW_TOKEN="<access_token>"
export ESW_TENANT_CODE="<tenantCode>"
```

{% endstep %}

{% step %}

#### Stand up your Order Confirmation endpoint

ESW sends a `POST` with the order payload to your webhook each time a shopper completes an order. Your endpoint authenticates the request, creates the order in your system, and returns a `2xx` response. It can return your own order number. Design it for duplicate deliveries.

{% code expandable="true" %}

```js
import express from "express";

const app = express();
app.use(express.json());

const processed = new Map(); // Delivery key -> orderNumber. Use a durable store in production.

app.post("/eventSink", async (req, res) => {
  // Authenticate: the header must match the credentials configured for this webhook.
  if (req.get("Authorization") !== process.env.ESW_WEBHOOK_AUTH) {
    return res.sendStatus(401);
  }

  // Asynchronous delivery has an Idempotency-Key. Synchronous delivery does not.
  // RetailerCartId stays stable across synchronous retries.
  const key = req.get("Idempotency-Key") ?? `sync:${req.body.RetailerCartId}`;
  if (processed.has(key)) {
    return res.status(200).json({ orderNumber: processed.get(key) });
  }

  // req.body.RetailerCartId matches the retailerCartId you sent in the PreOrder.
  const orderNumber = await createOrderInYourSystem(req.body); // your logic, returns your order number

  processed.set(key, orderNumber);
  res.status(200).json({ orderNumber });
});

app.listen(3000);
```

{% endcode %}

Create sandbox Basic-auth credentials before sending the request. Set `ESW_WEBHOOK_AUTH` to `Basic <base64(username:password)>`. Copy the Base64 output below, without the `Basic` prefix, into `OrderConfirmationBase64EncodedAuth_TestOnly`.

```sh
export ESW_WEBHOOK_USER="<username>"
export ESW_WEBHOOK_PASSWORD="<password>"
printf '%s' "$ESW_WEBHOOK_USER:$ESW_WEBHOOK_PASSWORD" | base64
```

The full payload also carries pricing, payment, delivery, and contact data. See [Order Confirmation Webhook](https://developer.esw.com/checkout-api/resources/order-confirmation-webhook.md) for every field.

{% hint style="warning" %}
A `4xx` or `5xx` response from your endpoint marks the order as canceled. Test its reachability and authentication before payment. ESW retries transport failures three times, after 1.25, 1.5, and 2 seconds. Make the handler safe for redelivery.
{% endhint %}

If you return an `orderNumber`, ESW shows it on the confirmation page. If you omit it, ESW uses the PreOrder's `retailerCartId`. Keep this number aligned with your order system.

{% hint style="info" %}
The example uses an in-memory map for clarity. In production, persist idempotency records and make the create-and-record operation atomic. This prevents duplicate orders when deliveries overlap or your service restarts.
{% endhint %}
{% endstep %}

{% step %}

#### Send the PreOrder

Save this request body as `preorder.json`. It contains the required fields plus the sandbox override that points ESW at your webhook.

{% code expandable="true" %}

```json
{
  "retailerCartId": "CART-100045",
  "deliveryCountryIso": "DE",
  "shopperCurrencyIso": "EUR",
  "retailerCurrencyIso": "GBP",
  "lineItems": [
    {
      "lineItemId": "1",
      "quantity": 1,
      "product": {
        "productCode": "SKU-00123",
        "title": "Classic Leather Wallet",
        "description": "Slim bifold wallet in full-grain cowhide leather",
        "productUnitPriceInfo": {
          "price": { "currency": "GBP", "amount": "89.95" }
        }
      }
    }
  ],
  "retailerCheckoutExperience": {
    "metadataItems": [
      {
        "name": "OrderConfirmationUri_TestOnly",
        "value": "https://your-sandbox-host.example.com/eventSink"
      },
      {
        "name": "OrderConfirmationBase64EncodedAuth_TestOnly",
        "value": "<base64 output from the previous step>"
      }
    ]
  }
}
```

{% endcode %}

Send it to the Checkout API:

```sh
curl --request POST "https://api.sandbox.esw.com/checkout/api/v3/$ESW_TENANT_CODE/PreOrder" \
  --header "Authorization: Bearer $ESW_TOKEN" \
  --header "Content-Type: application/json" \
  --data @preorder.json
```

ESW validates the cart and returns `201 Created`:

```json
{
  "preOrderCode": "<preOrderCode>",
  "orderNumber": "<provisional order number>",
  "redirectUrl": "<checkout url>",
  "shopperAccessToken": null
}
```

| Field                | Description                                                                                                     |
| -------------------- | --------------------------------------------------------------------------------------------------------------- |
| `preOrderCode`       | Unique PreOrder code                                                                                            |
| `orderNumber`        | Provisional order number generated by ESW                                                                       |
| `redirectUrl`        | Checkout URL to send the shopper to                                                                             |
| `shopperAccessToken` | JWT for stored payment cards. Returned only for registered shoppers with stored cards enabled, otherwise `null` |

**Required fields:** `retailerCartId`, `deliveryCountryIso` (two-letter ISO 3166), and at least one `lineItems` entry. Each product needs `productCode`, `title`, `description`, and `productUnitPriceInfo.price`. Send the price `currency` as a three-letter ISO 4217 code and its `amount` as a **string**. Set `shopperCurrencyIso` and `retailerCurrencyIso` too. They are optional, but ESW strongly recommends them.

{% hint style="info" %}
The `OrderConfirmationUri_TestOnly` override works only in test environments such as sandbox. It does not apply to asynchronous Order Confirmation, which ESW configures for you. `metadataItems` values must be agreed with ESW.
{% endhint %}
{% endstep %}

{% step %}

#### Redirect the shopper

Send the shopper to the `redirectUrl` from the PreOrder response. Do not construct this URL yourself. A server-side redirect is the simplest option.

```js
app.post("/checkout", async (req, res) => {
  const preOrder = await sendPreOrder(req.session.cart); // calls the PreOrder endpoint
  res.redirect(preOrder.redirectUrl);
});
```

{% endstep %}

{% step %}

#### Complete a test payment

Open the `redirectUrl`, review the order, enter shipping and billing details, and pay with a test card from [Test Cards](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/test-cards.md). Start with a non-3DS card, then try a 3DS card to see the authentication step.
{% endstep %}

{% step %}

#### Verify the result

Confirm all three of these:

* Your webhook endpoint received the `POST` and returned `200`
* The order exists in your system
* The shopper sees the confirmation page showing your order number, or the `retailerCartId` if you did not return one

Use the `preOrderCode` from the PreOrder response and `retailerCartId` to correlate logs across the flow.
{% endstep %}
{% endstepper %}

### Synchronous and asynchronous confirmation

Both modes use the same payload and response format. They differ in timing.

|                                    | Synchronous (default)                                    | Asynchronous                                                                               |
| ---------------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Shopper sees the confirmation page | After your endpoint responds and ESW finishes processing | Immediately after successful payment                                                       |
| Sandbox setup                      | Per request with `OrderConfirmationUri_TestOnly`         | ESW configures it. Do not send the overrides                                               |
| Extra headers                      | None                                                     | `Esw-Delivery`, `Esw-Event-Type`, `Idempotency-Key`                                        |
| De-duplication                     | Make the handler safe for redelivery                     | Use `Idempotency-Key`, which stays the same across retries                                 |
| No response from your endpoint     | Retries three times, then the order is canceled          | Retries three times over about two minutes, then ESW cancels the order and issues a refund |

To enable asynchronous processing, contact your ESW representative.

### Common errors

| Symptom                                           | Likely cause                                                   | Fix                                                                                                                                                                   |
| ------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` with a list of `code` and `message` entries | A required field is missing or a value is invalid              | Fix the fields named in the errors. See [Response Status Codes (Validation)](https://developer.esw.com/checkout-api/checkout-api/response-status-codes-validation.md) |
| `401`                                             | Token missing, malformed, or expired                           | Request a new token and resend                                                                                                                                        |
| `403`                                             | Token lacks the `checkout.preorder.api.all` scope              | Request a token with that scope                                                                                                                                       |
| `429`                                             | Too many requests                                              | Wait for the `Retry-After` interval, then retry                                                                                                                       |
| `500`                                             | Unexpected server error                                        | Retry with backoff. Contact ESW if it persists                                                                                                                        |
| Webhook never called in sandbox                   | Override metadata missing, misspelled, or endpoint unreachable | Names are case-sensitive. Check that the URL is public HTTPS                                                                                                          |
| Order canceled after payment                      | Your endpoint returned `4xx` or `5xx`, or did not respond      | Check your logs. ESW also logs every request it sends to your webhook                                                                                                 |

### Field notes

* Send `quantity` on every line item.
* If you send `cartDiscountPriceInfo`, do not set `price` to exactly `0.00`. Omit the object instead.
* Keep `retailerCartId` unique per cart. It is also the default order number.
* `pricingSynchronizationId` is optional. It selects the Pricing Advisor strategy used at checkout. See [Quick start: Pricing Advisor](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/pricing-advisor.md).

### Before you go live

* Request production tokens with production credentials
* Ask ESW to configure your production Order Confirmation webhook and credentials
* Decide between synchronous and asynchronous confirmation with your ESW representative
* Confirm the production Checkout API base URL with your ESW representative

### Next steps

* Explore the [PreOrder reference](https://developer.esw.com/checkout-api/checkout-api/api-methods/preorder.md) for every field
* Add [registered shoppers](https://developer.esw.com/checkout-api/checkout-api/concepts/registered-shopper.md), [shipping overrides](https://developer.esw.com/checkout-api/checkout-api/concepts/shipping-override.md), or [promotional codes](https://developer.esw.com/checkout-api/checkout-api/concepts/promotional-code.md)
* Review [webhook best practices](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/best-practices/webhooks.md)
* Return to the [Quick Start Guide](https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developer.esw.com/getting-started/get-started-with-esw/quick-start-guide/checkout.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
