# Accept a payment (/online-payments)
> Create an online payment, send the shopper to the MPS checkout, and read the outcome when they come back.
You create the payment on your backend, send the shopper to the returned `checkoutUrl`, and MPS
collects the payment. The shopper comes back to your success or failure URL, and you read the payment to
confirm the outcome.
The checkout leads with a QR code for **ANNA**, MPS's pay-by-bank app: the shopper scans it, chooses
their bank and confirms in their banking app. **Continue with card** opens the card form instead.
Either way you get the same states, the same webhook and the same read. In test mode ANNA simulates
the bank (see [Test mode](#test-mode)). MPS collects the card details on its own checkout, so card data
never touches your systems.
> **Server only.** The API cannot be called from a browser. The gateway answers no cross-origin (CORS) requests, and the API key must never reach a browser. Call it from your server.
> **Warning.** Landing on successUrl is not proof of payment. Verify the webhook signature, read the payment, and check its state, amount, currency, and reference before marking an order paid.
>Backend: Check out
Backend->>MPS: Create the payment
MPS-->>Backend: paymentReference, checkoutUrl
Backend-->>Shopper: Redirect to checkoutUrl
Shopper->>MPS: Pay on the checkout
MPS-->>Shopper: Redirect to successUrl or failureUrl
MPS-)Backend: Webhook payment.received, once paid
Backend->>MPS: Read the payment
MPS-->>Backend: state, amount
Backend-->>Shopper: Confirm the order
`}
/>
The return and the webhook can arrive in either order. [Payment lifecycle](/payment-lifecycle) draws
the detail.
- A test key (`mps_test_…`) from **Online › API keys** on the MPS platform. See [Authentication](/authentication).
- The scopes `internet:create` to create and `internet:read` to read. Every key holds them.
- A server that can make outbound HTTPS calls. Every call carries your API key as `Authorization: Bearer`.
- With a partner key: the merchant's wallet, sent as `x-wallet-number` on every call, the read included.
### Create a payment
Send the amount in euro cents and your two return URLs. Add an `Idempotency-Key`, one per checkout
attempt, so a retry never opens a second payment. Pick your language; each example runs as it is with
your test key in `MPS_API_KEY`, and the choice is kept for the whole page.
```http tab="HTTP" tab-group="lang"
POST https://gateway.mps-emi.com/api/payments/internet/create
Authorization: Bearer mps_test_…
Content-Type: application/json
Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91
{
"amount": 1995,
"reference": "order-1234",
"successUrl": "https://shop.example.com/orders/1234/paid",
"failureUrl": "https://shop.example.com/orders/1234/failed"
}
```
```bash tab="curl"
# Prerequisite: export MPS_API_KEY=mps_test_…
curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/internet/create" \
-H "Authorization: Bearer $MPS_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $(uuidgen)" \
-d '{
"amount": 1995,
"reference": "order-1234",
"successUrl": "https://shop.example.com/orders/1234/paid",
"failureUrl": "https://shop.example.com/orders/1234/failed"
}'
```
```csharp tab="C#"
// dotnet new console, replace Program.cs, then: MPS_API_KEY=mps_test_… dotnet run
using System.Net.Http.Json;
using System.Text.Json;
using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") };
mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY"));
using var create = new HttpRequestMessage(HttpMethod.Post, "create")
{
Content = JsonContent.Create(new
{
amount = 1995, // cents
reference = "order-1234",
successUrl = "https://shop.example.com/orders/1234/paid",
failureUrl = "https://shop.example.com/orders/1234/failed",
}),
};
create.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); // one per checkout attempt
using var response = await mps.SendAsync(create);
if (!response.IsSuccessStatusCode)
{
// 400 names the field, 401 and 403 the key: see Errors below.
Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
return 1;
}
var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data");
Console.WriteLine($"paymentReference: {data.GetProperty("paymentReference")}"); // store it with the order
Console.WriteLine($"checkoutUrl: {data.GetProperty("checkoutUrl")}"); // send the shopper here
return 0;
```
```ts tab="TypeScript"
// node create.ts (Node 23.6 or later), with MPS_API_KEY=mps_test_… in the environment
import { randomUUID } from 'node:crypto';
const response = await fetch('https://gateway.mps-emi.com/api/payments/internet/create', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.MPS_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': randomUUID(), // one per checkout attempt
},
body: JSON.stringify({
amount: 1995, // cents
reference: 'order-1234',
successUrl: 'https://shop.example.com/orders/1234/paid',
failureUrl: 'https://shop.example.com/orders/1234/failed',
}),
});
if (!response.ok) {
// 400 names the field, 401 and 403 the key: see Errors below.
throw new Error(`MPS answered ${response.status}: ${await response.text()}`);
}
const { data } = (await response.json()) as { data: { paymentReference: string; checkoutUrl: string } };
console.log('paymentReference:', data.paymentReference); // store it with the order
console.log('checkoutUrl:', data.checkoutUrl); // send the shopper here
```
```python tab="Python"
# pip install requests, then: MPS_API_KEY=mps_test_… python create.py
import os
import sys
import uuid
import requests
response = requests.post(
"https://gateway.mps-emi.com/api/payments/internet/create",
headers={
"Authorization": f"Bearer {os.environ['MPS_API_KEY']}",
"Idempotency-Key": str(uuid.uuid4()), # one per checkout attempt
},
json={
"amount": 1995, # cents
"reference": "order-1234",
"successUrl": "https://shop.example.com/orders/1234/paid",
"failureUrl": "https://shop.example.com/orders/1234/failed",
},
timeout=10,
)
if response.status_code != 200:
# 400 names the field, 401 and 403 the key: see Errors below.
sys.exit(f"MPS answered {response.status_code}: {response.text}")
data = response.json()["data"]
print("paymentReference:", data["paymentReference"]) # store it with the order
print("checkoutUrl:", data["checkoutUrl"]) # send the shopper here
```
```php tab="PHP"
true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MPS_API_KEY'),
'Content-Type: application/json',
'Idempotency-Key: ' . bin2hex(random_bytes(16)), // one per checkout attempt
],
CURLOPT_POSTFIELDS => json_encode([
'amount' => 1995, // cents
'reference' => 'order-1234',
'successUrl' => 'https://shop.example.com/orders/1234/paid',
'failureUrl' => 'https://shop.example.com/orders/1234/failed',
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$body = (string) curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
// 400 names the field, 401 and 403 the key: see Errors below.
fwrite(STDERR, "MPS answered $status: $body\n");
exit(1);
}
$data = json_decode($body, true)['data'];
echo "paymentReference: {$data['paymentReference']}\n"; // store it with the order
echo "checkoutUrl: {$data['checkoutUrl']}\n"; // send the shopper here
```
The gateway answers `200` with a `paymentReference` and a `checkoutUrl`. The fields are in
[Request body](#request-body) and [Response](#response). Add a `callbackUrl` to be told when the
payment is received: see [Webhooks](#webhooks).
### Store the payment reference
Store `paymentReference` with your order **before** you redirect. It is the only key the read accepts,
and nothing is appended to your return URLs to tell you which payment came back.
### Send the shopper to the checkout
Redirect the shopper's browser to `checkoutUrl`: an HTTP `303` from your backend, or
`window.location.assign`. When they finish, they land on your `successUrl` or `failureUrl`.
The checkout refuses to load inside an iframe (`frame-ancestors 'none'`). Redirect the top-level
window, with `window.top.location.href = checkoutUrl` from inside a frame, or open it in a new tab.
This applies to embedded previews, widgets and site builders that render your page in a frame, too.
Open a new tab **in the click handler, before any `await`**. A browser allows `window.open` only
during the click itself, so opening it after creating the payment is blocked, silently in some mobile
app shells. Open `about:blank` first and point it at `checkoutUrl` once you have it. If the tab was
blocked anyway, show `checkoutUrl` as a link the shopper can click.
### Read the outcome
When the shopper comes back, or when the webhook arrives, read the payment on your backend. The
examples take the `paymentReference` from `PAYMENT_REFERENCE`.
```http tab="HTTP" tab-group="lang"
GET https://gateway.mps-emi.com/api/payments/internet/{paymentReference}
Authorization: Bearer mps_test_…
```
```bash tab="curl"
# Prerequisite: export MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-…
curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \
-H "Authorization: Bearer $MPS_API_KEY"
```
```csharp tab="C#"
// dotnet new console, replace Program.cs, then: MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… dotnet run
using System.Net.Http.Json;
using System.Text.Json;
using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") };
mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY"));
var reference = Environment.GetEnvironmentVariable("PAYMENT_REFERENCE")!; // as stored with the order
using var response = await mps.GetAsync(Uri.EscapeDataString(reference));
if (!response.IsSuccessStatusCode)
{
// 404: no such payment for this key. See Errors below.
Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
return 1;
}
var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data");
var paid = data.GetProperty("state").GetString() == "executed" && data.GetProperty("amount").GetInt64() == 1995;
Console.WriteLine(paid ? "Paid" : $"Not paid: {data.GetProperty("state")}");
return 0;
```
```ts tab="TypeScript"
// node read.ts (Node 23.6 or later), with MPS_API_KEY and PAYMENT_REFERENCE in the environment
const reference = process.env.PAYMENT_REFERENCE!; // as stored with the order
const response = await fetch(
`https://gateway.mps-emi.com/api/payments/internet/${encodeURIComponent(reference)}`,
{ headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}` } },
);
if (!response.ok) {
// 404: no such payment for this key. See Errors below.
throw new Error(`MPS answered ${response.status}: ${await response.text()}`);
}
const { data } = (await response.json()) as { data: { state: string; amount: number } };
const paid = data.state === 'executed' && data.amount === 1995;
console.log(paid ? 'Paid' : `Not paid: ${data.state}`);
```
```python tab="Python"
# pip install requests, then: MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… python read.py
import os
import sys
from urllib.parse import quote
import requests
reference = os.environ["PAYMENT_REFERENCE"] # as stored with the order
response = requests.get(
f"https://gateway.mps-emi.com/api/payments/internet/{quote(reference, safe='')}",
headers={"Authorization": f"Bearer {os.environ['MPS_API_KEY']}"},
timeout=10,
)
if response.status_code != 200:
# 404: no such payment for this key. See Errors below.
sys.exit(f"MPS answered {response.status_code}: {response.text}")
data = response.json()["data"]
paid = data["state"] == "executed" and data["amount"] == 1995
print("Paid" if paid else f"Not paid: {data['state']}")
```
```php tab="PHP"
['Authorization: Bearer ' . getenv('MPS_API_KEY')],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$body = (string) curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
// 404: no such payment for this key. See Errors below.
fwrite(STDERR, "MPS answered $status: $body\n");
exit(1);
}
$data = json_decode($body, true)['data'];
$paid = $data['state'] === 'executed' && $data['amount'] === 1995;
echo $paid ? "Paid\n" : "Not paid: {$data['state']}\n";
```
The gateway answers `200` with the payment's `state` and `amount`. Fulfil the order only when `state` is
`executed` and `amount` equals the order total. See [Coming back](#coming-back) for what to do while it
is still `pending`.
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `amount` | integer | Yes | Amount to collect, in cents, as a JSON number. `1995` = EUR 19.95. At least `1`, at most `5000000` (EUR 50,000). A decimal (`19.95`) or a string (`"1995"`) is refused with `400` naming `amount`. |
| `reference` | string | No | Your own order reference, shown to the shopper and echoed back. At most 64 characters: letters `A-Z`, digits, spaces and `. _ : / # + -`. Never required to be unique, never a lookup key. |
| `successUrl` | string | Yes | Absolute HTTPS URL the shopper returns to after a successful payment. `http://` only on `localhost`, for local development. |
| `failureUrl` | string | Yes | Absolute HTTPS URL the shopper returns to after a failed or cancelled payment. `http://` only on `localhost`. |
| `cancelUrl` | string | No | Absolute HTTPS URL the shopper goes to when they choose **Go back** on the checkout instead of paying, such as your basket. Without it, **Go back** leads to `failureUrl`. `http://` only on `localhost`. |
| `callbackUrl` | string | No | HTTPS URL MPS posts this payment's webhooks to, server to server: `payment.received` once the payment is received, and the outcome of each of its refunds. At most 2048 characters. See [Webhooks](/webhooks). |
| `locale` | string | No | Language the checkout opens in: `en`, `nl` or `fr`. A language tag with a region, such as `nl-BE`, is accepted and used as its language (`nl`). Without it, the checkout follows the language of the shopper's browser, and English when the browser asks for none of these. Any other value is refused with `400` naming `locale`. |
The currency is EUR. Every return URL must be `https://`, except `http://` on `localhost`.
Pass `locale` when you know the shopper's language, such as the language of your shop or of the order.
The checkout then opens in that language whatever the shopper's browser asks for.
## Response
### Create
```json title="200 OK"
{
"data": {
"paymentReference": "test-00000000-0000-4000-8000-000000000001",
"checkoutUrl": "https://pay.mps-emi.com/…"
}
}
```
| Field | Type | Required | Description |
|---|---|---|---|
| `paymentReference` | string | Yes | The MPS payment reference. The only key the read endpoint accepts: store it against your order **before** you redirect. |
| `checkoutUrl` | string | Yes | The checkout to send the shopper to. |
Anyone holding `checkoutUrl` can pay this payment. Redirect the shopper to it. Do not log it, e-mail
it to anyone else, or put it where it can leak.
### Read
```json title="200 OK"
{
"data": {
"paymentReference": "test-00000000-0000-4000-8000-000000000001",
"state": "executed",
"amount": 1995,
"currency": "EUR",
"amountRefunded": 0,
"amountRemaining": 1995,
"reference": "order-1234"
}
}
```
| Field | Type | Required | Description |
|---|---|---|---|
| `paymentReference` | string | Yes | As returned by create. |
| `state` | string | Yes | Currently `pending`, `executed`, `failed` or `abandoned`. See [States](#states). |
| `amount` | integer | Yes | In cents. Once `executed`, the amount actually approved. |
| `currency` | string | Yes | ISO currency code of `amount`. |
| `amountRefunded` | integer | Yes | In cents: what has been paid back so far, the refunds that are `refunded`. A `pending` refund is not in it yet. See [Refunds](/refunds). |
| `amountRemaining` | integer | Yes | In cents: what can still be refunded, the executed amount less every `refunded` **and every `pending`** refund. `0` until `executed`. |
| `reference` | string | Yes | Your own order reference, echoed back verbatim. Null when you sent none. |
### The payment reference is an opaque string
Store and compare `paymentReference` as a string, exactly as you received it. Today a live reference
is a GUID and a test one is `test-` followed by a GUID (41 characters). **Do not validate it as a UUID**
or parse it: a test reference already fails that check. Treat it as opaque: letters, digits, `-` and
`_`, and allow up to 64 characters where you store it.
### States
`pending` changes; `executed` (paid) never does. `failed` and `abandoned` (not paid within 24 hours)
are final for the card, with one exception: an ANNA bank payment the shopper completes afterwards still
turns the payment `executed`, and sends `payment.received`. Treat a state you do not
recognise as `pending`: it never means paid. [Payment lifecycle](/payment-lifecycle) explains each one and
what to do with it.
On a partial approval the executed `amount` is **less** than you asked for, and this field is the
only signal that a shortfall occurred. Compare it with the order total before shipping.
You can poll the read every few seconds while the shopper is on the page.
## Retry safely with Idempotency-Key [#retrying-safely-idempotency-key]
Without a key, every create opens a new payment, so two calls for one order open two separately payable
checkouts. To retry safely after a timeout or a dropped connection, send an `Idempotency-Key` header
(`X-Idempotency-Key` is accepted too). Generate its value once per checkout attempt, such as a UUID:
```http
POST https://gateway.mps-emi.com/api/payments/internet/create
Authorization: Bearer mps_live_…
Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91
```
- A retry with the **same key and the same body** returns the payment the first call made: the same
`paymentReference` and `checkoutUrl`, and no second payment.
- The **same key with a different body** is a `400` naming `Idempotency-Key`. Use a new key for a new
payment.
- A retry while the first call is **still running** is a `409` with `code` `idempotency_key_in_use`.
Wait a second and send it again, unchanged.
- A request refused as **invalid** (`400`) does not use up its key: fix the body and send it with the
same key.
- After a **`5xx` or a network error** you cannot tell whether the payment was made. Send the same
request with the same key: you get the payment the first call made, or a new one if it made none.
- A key belongs to your merchant and its mode: the same key from a test key and a live key, or from two
merchants, makes two payments.
- At most 255 characters: letters, digits and punctuation, no spaces.
A key is kept for **24 hours** from the moment its payment was created, as long as that payment can be
paid. Retries do not extend it.
| You send the key again… | Same body | Different body |
|---|---|---|
| Within 24 hours | The first payment, `200` | `400` naming `Idempotency-Key` |
| Within 24 hours, but the first payment can no longer be read (rare) | `409` `idempotency_key_expired`: create a new payment with a new key | `400` naming `Idempotency-Key` |
| After 24 hours | A **new** payment | A new payment |
After 24 hours the first payment is abandoned unless it was paid. Before you open a new payment for an
order that already had one, read the first payment: if it is `executed`, the order is paid. Keep every
`paymentReference` an order had, so a late payment can still be matched to it.
## Coming back
MPS sends the shopper to your URLs **exactly as you passed them**. Nothing is appended: no payment
reference, no state. To know which payment a return belongs to, keep the `paymentReference` with the
order (or in the shopper's session) before redirecting. Or put your own order id in the URLs you pass,
such as `https://shop.example.com/orders/1234/paid`.
| The shopper lands on | When | `state` when you read it |
|---|---|---|
| `successUrl` | The payment went through | `executed` |
| `failureUrl` | The payment was declined or failed | `failed` |
| `cancelUrl`, or `failureUrl` without one | The shopper chose **Go back** on the checkout | Still `pending`: not paid |
| `failureUrl` | The payment expired, 24 hours after it was created, while the checkout was still open | `abandoned` |
On return, read the payment once on your backend. If it is still `pending`, poll it every 2 seconds for
up to about 30 seconds. Then show "we are confirming your payment" and let the
[webhook](#webhooks) or a later read settle the order. Never mark an order paid because
the shopper reached your success URL.
## Card attempts are limited
A **declined card ends the payment**: it is `failed`, and the shopper is sent to your failure URL. To let
them try another card, create a new payment, with a new `Idempotency-Key`.
Cards that end in neither an approval nor a decline leave the payment `pending`: an abandoned 3-D Secure
step, or a card refused before the issuer decided. The shopper may try again on the same checkout, at most
**five** cards per payment. After the fifth the checkout refuses further cards and tells the shopper so.
Nothing is sent to your return URLs, and the payment stays `pending` until it is abandoned, 24 hours after
it was created. A payment that has already been paid never takes a second card.
## Webhooks
Pass a `callbackUrl` when you create the payment, and MPS posts a signed `payment.received` webhook to
it, server to server, once the payment has been received and booked. It arrives even when the shopper
closes the tab before coming back. A payment that does not go through sends none: read it.
[Webhooks](/webhooks) shows how to verify the signature, what the body carries, and how retries work.
## Test mode
A payment created with a **test key**, an API key starting `mps_test_`, is a test payment. It works as
it does in live mode: the same endpoints, the same checkout URL, the same states and the same webhook.
But no card is charged, no bank is contacted, and nothing is booked or paid out.
- The `paymentReference` starts with `test-`, such as `test-00000000-0000-4000-8000-000000000001`; a live
one is the GUID alone. It is the same reference everywhere (the checkout URL, the read endpoint and
the webhook), so your system can tell a test payment from a live one by its reference alone.
- The checkout shows a **Test mode** banner and lists the test cards below.
- Only the test cards are accepted. Any other card number is refused under the card number field, and
uses up one of the payment's five [card attempts](#card-attempts-are-limited).
- The card number decides the outcome. Any future expiry date and any security code will do.
| Card number | Scheme | Outcome |
|---|---|---|
| `4111 1111 1111 1111` | Visa | `executed` |
| `5555 5555 5555 4444` | Mastercard | `executed` |
| `4000 0000 0000 0002` | Visa | `failed` |
| `5200 0000 0000 0007` | Mastercard | `failed` |
| `4000 0000 0000 0010` | Visa | stays `pending` |
The ANNA QR code opens ANNA's test screen, under a **Test mode** banner. The shopper chooses a bank as
in live mode, then chooses how the bank answers instead of confirming in their banking app:
| Choice | Outcome |
|---|---|
| Paid | `executed` |
| Rejected by the bank | the bank payment fails |
| Cancelled at the bank | the bank payment fails |
| Stays pending | stays `pending` |
A failed bank payment fails the payment once the card cannot pay it either, as in live mode: while the card
form can still be used, the payment stays `pending`.
An `executed` test payment sends the `payment.received` webhook to your `callbackUrl`, signed with the
test key's own signing secret. It is shown once, next to the API key, when you generate the key. A test
key has no 3-D Secure step.
## End-to-end example
A minimal backend for a shop: the cart posts to `/pay`, the shopper pays on the MPS checkout, comes
back to `/orders/:id/return`, and the backend reads the outcome. Run it with a **test key** and pay
with `4111 1111 1111 1111` (any future expiry, any security code) for a paid order, or
`4000 0000 0000 0002` for a declined one. See [Test mode](#test-mode).
```bash tab="curl"
# Prerequisite: export MPS_API_KEY=mps_test_… (and jq installed)
# 1. Create. Keep paymentReference with your order. One Idempotency-Key per checkout attempt:
# resend the same one to retry, and you get the same payment back.
IDEMPOTENCY_KEY=$(uuidgen)
CREATED=$(curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/internet/create" \
-H "Authorization: Bearer $MPS_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: $IDEMPOTENCY_KEY" \
-d '{"amount":1995,"reference":"order-1234",
"successUrl":"https://shop.example.com/orders/1234/return",
"failureUrl":"https://shop.example.com/orders/1234/return"}') || { echo "$CREATED"; exit 1; }
PAYMENT_REFERENCE=$(echo "$CREATED" | jq -r '.data.paymentReference')
# 2. Open checkoutUrl in a browser and pay with a test card.
echo "Pay here: $(echo "$CREATED" | jq -r '.data.checkoutUrl')"
read -r -p "Press Enter once you have paid. "
# 3. Read the outcome
curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \
-H "Authorization: Bearer $MPS_API_KEY"
```
```ts tab="TypeScript"
import express from 'express';
import { randomUUID } from 'node:crypto';
const API = 'https://gateway.mps-emi.com';
const app = express();
app.use(express.urlencoded({ extended: false }));
// Your own order store; paymentReference is kept as a plain string. One order to try it with.
const orders = new Map();
orders.set('1234', { total: 1995 });
// Your API key, from your vault or environment. Sent on every call; there is nothing to fetch first.
const auth = { Authorization: `Bearer ${process.env.MPS_API_KEY}` };
async function readPayment(reference: string) {
const res = await fetch(`${API}/api/payments/internet/${encodeURIComponent(reference)}`, {
headers: auth,
});
if (!res.ok) throw new Error(`Read failed: ${res.status}`);
return (await res.json()).data as { state: string; amount: number };
}
// Cart → MPS checkout
app.post('/orders/:id/pay', async (req, res) => {
const order = orders.get(req.params.id);
if (!order) return res.sendStatus(404);
const returnUrl = `https://shop.example.com/orders/${req.params.id}/return`;
// One key per checkout attempt, stored with the order: a retry sends it again and gets the same payment.
order.idempotencyKey ??= randomUUID();
try {
const created = await fetch(`${API}/api/payments/internet/create`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': order.idempotencyKey },
body: JSON.stringify({
amount: order.total, // cents
reference: req.params.id,
successUrl: returnUrl,
failureUrl: returnUrl,
}),
});
if (!created.ok) return res.status(502).send(await created.text());
const { data } = await created.json();
order.paymentReference = data.paymentReference; // store BEFORE redirecting
res.redirect(303, data.checkoutUrl); // top-level redirect: the checkout cannot be framed
} catch (err) {
// A network error or a timeout: the payment may exist. Retry with the same idempotencyKey.
console.error(err);
res.status(502).send('We could not start your payment. Please try again.');
}
});
// MPS → back to the shop. Nothing is appended to the URL; the order id in the path is enough.
app.get('/orders/:id/return', async (req, res) => {
const order = orders.get(req.params.id);
if (!order?.paymentReference) return res.sendStatus(404);
try {
let payment = await readPayment(order.paymentReference);
for (let i = 0; i < 15 && payment.state === 'pending'; i++) {
await new Promise((r) => setTimeout(r, 2000));
payment = await readPayment(order.paymentReference);
}
if (payment.state === 'executed' && payment.amount === order.total) {
order.paid = true;
return res.send('Thank you, your order is paid.');
}
if (payment.state === 'pending') return res.send('We are confirming your payment.');
res.send('Your payment did not go through. Please try again.');
} catch (err) {
// The read failed: leave the order open, and let the webhook or a later read settle it.
console.error(err);
res.send('We are confirming your payment.');
}
});
app.listen(3000);
```
The curl version prints the checkout and then the payment with `"state": "executed"` once you paid with
`4111 1111 1111 1111`.
In production, also pass a `callbackUrl` and settle orders from the [webhook](#webhooks): a
shopper who closes the tab after paying never reaches your return URL.
## Errors
Every status the create and read endpoints answer, with its body, is listed in
[Errors and rate limits](/errors-and-rate-limits#by-endpoint). The ones you meet here:
| Status | Code | Cause | Resolution |
|---|---|---|---|
| `400` | — | Validation failed: an amount of zero, a non-HTTPS return URL, a `callbackUrl` that is not an absolute HTTPS URL on a publicly routable host, or an `Idempotency-Key` reused for a different request. The body names the field. | Fix the named field. See [Validation errors](/errors-and-rate-limits#validation-errors). |
| `401` | — | No API key, or a wrong or revoked one. | Check the key. See [API key errors](/authentication#api-key-errors). |
| `403` | — | The key lacks the scope; a partner key sent no `x-wallet-number`, or one that is not one of your merchants; or the merchant has no shop name registered yet. | Check the scope and the wallet. With a partner key, send `x-wallet-number`. For a missing shop name, contact MPS. See [Authentication errors](/errors-and-rate-limits#authentication-errors). |
| `404` | — | Read only: no such payment for this merchant, or a partner key sent no `x-wallet-number`. | Check that the reference reached you unchanged, and read it for the wallet it was created with (with a partner key, the same `x-wallet-number`). See [Not found](/errors-and-rate-limits#not-found). |
| `409` | `idempotency_key_in_use` | Create only: a payment with this `Idempotency-Key` is still being created. | Retry after a second with the same key and body. See [Conflicts](/errors-and-rate-limits#conflicts). |
| `409` | `idempotency_key_expired` | Create only: the payment this key made can no longer be returned. | Create a new payment with a new key. See [Conflicts](/errors-and-rate-limits#conflicts). |
| `429` | — | Rate limited. | Wait `Retry-After` seconds. See [Rate limits](/errors-and-rate-limits#rate-limits). |
## Related
- [Receive webhooks](/webhooks)
- [Payment lifecycle](/payment-lifecycle)
- [Refund a payment](/refunds)