# Run an integration example (/integration-examples) > Run a minimal example or a production starting point in C#, TypeScript, Python or PHP that creates payments, verifies and stores webhooks and settles orders, to which you add durable fulfilment and reconciliation before a live shop uses it. Two starting points, each in C#, TypeScript, Python and PHP: - **[Minimal](#minimal-example)**: create a payment, redirect, read the result. About 40 lines, to see the flow work. - **[Production](#production-example)**: a production starting point, a whole backend in one file: a shop that sells one EUR 19.95 order. Start it, pay with a [test card](/online-payments#test-mode), and watch the order settle from the return page and from the webhook. The four do the same thing in the same order, so you can read the one you know and port it. > **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. - A test key (`mps_test_…`) and its signing secret, from **Online › API keys** on the MPS platform - The runtime of the language you pick: .NET 10, Node 22.13 or later, Python 3.10 or later, or PHP 8.1 or later (8.2 for the production example) - For the production example: a public HTTPS address for port `8000`, such as a tunnel (ngrok, Cloudflare Tunnel) ## Minimal example The smallest useful integration: create a payment, send the shopper to the checkout, and read the result when they come back. Open `http://localhost:8000/checkout`, pay with a [test card](/online-payments#test-mode), and the return page says whether it is paid. It keeps the order in memory, makes a new `Idempotency-Key` per click, receives no webhook and retries nothing. A production integration also verifies webhooks, stores the order and its key before calling MPS, and fulfils each order once: the [production example](#production-example) below does all of it. .NET 10: `dotnet new web`, replace `Program.cs`, then `dotnet run`. ```csharp title="Program.cs" using System.Text.Json; var app = WebApplication.CreateBuilder(args).Build(); 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 payments = new Dictionary(); // order id -> paymentReference: your database in a real shop app.MapGet("/checkout", async () => { var order = "order-42"; var back = $"http://localhost:8000/return?order={order}"; using var create = new HttpRequestMessage(HttpMethod.Post, "create") { Content = JsonContent.Create(new { amount = 1995, reference = order, successUrl = back, failureUrl = back }) }; create.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); using var response = await mps.SendAsync(create); if (!response.IsSuccessStatusCode) return Results.Text($"MPS answered {(int)response.StatusCode}", statusCode: 502); var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); payments[order] = data.GetProperty("paymentReference").GetString()!; return Results.Redirect(data.GetProperty("checkoutUrl").GetString()!); }); app.MapGet("/return", async (string order) => { if (!payments.TryGetValue(order, out var reference)) return Results.NotFound("Unknown order"); var data = (await mps.GetFromJsonAsync(Uri.EscapeDataString(reference))).GetProperty("data"); var state = data.GetProperty("state").GetString(); var paid = state == "executed" && data.GetProperty("amount").GetInt64() == 1995; return Results.Text(paid ? "Paid" : $"Not paid: {state}"); }); app.Run("http://localhost:8000"); ``` Run it: `npx tsx server.ts` (on Node 23.6 or later, `node server.ts` works too). ```ts title="server.ts" import { createServer } from 'node:http'; import { randomUUID } from 'node:crypto'; const API = 'https://gateway.mps-emi.com/api/payments/internet'; const auth = { Authorization: `Bearer ${process.env.MPS_API_KEY}` }; const payments = new Map(); // order id -> paymentReference: your database in a real shop createServer(async (req, res) => { const url = new URL(req.url ?? '/', 'http://localhost:8000'); if (url.pathname === '/checkout') { const order = 'order-42'; const back = `http://localhost:8000/return?order=${order}`; const created = await fetch(`${API}/create`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID() }, body: JSON.stringify({ amount: 1995, reference: order, successUrl: back, failureUrl: back }), }); if (created.status !== 200) return res.writeHead(502).end(`MPS answered ${created.status}`); const { data } = await created.json(); payments.set(order, data.paymentReference); res.writeHead(303, { Location: data.checkoutUrl }).end(); } else if (url.pathname === '/return') { const reference = payments.get(url.searchParams.get('order') ?? ''); if (!reference) return res.writeHead(404).end('Unknown order'); const read = await fetch(`${API}/${encodeURIComponent(reference)}`, { headers: auth }); const { data } = await read.json(); const paid = data.state === 'executed' && data.amount === 1995; res.end(paid ? 'Paid' : `Not paid: ${data.state}`); } else { res.writeHead(404).end(); } }).listen(8000); ``` `pip install flask requests`, then `python app.py`. ```python title="app.py" import os, uuid from urllib.parse import quote import requests from flask import Flask, redirect, request API = "https://gateway.mps-emi.com/api/payments/internet" AUTH = {"Authorization": f"Bearer {os.environ['MPS_API_KEY']}"} app = Flask(__name__) payments = {} # order id -> paymentReference: your database in a real shop @app.get("/checkout") def checkout(): order = "order-42" back = f"http://localhost:8000/return?order={order}" res = requests.post(f"{API}/create", timeout=10, headers={**AUTH, "Idempotency-Key": str(uuid.uuid4())}, json={"amount": 1995, "reference": order, "successUrl": back, "failureUrl": back}) if res.status_code != 200: return f"MPS answered {res.status_code}", 502 data = res.json()["data"] payments[order] = data["paymentReference"] return redirect(data["checkoutUrl"], 303) @app.get("/return") def back(): reference = payments.get(request.args.get("order", "")) if reference is None: return "Unknown order", 404 payment = requests.get(f"{API}/{quote(reference, safe='')}", headers=AUTH, timeout=10).json()["data"] paid = payment["state"] == "executed" and payment["amount"] == 1995 return "Paid" if paid else f"Not paid: {payment['state']}" if __name__ == "__main__": app.run(port=8000) ``` PHP 8.1 or later with curl: `php -S localhost:8000 index.php`. ```php title="index.php" paymentReference: your database in a real shop const API = 'https://gateway.mps-emi.com/api/payments/internet'; function mps(string $url, ?array $body = null): array { $headers = ['Authorization: Bearer ' . getenv('MPS_API_KEY'), 'Content-Type: application/json']; $ch = curl_init($url); if ($body !== null) { $headers[] = 'Idempotency-Key: ' . bin2hex(random_bytes(16)); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); } curl_setopt_array($ch, [CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]); $response = json_decode((string) curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { http_response_code(502); exit("MPS answered $status"); } return $response['data']; } $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if ($path === '/checkout') { $order = 'order-42'; $back = "http://localhost:8000/return?order=$order"; $data = mps(API . '/create', ['amount' => 1995, 'reference' => $order, 'successUrl' => $back, 'failureUrl' => $back]); $_SESSION[$order] = $data['paymentReference']; header('Location: ' . $data['checkoutUrl'], true, 303); } elseif ($path === '/return') { $reference = $_SESSION[$_GET['order'] ?? ''] ?? null; if ($reference === null) { http_response_code(404); exit('Unknown order'); } $payment = mps(API . '/' . rawurlencode($reference)); $paid = $payment['state'] === 'executed' && $payment['amount'] === 1995; echo $paid ? 'Paid' : "Not paid: {$payment['state']}"; } else { http_response_code(404); } ``` ## Production example The rest of this page is a production starting point, one file per language: webhook verification, a durable inbox, retried payment reads, one order with as many payment attempts as the shopper needs, and an atomic order-paid update, with recovery after a restart. **Fulfilment is a log message.** Before going live, record a fulfilment job in the same database commit that marks the order paid, then process that job with retries and an idempotency key the downstream system accepts, and run the reconciliation schedule in [Payment lifecycle](/payment-lifecycle#reconcile-what-you-did-not-hear-about). Each example runs **one worker in one process**, and its worker does not claim inbox rows. Run two instances (two servers behind a load balancer, or two overlapping cron runs of the PHP worker) and both can take the same row. The order is still settled once (see **The order is settled once** below), but both read the payment and record the outcome. Before running more than one worker, have each claim a row with an update only one of them can win, and process the row only when that update changed it: ```sql UPDATE webhook_inbox SET status = 'processing', claimed_until = :now + 60 WHERE delivery_id = :delivery_id AND (status = 'pending' OR (status = 'processing' AND claimed_until < :now)) ``` `claimed_until` is a column the examples do not have: it lets another worker take over a row whose worker stopped mid-way. On PostgreSQL, pick the candidates with `SELECT … FOR UPDATE SKIP LOCKED`; or use your queue, which hands each message to one worker. Run the PHP worker under a lock (`flock -n /tmp/mps-worker.lock php index.php`) so cron runs never overlap. ## What every example does - **`POST /checkout`** stores the order and a payment attempt with a fresh `Idempotency-Key`, and creates the payment with `POST /api/payments/internet/create` (amount in cents, `reference`, `successUrl`, `failureUrl`, `callbackUrl`), sending that key. It stores `paymentReference` and `checkoutUrl` against the attempt **before** redirecting, and sends the shopper to `checkoutUrl` with a `303`. If the create fails, **Try again** sends the same attempt with the same key: MPS returns a payment the failed call did open, rather than make a second one. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). - **Trying again after a `failed` or `abandoned` payment** creates a new payment attempt for the **same order**, with a new idempotency key, and keeps every earlier attempt with its `paymentReference`. A `pending` payment is not replaced: its checkout is reopened. A late ANNA payment on an earlier attempt still belongs to that order. If the order is already paid, the second payment is recorded for review and a refund; the order is never fulfilled twice. See [`failed`](/payment-lifecycle#failed). - **`POST /webhooks/mps`** reads the raw body, checks `X-Mps-Timestamp` is within five minutes, verifies `X-Mps-Signature` (HMAC-SHA256 of `{timestamp}.{raw body}`, lower-case hex, every `v1=` value, constant-time), **stores the webhook in the `webhook_inbox` table**, keyed on `X-Mps-Delivery-Id` so a duplicate webhook is a no-op, and only then answers `2xx`. If it cannot store it, it answers `500` and MPS tries again. It does no other work. See [Process webhooks reliably](/webhooks#processing-them-reliably). - **A worker** completes the business operation, separately from receiving the webhook. Every few seconds it takes the pending inbox rows, finds the attempt and order of each payment (an earlier attempt included), reads the payment and settles it. A temporary failure (a timeout, a `429`, a `5xx`, a payment still `pending`) is retried with backoff, up to 8 times; a permanent one (an unknown payment, a different amount, a payment that does not match its order, a refused read) is kept as `failed` with its reason, for you to look at. Because the inbox is stored, a crash or a restart loses nothing: the next pass picks up where it stopped. In C#, TypeScript and Python it runs inside the server; in PHP it is `php index.php`, run from cron. - **`GET /return`** is both the `successUrl` and the `failureUrl`. It never trusts the landing: it reads `GET /api/payments/internet/{paymentReference}` and settles through the **same function as the worker**, so both paths check the same things before an order is marked paid: `paymentReference` matches the stored attempt (compared as opaque strings), `reference` matches the order, `currency` matches the order's (`EUR` here), `state` is `executed` and `amount` equals the order total in cents. A mismatch never marks the order paid and is recorded for investigation; a partial approval leaves the order unpaid for a person to decide; an unknown state stays pending. The page re-reads a `pending` payment every 2 seconds for about 30 seconds. - **Errors** follow [Errors and rate limits](/errors-and-rate-limits): a `400` logs each field of the problem document, `401` and `403` are configuration problems and are not retried, a `429` is retried after `Retry-After`, and a `5xx` or network error is retried on reads **and on the create**, which is safe because it carries an `Idempotency-Key`. A `409` is decided on its `code`: only `idempotency_key_in_use` (the first call with that key is still running) is retried, after a second; any other code, or none, is final. - **The order is settled once.** The worker and the return page both settle through one statement, `UPDATE orders SET paid_at = …, paid_by = … WHERE id = … AND paid_at IS NULL`, and ship only when it changed a row. A duplicate delivery, a second worker pass or the shopper's return racing the worker cannot ship twice; a second payment that completes for an order already paid is flagged for a refund. **Fulfilment is a placeholder**: where the examples log "ship it", a real shop inserts a fulfilment job in the same commit and processes it with retries and downstream idempotency, so a failed shipment is not lost once the order reads paid. The paid-at update alone does not make the shipment happen. See [Process, then answer](/webhooks#the-simple-handler-process-then-answer) and [Reconcile what you did not hear about](/payment-lifecycle#reconcile-what-you-did-not-hear-about). - **Storage** is SQLite, in `mps-example.db`, so you can run each example as is. It stands in for your database: the same three tables and statements work there. It is a single-instance setup: with more than one worker, claim each row first, as the **Single-instance examples** box at the top shows, or use your queue. Find what needs a person with `SELECT * FROM webhook_inbox WHERE status = 'failed'`. ## Run the production example ### Configure [#configure] | Variable | Required | Description | |---|---|---| | `MPS_API_KEY` | Yes | Your API key, `mps_test_…` while you build. Sent as `Authorization: Bearer`. | | `MPS_WEBHOOK_SECRET` | Yes | The signing secret shown next to the key. | | `PUBLIC_BASE_URL` | Yes | The public `https://` address of this server, for example a tunnel to `localhost:8000`. The examples build the return URL and the `callbackUrl` from it. | | `MPS_WALLET_NUMBER` | No | Partner keys only: the merchant's wallet, sent as `x-wallet-number` on every call. Leave it unset for a test key or a merchant's own key. See [Choosing the merchant](/authentication#choosing-the-merchant). | ```bash export MPS_API_KEY="mps_test_…" # from your secret store, never from source control export MPS_WEBHOOK_SECRET="…" export PUBLIC_BASE_URL="https://your-tunnel.example" # forwards to http://localhost:8000 ``` The webhook only reaches you on a public HTTPS host: put a tunnel (ngrok, Cloudflare Tunnel) in front of port `8000`. Every example listens there. ### Run the code [#the-code] .NET 10, ASP.NET Core minimal API and `HttpClient`, plus SQLite for storage. Run it: `dotnet new web -n MpsExample`, then `dotnet add package Microsoft.Data.Sqlite`, replace `Program.cs` with the file below, then `dotnet run --urls http://localhost:8000`. The orders and the webhook inbox live in `mps-example.db`. ```csharp title="Program.cs" // Program.cs: .NET 10 minimal API; one package, Microsoft.Data.Sqlite. using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Data.Sqlite; var apiKey = Required("MPS_API_KEY"); // mps_test_… or mps_live_… var webhookSecret = Required("MPS_WEBHOOK_SECRET"); // shown once, next to the API key var publicBaseUrl = Required("PUBLIC_BASE_URL").TrimEnd('/'); var walletNumber = Environment.GetEnvironmentVariable("MPS_WALLET_NUMBER"); var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com"), Timeout = TimeSpan.FromSeconds(15) }; mps.DefaultRequestHeaders.Authorization = new("Bearer", apiKey); // Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if (!string.IsNullOrEmpty(walletNumber)) mps.DefaultRequestHeaders.Add("x-wallet-number", walletNumber); // SQLite stands in for your database: the same tables and statements work there. const string connectionString = "Data Source=mps-example.db"; Execute(""" CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see MarkPaid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); """); var app = WebApplication.CreateBuilder(args).Build(); var log = app.Logger; app.MapGet("/", () => Html("""
""")); // 1. Create the payment and send the shopper to the MPS checkout. ?retry= tries again for an order that exists: // the order stays, with every attempt it ever had, so a late payment on an earlier attempt still finds it. app.MapPost("/checkout", async (HttpResponse response, string? retry) => { var order = retry is null ? null : OrderById(retry); if (order is { PaidAt: not null }) return Html("

This order is already paid.

"); var attempt = order is null ? null : ActiveAttempt(order.Id); if (attempt is { PaymentReference: not null }) { // The last attempt did open a payment: what became of it decides. var read = await Send(HttpMethod.Get, $"/api/payments/internet/{Uri.EscapeDataString(attempt.PaymentReference)}"); if (read.Status != 200) { LogFailure("read", read); return Html("

We could not check your previous payment just now. Try again in a moment.

", 502); } switch (read.Body.GetProperty("data").GetProperty("state").GetString()) { case "pending": // the shopper can still pay it: reopen that checkout, never a second one response.Headers.Location = attempt.CheckoutUrl; return Results.StatusCode(StatusCodes.Status303SeeOther); case "failed" or "abandoned": // a new attempt for the same order, with a new key // Closing the old attempt in one statement lets one request win: two clicks open one attempt, not two. if (Execute("UPDATE payment_attempts SET active = 0 WHERE idempotency_key = $key AND active = 1", ("$key", attempt.IdempotencyKey)) != 1) return Html("

Your payment was just restarted in another tab. Use that one.

", 409); attempt = null; break; default: // executed, or a state this code does not know: the return page settles it return Results.Redirect($"/return?order={order!.Id}", false, false); } } if (order is null) { order = new($"order-{Guid.NewGuid():N}"[..14], 1995, null, null); // cents Execute("INSERT INTO orders (id, total) VALUES ($id, $total)", ("$id", order.Id), ("$total", order.Total)); } if (attempt is null) { // One Idempotency-Key per attempt, stored BEFORE calling MPS. Every retry with it, by Send or by // "Try again" below, returns the payment the first call made, never a second one. attempt = new(Guid.NewGuid().ToString(), order.Id, null, null); Execute("INSERT INTO payment_attempts (idempotency_key, order_id, created_at) VALUES ($key, $order, $now)", ("$key", attempt.IdempotencyKey), ("$order", order.Id), ("$now", DateTimeOffset.UtcNow.ToString("O"))); } var returnUrl = $"{publicBaseUrl}/return?order={order.Id}"; // MPS appends nothing: carry your own id // Built from the order alone, so a retry sends the same body: the same key with another body is a 400. var result = await Send(HttpMethod.Post, "/api/payments/internet/create", new { amount = order.Total, reference = order.Id, successUrl = returnUrl, failureUrl = returnUrl, callbackUrl = $"{publicBaseUrl}/webhooks/mps", }, attempt.IdempotencyKey); if (result.Status != 200) { LogFailure("create", result); // The same attempt and key: if the failed call did open a payment, trying again returns that one. return Html($"""

We could not start the payment.

""", 502); } var data = result.Body.GetProperty("data"); Execute("UPDATE payment_attempts SET payment_reference = $reference, checkout_url = $url WHERE idempotency_key = $key", // BEFORE redirecting ("$reference", data.GetProperty("paymentReference").GetString()), ("$url", data.GetProperty("checkoutUrl").GetString()), ("$key", attempt.IdempotencyKey)); response.Headers.Location = data.GetProperty("checkoutUrl").GetString(); // never log it: whoever has it can pay return Results.StatusCode(StatusCodes.Status303SeeOther); }); // 2. The webhook route: verify, store the webhook in the inbox, then answer 2xx. Nothing else. // A 2xx means "accepted responsibility": after it, MPS does not send this webhook again. So the row // is written first, and if that fails the answer is a 500 and MPS retries. Never acknowledge unpersisted work. // It reads nothing and starts nothing: the worker (4) does the work, so the answer stays well inside the 10-second budget. app.MapPost("/webhooks/mps", async (HttpRequest request) => { using var buffer = new MemoryStream(); await request.Body.CopyToAsync(buffer); // the raw bytes: verify BEFORE parsing var body = buffer.ToArray(); if (!IsValidSignature(request.Headers["X-Mps-Timestamp"].ToString(), request.Headers["X-Mps-Signature"].ToString(), body)) return Results.Unauthorized(); var notification = JsonDocument.Parse(body).RootElement; if (notification.GetProperty("eventType").GetString() != "payment.received") return Results.Ok(); // a new event type: ignore it, never fail on it try { // Every retry of a webhook carries the same delivery id: the primary key turns a repeat into a no-op. Execute(""" INSERT INTO webhook_inbox (delivery_id, payment_reference, received_at, next_attempt_at) VALUES ($delivery, $reference, $received, $now) ON CONFLICT(delivery_id) DO NOTHING """, ("$delivery", request.Headers["X-Mps-Delivery-Id"].ToString()), ("$reference", notification.GetProperty("paymentReference").GetString()), ("$received", DateTimeOffset.UtcNow.ToString("O")), ("$now", DateTimeOffset.UtcNow.ToUnixTimeSeconds())); } catch (Exception e) { log.LogError(e, "Could not store the notification; answering 500 so MPS retries"); return Results.StatusCode(StatusCodes.Status500InternalServerError); } return Results.Ok(); }); // 3. The shopper's return: read the payment. Landing here proves nothing. It settles through the same // Settle as the worker, so both paths apply the same checks. app.MapGet("/return", async (string order, int? attempt) => { if (OrderById(order) is not { } found || ActiveAttempt(found.Id) is not { PaymentReference: not null } current) return Results.NotFound(); var result = await Send(HttpMethod.Get, $"/api/payments/internet/{Uri.EscapeDataString(current.PaymentReference)}"); if (result.Status != 200) { LogFailure("read", result); return Html("

We could not check your payment just now. Refresh this page in a moment.

", 502); } var next = (attempt ?? 0) + 1; return Settle(found, current, result.Body.GetProperty("data")).Outcome switch { Outcome.Paid => Html("

Thank you, your order is paid.

"), Outcome.PaidTwice => Html("

This order was already paid by an earlier payment. We will refund this one.

"), Outcome.Short => Html("

Your card was approved for less than the order total. We have not shipped; please contact us.

"), Outcome.Mismatch => Html("

We could not match this payment to your order. We have not shipped; please contact us.

"), // A new attempt for the same order: the order keeps its id and its earlier payments. Outcome.NotPaid => Html($"""

Your payment did not go through.

"""), // Still pending (or a state we do not know): re-read every 2 s for about 30 s, then let the webhook settle it. _ when next <= 15 => Html($"""

Confirming your payment…

"""), _ => Html("

We are confirming your payment and will e-mail you as soon as it is.

"), }; }); // 4. The worker: the business operation, separate from receiving the webhook. Every 5 s it takes the // pending inbox rows that are due and confirms each by reading the payment. A row stays pending until its // outcome is recorded, so after a crash or restart the next pass picks it up again (at least once); MarkPaid // makes that safe. One worker per process: with several instances, claim a row first // (UPDATE ... SET status = 'processing' ... RETURNING) or use your queue. var worker = ConfirmPendingWebhooksAsync(app.Lifetime.ApplicationStopping); await app.RunAsync(); await worker; async Task ConfirmPendingWebhooksAsync(CancellationToken stopping) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5)); try { while (await timer.WaitForNextTickAsync(stopping)) { try { var due = Query(""" SELECT delivery_id, payment_reference, attempts FROM webhook_inbox WHERE status = 'pending' AND next_attempt_at <= $now ORDER BY received_at LIMIT 20 """, static row => new InboxRow(row.GetString(0), row.GetString(1), row.GetInt64(2)), ("$now", DateTimeOffset.UtcNow.ToUnixTimeSeconds())); foreach (var row in due) { // One bad row never stops the loop: an unexpected error is a temporary failure, tried again later. Confirmation confirmation; try { confirmation = await ConfirmAsync(row.PaymentReference); } catch (Exception e) { confirmation = new(Verdict.Temporary, e.Message); } try { Record(row, confirmation); } catch (Exception e) { log.LogError(e, "Recording delivery {DeliveryId} failed; the next pass retries", row.DeliveryId); } } } catch (Exception e) when (e is not OperationCanceledException) { log.LogError(e, "Worker pass failed; the next pass retries"); } } } catch (OperationCanceledException) { log.LogInformation("Worker stopped: the server is shutting down"); } } // Confirm one webhook: find the attempt and its order, read the payment, settle through the same Settle as the return page. async Task ConfirmAsync(string paymentReference) { // Any attempt, active or not: a late ANNA payment on an earlier attempt still belongs to its order. if (AttemptByPayment(paymentReference) is not { } attempt || OrderById(attempt.OrderId) is not { } order) return new(Verdict.Permanent, "unknown payment"); var result = await Send(HttpMethod.Get, $"/api/payments/internet/{Uri.EscapeDataString(paymentReference)}"); if (result.Status != 200) { LogFailure("read", result); return result.Status is 400 or 401 or 403 or 404 ? new(Verdict.Permanent, $"MPS answered {result.Status}") // fix the configuration; retrying cannot help : new(Verdict.Temporary, $"MPS answered {result.Status}"); // 0 (network), 429, 5xx: try again later } var settlement = Settle(order, attempt, result.Body.GetProperty("data")); return settlement.Outcome switch { Outcome.Paid or Outcome.NotPaid => new(Verdict.Processed), // shipped, or nothing to ship Outcome.Pending => new(Verdict.Temporary, settlement.Reason), _ => new(Verdict.Permanent, settlement.Reason), // Short, Mismatch, PaidTwice: a person decides; never ship }; } // Record the outcome on the inbox row. Failed rows stay for investigation: // SELECT * FROM webhook_inbox WHERE status = 'failed' void Record(InboxRow row, Confirmation confirmation) { var attempts = row.Attempts + 1; switch (confirmation.Verdict) { case Verdict.Processed: Execute("UPDATE webhook_inbox SET status = 'processed', last_error = NULL WHERE delivery_id = $delivery", ("$delivery", row.DeliveryId)); return; case Verdict.Temporary when attempts < 8: // back off 10 s, 20 s, 40 s … at most an hour Execute("UPDATE webhook_inbox SET attempts = $attempts, next_attempt_at = $next, last_error = $error WHERE delivery_id = $delivery", ("$attempts", attempts), ("$next", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + Math.Min(5L << (int)attempts, 3600)), ("$error", confirmation.Error), ("$delivery", row.DeliveryId)); return; case Verdict.Temporary: // the eighth try: stop retrying Execute("UPDATE webhook_inbox SET status = 'failed', attempts = $attempts, last_error = $error WHERE delivery_id = $delivery", ("$attempts", attempts), ("$error", confirmation.Error), ("$delivery", row.DeliveryId)); break; default: // permanent: retrying cannot help Execute("UPDATE webhook_inbox SET status = 'failed', last_error = $error WHERE delivery_id = $delivery", ("$error", confirmation.Error), ("$delivery", row.DeliveryId)); break; } log.LogError("Delivery {DeliveryId} failed: {Error}", row.DeliveryId, confirmation.Error); } // The one place a payment is matched to its order and settled; the return page and the worker both call it. // The read is the source of truth. Ship once, and only for the full amount. Settlement Settle(Order order, Attempt attempt, JsonElement payment) { // The key only ever reads its own merchant's payments (any other is a 404), so these checks catch a // mix-up on our side: a payment reference stored against the wrong order, or another currency. if (payment.GetProperty("paymentReference").GetString() != attempt.PaymentReference) return new(Outcome.Mismatch, $"paymentReference {payment.GetProperty("paymentReference")} is not {attempt.PaymentReference}"); if (payment.GetProperty("reference").GetString() != order.Id) return new(Outcome.Mismatch, $"reference {payment.GetProperty("reference")} is not {order.Id}"); if (payment.GetProperty("currency").GetString() != "EUR") return new(Outcome.Mismatch, $"currency {payment.GetProperty("currency")} is not EUR"); var state = payment.GetProperty("state").GetString(); var amount = payment.GetProperty("amount").GetInt64(); // once executed: the amount actually approved return state switch { "executed" when amount == order.Total => MarkPaid(order, attempt.PaymentReference!), "executed" => new(Outcome.Short, $"approved {amount} of {order.Total} cents"), "failed" or "abandoned" => new(Outcome.NotPaid), _ => new(Outcome.Pending, $"still {state}"), // an unknown state is never paid }; } // One atomic statement: only the call that changes the row ships. This is why a duplicate delivery, a second // worker pass, or the return page racing the worker can never ship twice. Fulfilment is a placeholder here: // in a live shop, insert a fulfilment job in the same commit, then process that job with retries and // an idempotency key the downstream system accepts. Settlement MarkPaid(Order order, string paymentReference) { if (Execute("UPDATE orders SET paid_at = $now, paid_by = $reference WHERE id = $id AND paid_at IS NULL", ("$now", DateTimeOffset.UtcNow.ToString("O")), ("$reference", paymentReference), ("$id", order.Id)) == 1) { log.LogInformation("Order {OrderId} paid; ship it", order.Id); return new(Outcome.Paid); } // Already paid. By this payment: a repeat, nothing to do. By another one: an earlier attempt completed // late (an ANNA payment, for example). Refund it; never ship twice. var paidBy = OrderById(order.Id)?.PaidBy; return paidBy == paymentReference ? new(Outcome.Paid) : new(Outcome.PaidTwice, $"order already paid by {paidBy}; refund {paymentReference}"); } Order? OrderById(string id) => Query("SELECT id, total, paid_at, paid_by FROM orders WHERE id = $id", ReadOrder, ("$id", id)).SingleOrDefault(); Attempt? ActiveAttempt(string orderId) => Query("SELECT idempotency_key, order_id, payment_reference, checkout_url FROM payment_attempts WHERE order_id = $order AND active = 1", ReadAttempt, ("$order", orderId)).SingleOrDefault(); Attempt? AttemptByPayment(string paymentReference) => Query("SELECT idempotency_key, order_id, payment_reference, checkout_url FROM payment_attempts WHERE payment_reference = $reference", ReadAttempt, ("$reference", paymentReference)).SingleOrDefault(); // A connection per operation: SqliteConnection is cheap, and pooled. Always parameters, never concatenated SQL. int Execute(string sql, params (string Name, object? Value)[] parameters) { using var connection = new SqliteConnection(connectionString); connection.Open(); using var command = Command(connection, sql, parameters); return command.ExecuteNonQuery(); // the number of rows changed } List Query(string sql, Func map, params (string Name, object? Value)[] parameters) { using var connection = new SqliteConnection(connectionString); connection.Open(); using var command = Command(connection, sql, parameters); using var reader = command.ExecuteReader(); List rows = []; while (reader.Read()) rows.Add(map(reader)); return rows; } // X-Mps-Signature: v1=, two values during a rotation. bool IsValidSignature(string timestamp, string signatureHeader, byte[] body) { if (!long.TryParse(timestamp, out var seconds) || Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - seconds) > 300) return false; // outside five minutes: a replay var signed = (byte[])[.. Encoding.UTF8.GetBytes($"{timestamp}."), .. body]; var expected = Encoding.ASCII.GetBytes(Convert.ToHexStringLower(HMACSHA256.HashData(Encoding.UTF8.GetBytes(webhookSecret), signed))); return signatureHeader.Split(',') .Select(static value => value.Trim()) .Where(static value => value.StartsWith("v1=")) .Any(value => CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(value[3..]), expected)); } // One call to MPS. Retries a 429 after Retry-After. Retries a 5xx or network error on a read, and on a // create that carries an Idempotency-Key: the key makes the retry return the payment the first call made. // A create without one is never retried, as it could open a second payment. async Task Send(HttpMethod method, string path, object? payload = null, string? idempotencyKey = null) { var retryable = method == HttpMethod.Get || idempotencyKey is not null; for (var attempt = 1; ; attempt++) { HttpResponseMessage response; try { using var request = new HttpRequestMessage(method, path) { Content = payload is null ? null : JsonContent.Create(payload) }; if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey); response = await mps.SendAsync(request); } catch (Exception e) when (e is HttpRequestException or TaskCanceledException) { if (retryable && attempt < 4) { await Task.Delay(TimeSpan.FromSeconds(1 << (attempt - 1))); continue; } return new(0, default, null); } var status = (int)response.StatusCode; var retryAfter = response.Headers.RetryAfter?.Delta; if (status == 429 && attempt < 3 && retryAfter is not { TotalSeconds: > 10 }) { await Task.Delay(retryAfter ?? TimeSpan.FromSeconds(1)); continue; } if (status >= 500 && retryable && attempt < 4) { await Task.Delay(TimeSpan.FromSeconds(1 << (attempt - 1))); continue; } var text = await response.Content.ReadAsStringAsync(); JsonElement body = default; try { if (text.Length > 0) body = JsonDocument.Parse(text).RootElement; } catch (JsonException e) { log.LogWarning("MPS answered {Status} with a body that is not JSON: {Error}", status, e.Message); } // 409 idempotency_key_in_use: the first call with this key is still running; the retry returns its payment. // Any other code (idempotency_key_expired, one this code does not know, or none) is final: never retried. if (status == 409 && idempotencyKey is not null && attempt < 4 && body.ValueKind == JsonValueKind.Object && body.TryGetProperty("code", out var code) && code.ToString() == "idempotency_key_in_use") { await Task.Delay(TimeSpan.FromSeconds(1)); continue; } return new(status, body, retryAfter); } } void LogFailure(string operation, MpsResult result) { switch (result.Status) { case 400 when result.Body.ValueKind == JsonValueKind.Object && result.Body.TryGetProperty("errors", out var errors): // A problem document: each field with its messages. Fix the request; do not retry it unchanged. foreach (var field in errors.EnumerateObject()) log.LogError("MPS {Operation} refused {Field}: {Messages}", operation, field.Name.StartsWith("Request.") ? field.Name["Request.".Length..] : field.Name, field.Value.ToString()); break; case 401: log.LogError("MPS {Operation}: 401, the API key is missing, wrong or revoked", operation); break; case 403: log.LogError("MPS {Operation}: 403, the key lacks the scope, or x-wallet-number is not one of your merchants", operation); break; case 404: log.LogError("MPS {Operation}: 404, no such payment for this merchant", operation); break; case 429: log.LogWarning("MPS {Operation}: 429, rate limited; Retry-After {Seconds}s", operation, result.RetryAfter?.TotalSeconds); break; case 0: log.LogError("MPS {Operation}: no response (network error or timeout)", operation); break; default: log.LogError("MPS {Operation}: {Status}", operation, result.Status); break; } } static SqliteCommand Command(SqliteConnection connection, string sql, (string Name, object? Value)[] parameters) { var command = connection.CreateCommand(); command.CommandText = sql; foreach (var (name, value) in parameters) command.Parameters.AddWithValue(name, value ?? DBNull.Value); return command; } static Order ReadOrder(SqliteDataReader row) => new(row.GetString(0), row.GetInt64(1), row.IsDBNull(2) ? null : row.GetString(2), row.IsDBNull(3) ? null : row.GetString(3)); static Attempt ReadAttempt(SqliteDataReader row) => new(row.GetString(0), row.GetString(1), row.IsDBNull(2) ? null : row.GetString(2), row.IsDBNull(3) ? null : row.GetString(3)); static IResult Html(string body, int status = 200) => Results.Content($"{body}", "text/html", Encoding.UTF8, status); static string Required(string name) => Environment.GetEnvironmentVariable(name) is { Length: > 0 } value ? value : throw new InvalidOperationException($"Set {name}"); record Order(string Id, long Total, string? PaidAt, string? PaidBy); // Total in cents record Attempt(string IdempotencyKey, string OrderId, string? PaymentReference, string? CheckoutUrl); record InboxRow(string DeliveryId, string PaymentReference, long Attempts); record Settlement(Outcome Outcome, string? Reason = null); record Confirmation(Verdict Verdict, string? Error = null); record MpsResult(int Status, JsonElement Body, TimeSpan? RetryAfter); enum Outcome { Paid, Short, NotPaid, Pending, Mismatch, PaidTwice } enum Verdict { Processed, Temporary, Permanent } // done; try again later; a person must look ```
Node 22.13 or later, built-in `node:http`, `node:crypto`, `node:sqlite` and `fetch`; no packages. Run it: `npx tsx server.ts` (on Node 23.6 or later, `node server.ts` works too). The orders and the webhook inbox are kept in `mps-example.db` in the working directory, so they survive a restart. ```ts title="server.ts" // server.ts: Node 22.13+, built-in node:http, node:sqlite and fetch, no dependencies. import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; const MPS = 'https://gateway.mps-emi.com'; const apiKey = required('MPS_API_KEY'); // mps_test_… or mps_live_… const webhookSecret = required('MPS_WEBHOOK_SECRET'); // shown once, next to the API key const publicBaseUrl = required('PUBLIC_BASE_URL').replace(/\/+$/, ''); const walletNumber = process.env.MPS_WALLET_NUMBER; type Order = { id: string; total: number; paid_at: string | null; paid_by: string | null }; type Attempt = { idempotency_key: string; order_id: string; payment_reference: string | null; checkout_url: string | null; active: number }; type InboxRow = { delivery_id: string; payment_reference: string; attempts: number }; type Payment = { paymentReference: string; state: string; amount: number; currency: string; reference: string | null }; type MpsResult = { status: number; body: any; retryAfter?: number }; type Outcome = 'paid' | 'short' | 'not-paid' | 'pending' | 'mismatch' | 'paid-twice'; type Settlement = { outcome: Outcome; reason?: string }; type Confirmation = { outcome: 'processed' } | { outcome: 'temporary' | 'permanent'; error: string }; // SQLite stands in for your database: the same tables and statements work there. const db = new DatabaseSync('mps-example.db'); db.exec(` CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see markPaid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); `); const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const unixNow = () => Math.floor(Date.now() / 1000); // 1. Create the payment and send the shopper to the MPS checkout. ?retry= tries again for an order that exists: // the order stays, with every attempt it ever had, so a late payment on an earlier attempt still finds it. async function checkout(url: URL, res: ServerResponse) { let order = findOrder(url.searchParams.get('retry') ?? ''); if (order?.paid_at) return html(res, '

This order is already paid.

'); let attempt = order ? activeAttempt(order.id) : undefined; if (attempt?.payment_reference) { // The last attempt did open a payment: what became of it decides. const read = await readPayment(attempt.payment_reference); if (read.status !== 200) { logFailure('read', read); return html(res, '

We could not check your previous payment just now. Try again in a moment.

', 502); } const state: string = read.body.data.state; // Pending: the shopper can still pay it, so reopen that checkout, never a second one. if (state === 'pending') return res.writeHead(303, { Location: attempt.checkout_url! }).end(); // Executed, or a state this code does not know: the return page settles it. if (state !== 'failed' && state !== 'abandoned') return res.writeHead(303, { Location: `/return?order=${order!.id}` }).end(); // Failed or abandoned: a new attempt for the same order, with a new key. Closing the old attempt in one // statement lets one request win: two clicks open one attempt, not two. const { changes } = db.prepare('UPDATE payment_attempts SET active = 0 WHERE idempotency_key = ? AND active = 1').run(attempt.idempotency_key); if (changes !== 1) return html(res, '

Your payment was just restarted in another tab. Use that one.

', 409); attempt = undefined; } if (!order) { order = { id: `order-${randomUUID().slice(0, 8)}`, total: 1995, paid_at: null, paid_by: null }; // cents db.prepare('INSERT INTO orders (id, total) VALUES (?, ?)').run(order.id, order.total); } if (!attempt) { // One Idempotency-Key per attempt, stored BEFORE calling MPS. Every retry with it, by mps() or by // "Try again" below, returns the payment the first call made, never a second one. attempt = { idempotency_key: randomUUID(), order_id: order.id, payment_reference: null, checkout_url: null, active: 1 }; db.prepare('INSERT INTO payment_attempts (idempotency_key, order_id, created_at) VALUES (?, ?, ?)') .run(attempt.idempotency_key, order.id, new Date().toISOString()); } const returnUrl = `${publicBaseUrl}/return?order=${order.id}`; // MPS appends nothing: carry your own id // Built from the order alone, so a retry sends the same body: the same key with another body is a 400. const result = await mps('POST', '/api/payments/internet/create', { amount: order.total, reference: order.id, successUrl: returnUrl, failureUrl: returnUrl, callbackUrl: `${publicBaseUrl}/webhooks/mps`, }, attempt.idempotency_key); if (result.status !== 200) { logFailure('create', result); // The same attempt and key: if the failed call did open a payment, trying again returns that one. return html(res, `

We could not start the payment.

`, 502); } const { paymentReference, checkoutUrl } = result.body.data; // Store them BEFORE redirecting: the webhook and the worker find the order by the reference. db.prepare('UPDATE payment_attempts SET payment_reference = ?, checkout_url = ? WHERE idempotency_key = ?') .run(paymentReference, checkoutUrl, attempt.idempotency_key); res.writeHead(303, { Location: checkoutUrl }).end(); // never log it: whoever has it can pay } // 2. The webhook route: verify, store the webhook in the inbox, then answer 2xx. A 2xx means "accepted // responsibility": after it, MPS does not send this webhook again, so nothing is acknowledged before // it is stored. It calls nothing else (no MPS read, no background task): the worker (4) does the work, so // the answer stays well inside the 10-second budget. async function webhook(req: IncomingMessage, res: ServerResponse) { const body = await rawBody(req); // the raw bytes: verify BEFORE parsing if (!isValidSignature(header(req, 'x-mps-timestamp'), header(req, 'x-mps-signature'), body)) { return res.writeHead(401).end(); } const notification = JSON.parse(body.toString('utf8')); if (notification.eventType !== 'payment.received') return res.writeHead(200).end(); // new event: ignore try { // Every retry of a webhook carries the same delivery id: the primary key makes a repeat a no-op. db.prepare(`INSERT INTO webhook_inbox (delivery_id, payment_reference, received_at, next_attempt_at) VALUES (?, ?, ?, ?) ON CONFLICT(delivery_id) DO NOTHING`) .run(header(req, 'x-mps-delivery-id'), notification.paymentReference, new Date().toISOString(), unixNow()); } catch (err) { console.error('Storing the notification failed; answering 500 so MPS retries', err); return res.writeHead(500).end(); // never acknowledge work that is not stored } res.writeHead(200).end(); } // 3. The shopper's return: read the payment. Landing here proves nothing. It settles through the same // settle() as the worker, so both paths apply the same checks. async function shopperReturn(url: URL, res: ServerResponse) { const order = findOrder(url.searchParams.get('order') ?? ''); const attempt = order ? activeAttempt(order.id) : undefined; if (!order || !attempt?.payment_reference) return res.writeHead(404).end(); const result = await readPayment(attempt.payment_reference); if (result.status !== 200) { logFailure('read', result); return html(res, '

We could not check your payment just now. Refresh this page in a moment.

', 502); } const next = Number(url.searchParams.get('attempt') ?? 0) + 1; switch (settle(order, attempt, result.body.data).outcome) { case 'paid': return html(res, '

Thank you, your order is paid.

'); case 'paid-twice': return html(res, '

This order was already paid by an earlier payment. We will refund this one.

'); case 'short': return html(res, '

Your card was approved for less than the order total. We have not shipped; please contact us.

'); case 'mismatch': return html(res, '

We could not match this payment to your order. We have not shipped; please contact us.

'); case 'not-paid': // a new attempt for the same order: the order keeps its id and its earlier payments return html(res, `

Your payment did not go through.

`); default: // Still pending (or a state we do not know): re-read every 2 s for about 30 s, then let the webhook settle it. return next <= 15 ? html(res, `

Confirming your payment…

`) : html(res, '

We are confirming your payment and will e-mail you as soon as it is.

'); } } // 4. The worker: the business operation, separate from receiving the webhook. Every 5 seconds it takes // the inbox rows that are due, reads each payment and settles its order. The rows are in the database, so a // crash or restart after the webhook's 2xx loses nothing: the next pass picks them up again (at least once), // and markPaid makes a second pass harmless. One worker per process; with several instances, claim a row // first (UPDATE ... SET status = 'processing' ... RETURNING) or use your queue. async function confirmPendingWebhooks() { const due = db.prepare(`SELECT delivery_id, payment_reference, attempts FROM webhook_inbox WHERE status = 'pending' AND next_attempt_at <= ? ORDER BY received_at LIMIT 20`) .all(unixNow()) as InboxRow[]; for (const row of due) { let confirmation: Confirmation; try { confirmation = await confirmPayment(row.payment_reference); } catch (err) { confirmation = { outcome: 'temporary', error: err instanceof Error ? err.message : String(err) }; } try { recordOutcome(row, confirmation); // one bad row never stops the loop } catch (err) { console.error(`Recording delivery ${row.delivery_id} failed; the next pass retries`, err); } } } async function confirmPayment(paymentReference: string): Promise { // 4.1 The attempt this payment belongs to, active or not: a late ANNA payment on an earlier attempt still belongs to its order. const attempt = attemptByPayment(paymentReference); const order = attempt ? findOrder(attempt.order_id) : undefined; if (!attempt || !order) return { outcome: 'permanent', error: 'unknown payment' }; // 4.2 Read the payment: the read is the source of truth, the webhook only says "look". const result = await readPayment(paymentReference); if (result.status !== 200) { logFailure('read', result); // 400, 401, 403, 404: fix the configuration; retrying cannot help. Network, 429 and 5xx: try again later. return [400, 401, 403, 404].includes(result.status) ? { outcome: 'permanent', error: `read answered ${result.status}` } : { outcome: 'temporary', error: `read answered ${result.status}` }; } const settlement = settle(order, attempt, result.body.data); switch (settlement.outcome) { case 'paid': case 'not-paid': // shipped, or nothing to ship return { outcome: 'processed' }; case 'pending': return { outcome: 'temporary', error: settlement.reason! }; default: // short, mismatch, paid-twice: a person decides; never ship return { outcome: 'permanent', error: settlement.reason! }; } } // 4.3 The one place a payment is matched to its order and settled; the return page and the worker both call it. // The read is the source of truth. Ship once, and only for the full amount. function settle(order: Order, attempt: Attempt, payment: Payment): Settlement { // The key only ever reads its own merchant's payments (any other is a 404), so these checks catch a // mix-up on our side: a payment reference stored against the wrong order, or another currency. if (payment.paymentReference !== attempt.payment_reference) return { outcome: 'mismatch', reason: `paymentReference is ${payment.paymentReference}, not ${attempt.payment_reference}` }; if (payment.reference !== order.id) return { outcome: 'mismatch', reason: `reference is ${payment.reference}, not ${order.id}` }; if (payment.currency !== 'EUR') return { outcome: 'mismatch', reason: `currency is ${payment.currency}, not EUR` }; if (payment.state === 'executed') { return payment.amount === order.total // amount = approved amount ? markPaid(order, payment.paymentReference) : { outcome: 'short', reason: `approved ${payment.amount} of ${order.total} cents` }; } if (payment.state === 'failed' || payment.state === 'abandoned') return { outcome: 'not-paid' }; return { outcome: 'pending', reason: `still ${payment.state}` }; // an unknown state is never paid } // One atomic statement: a duplicate delivery, a second worker pass, or the return page racing the worker // can never ship twice, because only one of them changes the row. Fulfilment is a placeholder here: in a // live shop, insert a fulfilment job in the same commit, then process that job with retries and an // idempotency key the downstream system accepts. function markPaid(order: Order, paymentReference: string): Settlement { const { changes } = db.prepare('UPDATE orders SET paid_at = ?, paid_by = ? WHERE id = ? AND paid_at IS NULL') .run(new Date().toISOString(), paymentReference, order.id); if (changes === 1) { console.log(`Order ${order.id} paid; ship it`); return { outcome: 'paid' }; } // Already paid. By this payment: a repeat, nothing to do. By another one: an earlier attempt completed // late (an ANNA payment, for example). Refund it; never ship twice. const paidBy = findOrder(order.id)?.paid_by; return paidBy === paymentReference ? { outcome: 'paid' } : { outcome: 'paid-twice', reason: `order already paid by ${paidBy}; refund ${paymentReference}` }; } // 4.4 Record the outcome. A temporary failure is retried with backoff (5 s doubling, at most an hour) up to // 8 attempts. Failed rows stay for investigation: SELECT * FROM webhook_inbox WHERE status = 'failed'. function recordOutcome(row: InboxRow, confirmation: Confirmation) { if (confirmation.outcome === 'processed') { db.prepare(`UPDATE webhook_inbox SET status = 'processed', last_error = NULL WHERE delivery_id = ?`).run(row.delivery_id); return; } console.warn(`Delivery ${row.delivery_id} (${row.payment_reference}): ${confirmation.outcome} failure, ${confirmation.error}`); if (confirmation.outcome === 'permanent') { db.prepare(`UPDATE webhook_inbox SET status = 'failed', last_error = ? WHERE delivery_id = ?`).run(confirmation.error, row.delivery_id); return; } const attempts = row.attempts + 1; db.prepare(`UPDATE webhook_inbox SET attempts = ?, status = ?, next_attempt_at = ?, last_error = ? WHERE delivery_id = ?`) .run(attempts, attempts >= 8 ? 'failed' : 'pending', unixNow() + Math.min(5 * 2 ** attempts, 3600), confirmation.error, row.delivery_id); } const findOrder = (id: string) => db.prepare('SELECT * FROM orders WHERE id = ?').get(id) as Order | undefined; const activeAttempt = (orderId: string) => db.prepare('SELECT * FROM payment_attempts WHERE order_id = ? AND active = 1').get(orderId) as Attempt | undefined; const attemptByPayment = (paymentReference: string) => db.prepare('SELECT * FROM payment_attempts WHERE payment_reference = ?').get(paymentReference) as Attempt | undefined; // X-Mps-Signature: v1=, two values during a rotation. function isValidSignature(timestamp: string, signatureHeader: string, body: Buffer): boolean { if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // a replay const expected = Buffer.from(createHmac('sha256', webhookSecret).update(`${timestamp}.`).update(body).digest('hex')); return signatureHeader .split(',') .map((value) => value.trim()) .filter((value) => value.startsWith('v1=')) .map((value) => Buffer.from(value.slice(3))) .some((candidate) => candidate.length === expected.length && timingSafeEqual(candidate, expected)); } const readPayment = (paymentReference: string) => mps('GET', `/api/payments/internet/${encodeURIComponent(paymentReference)}`); // One call to MPS. Retries a 429 after Retry-After. Retries a 5xx or network error on a read, and on a // create that carries an Idempotency-Key: the key makes the retry return the payment the first call made. // A create without one is never retried, as it could open a second payment. async function mps(method: 'GET' | 'POST', path: string, payload?: unknown, idempotencyKey?: string): Promise { const headers: Record = { Authorization: `Bearer ${apiKey}` }; // Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if (walletNumber) headers['x-wallet-number'] = walletNumber; if (payload !== undefined) headers['Content-Type'] = 'application/json'; if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey; const retryable = method === 'GET' || idempotencyKey !== undefined; for (let attempt = 1; ; attempt++) { let res: Response; try { res = await fetch(MPS + path, { method, headers, body: payload === undefined ? undefined : JSON.stringify(payload), signal: AbortSignal.timeout(15_000), }); } catch { if (retryable && attempt < 4) { await sleep(1000 * 2 ** (attempt - 1)); continue; } return { status: 0, body: null }; } const retryAfter = Number(res.headers.get('retry-after')) || undefined; if (res.status === 429 && attempt < 3 && (retryAfter ?? 1) <= 10) { await sleep((retryAfter ?? 1) * 1000); continue; } if (res.status >= 500 && retryable && attempt < 4) { await sleep(1000 * 2 ** (attempt - 1)); continue; } const text = await res.text(); let body: any = null; try { body = text ? JSON.parse(text) : null; } catch (err) { console.warn(`MPS answered ${res.status} with a body that is not JSON`, err); } // 409 idempotency_key_in_use: the first call with this key is still running; the retry returns its payment. // Any other code (idempotency_key_expired, one this code does not know, or none) is final: never retried. if (res.status === 409 && idempotencyKey && attempt < 4 && body?.code === 'idempotency_key_in_use') { await sleep(1000); continue; } return { status: res.status, body, retryAfter }; } } function logFailure(operation: string, { status, body, retryAfter }: MpsResult) { if (status === 400 && body?.errors) { // A problem document: each field with its messages. Fix the request; do not retry it unchanged. for (const [field, messages] of Object.entries(body.errors)) { console.error(`MPS ${operation} refused ${field.replace(/^Request\./, '')}: ${(messages as string[]).join('; ')}`); } } else if (status === 401) console.error(`MPS ${operation}: 401, the API key is missing, wrong or revoked`); else if (status === 403) console.error(`MPS ${operation}: 403, the key lacks the scope, or x-wallet-number is not one of your merchants`); else if (status === 404) console.error(`MPS ${operation}: 404, no such payment for this merchant`); else if (status === 429) console.warn(`MPS ${operation}: 429, rate limited; Retry-After ${retryAfter}s`); else if (status === 0) console.error(`MPS ${operation}: no response (network error or timeout)`); else console.error(`MPS ${operation}: ${status}`); } async function rawBody(req: IncomingMessage): Promise { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); return Buffer.concat(chunks); } function header(req: IncomingMessage, name: string): string { const value = req.headers[name]; return Array.isArray(value) ? value.join(',') : value ?? ''; } function html(res: ServerResponse, body: string, status = 200) { res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' }).end(`${body}`); } function required(name: string): string { const value = process.env[name]; if (!value) throw new Error(`Set ${name}`); return value; } const server = createServer(async (req, res) => { const url = new URL(req.url ?? '/', 'http://localhost'); try { if (req.method === 'GET' && url.pathname === '/') { return html(res, '
'); } if (req.method === 'POST' && url.pathname === '/checkout') return await checkout(url, res); if (req.method === 'POST' && url.pathname === '/webhooks/mps') return await webhook(req, res); if (req.method === 'GET' && url.pathname === '/return') return await shopperReturn(url, res); res.writeHead(404).end(); } catch (err) { console.error(err); if (!res.headersSent) res.writeHead(500).end(); } }).listen(Number(process.env.PORT ?? 8000)); // One pass at a time: a pass still running (a slow read with retries) makes the next tick skip. let pass: Promise | null = null; const worker = setInterval(() => { pass ??= confirmPendingWebhooks() .catch((err) => console.error('Worker pass failed; the next pass retries', err)) .finally(() => { pass = null; }); }, 5_000); // Stop cleanly: no new pass, no new requests, let the current pass finish, then close the database. for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.once(signal, async () => { clearInterval(worker); await Promise.all([new Promise((resolve) => server.close(resolve)), pass]); db.close(); }); } ```
Python 3.10 or later with Flask and requests; the database is the built-in `sqlite3`. Run it: `pip install flask requests`, then `python app.py`. It creates `mps-example.db` in the working directory; the worker runs in the same process. ```python title="app.py" # app.py: Python 3.10+, Flask and requests. import hashlib import hmac import json import logging import os import sqlite3 import threading import time import uuid from contextlib import contextmanager from datetime import datetime, timezone from urllib.parse import quote import requests from flask import Flask, Response, redirect, request MPS = "https://gateway.mps-emi.com" API_KEY = os.environ["MPS_API_KEY"] # mps_test_… or mps_live_… WEBHOOK_SECRET = os.environ["MPS_WEBHOOK_SECRET"] # shown once, next to the API key PUBLIC_BASE_URL = os.environ["PUBLIC_BASE_URL"].rstrip("/") WALLET_NUMBER = os.environ.get("MPS_WALLET_NUMBER") session = requests.Session() session.headers["Authorization"] = f"Bearer {API_KEY}" # Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if WALLET_NUMBER: session.headers["x-wallet-number"] = WALLET_NUMBER # SQLite stands in for your database: the same tables and statements work there. DB_PATH = "mps-example.db" SCHEMA = """ CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see mark_paid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); """ @contextmanager def db(): """One connection per operation: sqlite3 connections belong to the thread that opened them.""" conn = sqlite3.connect(DB_PATH, timeout=10) conn.row_factory = sqlite3.Row try: with conn: # commits on success, rolls back on an exception yield conn finally: conn.close() with db() as conn: conn.executescript(SCHEMA) app = Flask(__name__) logging.basicConfig(level=logging.INFO) @app.get("/") def home(): return html('
') # 1. Create the payment and send the shopper to the MPS checkout. ?retry= tries again for an order that exists: # the order stays, with every attempt it ever had, so a late payment on an earlier attempt still finds it. @app.post("/checkout") def checkout(): with db() as conn: order = conn.execute("SELECT * FROM orders WHERE id = ?", (request.args.get("retry", ""),)).fetchone() attempt = active_attempt(conn, order["id"]) if order is not None else None if order is not None and order["paid_at"] is not None: return html("

This order is already paid.

") if attempt is not None and attempt["payment_reference"] is not None: # The last attempt did open a payment: what became of it decides. status, body, retry_after = read_payment(attempt["payment_reference"]) if status != 200: log_failure("read", status, body, retry_after) return html("

We could not check your previous payment just now. Try again in a moment.

", 502) state = body["data"]["state"] if state == "pending": # the shopper can still pay it: reopen that checkout, never a second one return redirect(attempt["checkout_url"], code=303) if state not in ("failed", "abandoned"): # executed, or a state this code does not know: the return page settles it return redirect(f"/return?order={order['id']}", code=303) # Failed or abandoned: a new attempt for the same order, with a new key. Closing the old attempt in one # statement lets one request win: two clicks open one attempt, not two. with db() as conn: closed = conn.execute("UPDATE payment_attempts SET active = 0 WHERE idempotency_key = ? AND active = 1", (attempt["idempotency_key"],)).rowcount if closed != 1: return html("

Your payment was just restarted in another tab. Use that one.

", 409) attempt = None with db() as conn: if order is None: order = {"id": f"order-{uuid.uuid4().hex[:8]}", "total": 1995} # cents conn.execute("INSERT INTO orders (id, total) VALUES (?, ?)", (order["id"], order["total"])) if attempt is None: # One Idempotency-Key per attempt, stored BEFORE calling MPS. Every retry with it, by mps() or by # "Try again" below, returns the payment the first call made, never a second one. attempt = {"idempotency_key": str(uuid.uuid4())} conn.execute("INSERT INTO payment_attempts (idempotency_key, order_id, created_at) VALUES (?, ?, ?)", (attempt["idempotency_key"], order["id"], utc_now())) return_url = f"{PUBLIC_BASE_URL}/return?order={order['id']}" # MPS appends nothing: carry your own id # Built from the order alone, so a retry sends the same body: the same key with another body is a 400. status, body, retry_after = mps("POST", "/api/payments/internet/create", { "amount": order["total"], "reference": order["id"], "successUrl": return_url, "failureUrl": return_url, "callbackUrl": f"{PUBLIC_BASE_URL}/webhooks/mps", }, idempotency_key=attempt["idempotency_key"]) if status != 200: log_failure("create", status, body, retry_after) # The same attempt and key: if the failed call did open a payment, trying again returns that one. return html(f'

We could not start the payment.

' "
", 502) data = body["data"] with db() as conn: # store them BEFORE redirecting: the webhook and the worker find the order by the reference conn.execute("UPDATE payment_attempts SET payment_reference = ?, checkout_url = ? WHERE idempotency_key = ?", (data["paymentReference"], data["checkoutUrl"], attempt["idempotency_key"])) return redirect(data["checkoutUrl"], code=303) # never log it: whoever has it can pay # 2. The webhook route: verify, store the webhook in the inbox, then answer 2xx. # A 2xx means "accepted responsibility": after it, MPS does not send this webhook again. So store it # first, and do nothing else here: no read, no background task. The worker (4) does the work. @app.post("/webhooks/mps") def webhook(): body = request.get_data() # the raw bytes: verify BEFORE parsing (not request.get_json()) if not is_valid_signature(request.headers.get("X-Mps-Timestamp", ""), request.headers.get("X-Mps-Signature", ""), body): return "", 401 notification = json.loads(body) if notification["eventType"] != "payment.received": return "", 200 # a new event type: ignore it, never fail on it # Every retry of a webhook carries the same delivery id: the primary key turns a repeat into a no-op. try: with db() as conn: conn.execute("INSERT INTO webhook_inbox (delivery_id, payment_reference, received_at, next_attempt_at) " "VALUES (?, ?, ?, ?) ON CONFLICT(delivery_id) DO NOTHING", (request.headers.get("X-Mps-Delivery-Id", ""), notification["paymentReference"], utc_now(), int(time.time()))) except Exception: app.logger.exception("Could not store the notification; MPS will retry it") return "", 500 # never acknowledge work that is not stored return "", 200 # 3. The shopper's return: read the payment. Landing here proves nothing. It settles through the same # settle() as the worker, so both paths apply the same checks. @app.get("/return") def shopper_return(): with db() as conn: order = conn.execute("SELECT * FROM orders WHERE id = ?", (request.args.get("order", ""),)).fetchone() attempt = active_attempt(conn, order["id"]) if order is not None else None if attempt is None or attempt["payment_reference"] is None: return "", 404 status, body, retry_after = read_payment(attempt["payment_reference"]) if status != 200: log_failure("read", status, body, retry_after) return html("

We could not check your payment just now. Refresh this page in a moment.

", 502) outcome, _ = settle(order, attempt, body["data"]) if outcome == "paid": return html("

Thank you, your order is paid.

") if outcome == "paid-twice": return html("

This order was already paid by an earlier payment. We will refund this one.

") if outcome == "short": return html("

Your card was approved for less than the order total. We have not shipped; please contact us.

") if outcome == "mismatch": return html("

We could not match this payment to your order. We have not shipped; please contact us.

") if outcome == "not-paid": # a new attempt for the same order: the order keeps its id and its earlier payments return html(f'

Your payment did not go through.

' "
") # Still pending (or a state we do not know): re-read every 2 s for about 30 s, then let the worker settle it. attempt_no = request.args.get("attempt", "0") next_attempt = (int(attempt_no) if attempt_no.isdigit() else 0) + 1 if next_attempt <= 15: return html(f'' "

Confirming your payment…

") return html("

We are confirming your payment and will e-mail you as soon as it is.

") # 4. The worker: the business operation, separate from receiving the webhook. # One worker per process. With several instances, claim a row first (UPDATE ... SET status = 'processing' ... RETURNING) # or use your queue. After a restart, pending rows are picked up again (at least once); mark_paid makes that safe. stopping = threading.Event() def confirm_pending_webhooks() -> None: while not stopping.wait(5): try: with db() as conn: due = conn.execute("SELECT * FROM webhook_inbox WHERE status = 'pending' AND next_attempt_at <= ? " "ORDER BY received_at LIMIT 20", (int(time.time()),)).fetchall() except Exception: app.logger.exception("Reading the webhook inbox failed; the next pass retries") continue for row in due: try: # one bad row never stops the loop try: outcome, error = confirm(row["payment_reference"]) except Exception as exc: outcome, error = "temporary", str(exc) record_outcome(row, outcome, error) except Exception: app.logger.exception("Recording delivery %s failed; the next pass retries", row["delivery_id"]) def confirm(payment_reference: str) -> tuple[str, str | None]: """Returns ("processed", None), ("temporary", why) or ("permanent", why).""" with db() as conn: # Any attempt, active or not: a late ANNA payment on an earlier attempt still belongs to its order. attempt = conn.execute("SELECT * FROM payment_attempts WHERE payment_reference = ?", (payment_reference,)).fetchone() order = conn.execute("SELECT * FROM orders WHERE id = ?", (attempt["order_id"],)).fetchone() if attempt else None if order is None: return "permanent", "unknown payment" status, body, retry_after = read_payment(payment_reference) if status != 200: log_failure("read", status, body, retry_after) if status in (400, 401, 403, 404): return "permanent", f"MPS answered {status}" # fix the configuration; retrying cannot help return "temporary", f"MPS answered {status}" if status else "no response from MPS" outcome, reason = settle(order, attempt, body["data"]) if outcome in ("paid", "not-paid"): return "processed", None # shipped, or nothing to ship if outcome == "pending": return "temporary", reason return "permanent", reason # short, mismatch, paid-twice: a person decides; never ship def settle(order: sqlite3.Row, attempt: sqlite3.Row, payment: dict) -> tuple[str, str | None]: """The one place a payment is matched to its order and settled; the return page and the worker both call it. The read is the source of truth. Ship once, and only for the full amount.""" # The key only reads its own merchant's payments (another merchant's is a 404), so these checks catch a # mix-up on our side: a payment reference stored against the wrong order, or another currency. for field, expected in (("paymentReference", attempt["payment_reference"]), ("reference", order["id"]), ("currency", "EUR")): if payment.get(field) != expected: return "mismatch", f"{field} {payment.get(field)!r}, expected {expected!r}" if payment["state"] == "executed" and payment["amount"] == order["total"]: # amount = approved amount return mark_paid(order, payment["paymentReference"]) if payment["state"] == "executed": return "short", f"approved {payment['amount']} of {order['total']} cents" if payment["state"] in ("failed", "abandoned"): return "not-paid", None return "pending", f"still {payment['state']}" # an unknown state is never paid def mark_paid(order: sqlite3.Row, payment_reference: str) -> tuple[str, str | None]: """One atomic statement: a duplicate delivery, a second worker pass or the return page racing the worker can never ship twice. Fulfilment is a placeholder here: in a live shop, insert a fulfilment job in the same commit, then process that job with retries and an idempotency key the downstream system accepts.""" with db() as conn: changed = conn.execute("UPDATE orders SET paid_at = ?, paid_by = ? WHERE id = ? AND paid_at IS NULL", (utc_now(), payment_reference, order["id"])).rowcount if changed == 1: app.logger.info("Order %s paid; ship it", order["id"]) return "paid", None # Already paid. By this payment: a repeat, nothing to do. By another one: an earlier attempt completed # late (an ANNA payment, for example). Refund it; never ship twice. paid_by = conn.execute("SELECT paid_by FROM orders WHERE id = ?", (order["id"],)).fetchone()["paid_by"] if paid_by == payment_reference: return "paid", None return "paid-twice", f"order already paid by {paid_by}; refund {payment_reference}" def active_attempt(conn: sqlite3.Connection, order_id: str) -> sqlite3.Row | None: return conn.execute("SELECT * FROM payment_attempts WHERE order_id = ? AND active = 1", (order_id,)).fetchone() def record_outcome(row: sqlite3.Row, outcome: str, error: str | None) -> None: """Failed rows stay for investigation: SELECT * FROM webhook_inbox WHERE status = 'failed'.""" with db() as conn: if outcome == "processed": conn.execute("UPDATE webhook_inbox SET status = 'processed', last_error = NULL WHERE delivery_id = ?", (row["delivery_id"],)) elif outcome == "temporary" and row["attempts"] + 1 < 8: attempts = row["attempts"] + 1 # back off: 10 s, 20 s, 40 s, … at most an hour conn.execute("UPDATE webhook_inbox SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE delivery_id = ?", (attempts, int(time.time()) + min(5 * 2 ** attempts, 3600), error, row["delivery_id"])) else: # permanent, or temporary for the 8th time conn.execute("UPDATE webhook_inbox SET status = 'failed', attempts = attempts + ?, last_error = ? " "WHERE delivery_id = ?", (1 if outcome == "temporary" else 0, error, row["delivery_id"])) app.logger.error("Delivery %s failed: %s", row["delivery_id"], error) def is_valid_signature(timestamp: str, signature_header: str, body: bytes) -> bool: """X-Mps-Signature: v1=, two values during a rotation.""" if not (timestamp.isascii() and timestamp.isdigit() and len(timestamp) <= 12) or abs(time.time() - int(timestamp)) > 300: return False # a replay expected = hmac.new(WEBHOOK_SECRET.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest() return any( hmac.compare_digest(expected.encode(), value.strip().removeprefix("v1=").encode()) for value in signature_header.split(",") if value.strip().startswith("v1=") ) def read_payment(payment_reference: str): return mps("GET", f"/api/payments/internet/{quote(payment_reference, safe='')}") def mps(method: str, path: str, payload: dict | None = None, idempotency_key: str | None = None): """One call to MPS. Retries a 429 after Retry-After. Retries a 5xx or network error on a read, and on a create that carries an Idempotency-Key: the key makes the retry return the payment the first call made. A create without one is never retried, as it could open a second payment.""" headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None retryable = method == "GET" or idempotency_key is not None attempt = 0 while True: attempt += 1 try: res = session.request(method, MPS + path, json=payload, headers=headers, timeout=15) except requests.RequestException: if retryable and attempt < 4: time.sleep(2 ** (attempt - 1)) continue return 0, None, None header = res.headers.get("Retry-After", "") retry_after = int(header) if header.isdigit() else None if res.status_code == 429 and attempt < 3 and (retry_after or 1) <= 10: time.sleep(retry_after or 1) continue if res.status_code >= 500 and retryable and attempt < 4: time.sleep(2 ** (attempt - 1)) continue try: body = res.json() except ValueError: body = None # 409 idempotency_key_in_use: the first call with this key is still running; the retry returns its payment. # Any other code (idempotency_key_expired, one this code does not know, or none) is final: never retried. if (res.status_code == 409 and idempotency_key and attempt < 4 and isinstance(body, dict) and body.get("code") == "idempotency_key_in_use"): time.sleep(1) continue return res.status_code, body, retry_after def log_failure(operation: str, status: int, body, retry_after) -> None: if status == 400 and isinstance(body, dict) and body.get("errors"): # A problem document: each field with its messages. Fix the request; do not retry it unchanged. for field, messages in body["errors"].items(): app.logger.error("MPS %s refused %s: %s", operation, field.removeprefix("Request."), "; ".join(messages)) elif status == 401: app.logger.error("MPS %s: 401, the API key is missing, wrong or revoked", operation) elif status == 403: app.logger.error("MPS %s: 403, the key lacks the scope, or x-wallet-number is not one of your merchants", operation) elif status == 404: app.logger.error("MPS %s: 404, no such payment for this merchant", operation) elif status == 429: app.logger.warning("MPS %s: 429, rate limited; Retry-After %ss", operation, retry_after) elif status == 0: app.logger.error("MPS %s: no response (network error or timeout)", operation) else: app.logger.error("MPS %s: %s", operation, status) def utc_now() -> str: return datetime.now(timezone.utc).isoformat() def html(body: str, status: int = 200) -> Response: return Response(f"{body}", status, mimetype="text/html") if __name__ == "__main__": worker = threading.Thread(target=confirm_pending_webhooks, daemon=True) worker.start() try: app.run(port=8000) finally: stopping.set() # Ctrl+C: let the worker finish the row it is on, then stop worker.join() ```
PHP 8.2 or later with the `curl` and `pdo_sqlite` extensions; no framework. Run it: `php -S localhost:8000 index.php` (the file is the router, so pass it), and the worker that works through the webhook inbox beside it: `while true; do php index.php; sleep 5; done`. In production, run `php index.php` from cron every minute. ```php title="index.php" html('
'), $method === 'POST' && $path === '/checkout' => checkout(), $method === 'POST' && $path === '/webhooks/mps' => webhook(), $method === 'GET' && $path === '/return' => shopper_return(), default => http_response_code(404), }; // 1. Create the payment and send the shopper to the MPS checkout. ?retry= tries again for an order that exists: // the order stays, with every attempt it ever had, so a late payment on an earlier attempt still finds it. function checkout(): void { $order = query('SELECT * FROM orders WHERE id = ?', [$_GET['retry'] ?? ''])->fetch() ?: null; if ($order !== null && $order['paid_at'] !== null) { html('

This order is already paid.

'); return; } $attempt = $order === null ? null : active_attempt($order['id']); if ($attempt !== null && $attempt['payment_reference'] !== null) { // The last attempt did open a payment: what became of it decides. $read = read_payment($attempt['payment_reference']); if ($read['status'] !== 200) { log_failure('read', $read); html('

We could not check your previous payment just now. Try again in a moment.

', 502); return; } $state = $read['body']['data']['state']; if ($state === 'pending') { // the shopper can still pay it: reopen that checkout, never a second one header('Location: ' . $attempt['checkout_url'], true, 303); return; } if ($state !== 'failed' && $state !== 'abandoned') { // executed, or a state this code does not know: the return page settles it header('Location: /return?order=' . urlencode($order['id']), true, 303); return; } // Failed or abandoned: a new attempt for the same order, with a new key. Closing the old attempt in one // statement lets one request win: two clicks open one attempt, not two. if (query('UPDATE payment_attempts SET active = 0 WHERE idempotency_key = ? AND active = 1', [$attempt['idempotency_key']])->rowCount() !== 1) { html('

Your payment was just restarted in another tab. Use that one.

', 409); return; } $attempt = null; } if ($order === null) { $order = ['id' => 'order-' . bin2hex(random_bytes(4)), 'total' => 1995]; // total in cents query('INSERT INTO orders (id, total) VALUES (?, ?)', [$order['id'], $order['total']]); } if ($attempt === null) { // One Idempotency-Key per attempt, stored BEFORE calling MPS. Every retry with it, by mps() or by // "Try again" below, returns the payment the first call made, never a second one. $attempt = ['idempotency_key' => uuid()]; query('INSERT INTO payment_attempts (idempotency_key, order_id, created_at) VALUES (?, ?, ?)', [$attempt['idempotency_key'], $order['id'], gmdate('c')]); } $returnUrl = public_base_url() . '/return?order=' . $order['id']; // MPS appends nothing: carry your own id // Built from the order alone, so a retry sends the same body: the same key with another body is a 400. $result = mps('POST', '/api/payments/internet/create', [ 'amount' => $order['total'], 'reference' => $order['id'], 'successUrl' => $returnUrl, 'failureUrl' => $returnUrl, 'callbackUrl' => public_base_url() . '/webhooks/mps', ], $attempt['idempotency_key']); if ($result['status'] !== 200) { log_failure('create', $result); // The same attempt and key: if the failed call did open a payment, trying again returns that one. html('

We could not start the payment.

', 502); return; } $data = $result['body']['data']; query('UPDATE payment_attempts SET payment_reference = ?, checkout_url = ? WHERE idempotency_key = ?', // BEFORE redirecting [$data['paymentReference'], $data['checkoutUrl'], $attempt['idempotency_key']]); header('Location: ' . $data['checkoutUrl'], true, 303); // never log it: whoever has it can pay } // 2. The webhook route: verify, then store the webhook in the inbox and answer 2xx. Nothing else. // A 2xx means "accepted responsibility": after it, MPS does not send this webhook again. So the // work is stored BEFORE answering, and the worker (4) does it, which keeps the answer well inside the // 10-second budget. This handler calls nothing: no MPS read, no background task. function webhook(): void { $body = file_get_contents('php://input'); // the raw bytes: verify BEFORE parsing if (!is_valid_signature($_SERVER['HTTP_X_MPS_TIMESTAMP'] ?? '', $_SERVER['HTTP_X_MPS_SIGNATURE'] ?? '', $body)) { http_response_code(401); return; } $notification = json_decode($body, true); if ($notification['eventType'] !== 'payment.received') { http_response_code(200); // a new event type: ignore it, never fail on it return; } try { // Every retry of a webhook carries the same delivery id, so a repeat inserts nothing. query('INSERT INTO webhook_inbox (delivery_id, payment_reference, received_at, next_attempt_at) VALUES (?, ?, ?, ?) ON CONFLICT (delivery_id) DO NOTHING', [$_SERVER['HTTP_X_MPS_DELIVERY_ID'] ?? '', $notification['paymentReference'], gmdate('c'), time()]); } catch (Throwable $e) { // Never acknowledge work that is not stored: a 5xx makes MPS deliver it again. error_log("Storing the notification failed; MPS will retry: {$e->getMessage()}"); http_response_code(500); return; } http_response_code(200); } // 3. The shopper's return: read the payment. Landing here proves nothing. It settles through the same // settle() as the worker, so both paths apply the same checks. function shopper_return(): void { $order = query('SELECT * FROM orders WHERE id = ?', [$_GET['order'] ?? ''])->fetch(); $attempt = $order === false ? null : active_attempt($order['id']); if ($attempt === null || $attempt['payment_reference'] === null) { http_response_code(404); return; } $result = read_payment($attempt['payment_reference']); if ($result['status'] !== 200) { log_failure('read', $result); html('

We could not check your payment just now. Refresh this page in a moment.

', 502); return; } $next = (int) ($_GET['attempt'] ?? 0) + 1; match (settle($order, $attempt, $result['body']['data'])[0]) { 'paid' => html('

Thank you, your order is paid.

'), 'paid-twice' => html('

This order was already paid by an earlier payment. We will refund this one.

'), 'short' => html('

Your card was approved for less than the order total. We have not shipped; please contact us.

'), 'mismatch' => html('

We could not match this payment to your order. We have not shipped; please contact us.

'), // A new attempt for the same order: the order keeps its id and its earlier payments. 'not-paid' => html('

Your payment did not go through.

'), // Still pending (or a state we do not know): re-read every 2 s for about 30 s, then let the webhook settle it. default => $next <= 15 ? html('

Confirming your payment…

') : html('

We are confirming your payment and will e-mail you as soon as it is.

'), }; } // 4. The worker: the business operation, separate from receiving the webhook. Each run takes up to 20 // due rows of the inbox. A row left pending (a crash, a restart) is picked up by the next run: at-least-once, // and mark_paid makes that safe. Run it every 5 seconds while testing, from cron every minute in production. // One worker at a time: with several, claim a row first (UPDATE ... SET status = 'processing' ... RETURNING) or use your queue. function confirm_pending_webhooks(): void { $rows = query("SELECT * FROM webhook_inbox WHERE status = 'pending' AND next_attempt_at <= ? ORDER BY received_at LIMIT 20", [time()])->fetchAll(); foreach ($rows as $row) { try { // one bad row never stops the batch try { [$outcome, $error] = process_notification($row['payment_reference']); } catch (Throwable $e) { [$outcome, $error] = ['temporary', $e->getMessage()]; } record_outcome($row, $outcome, $error); } catch (Throwable $e) { error_log("Inbox row {$row['delivery_id']} failed; the next run retries: {$e->getMessage()}"); } } } // Returns [processed|temporary|permanent, error]. Temporary is tried again later; permanent needs a person. function process_notification(string $paymentReference): array { // Any attempt, active or not: a late ANNA payment on an earlier attempt still belongs to its order. $attempt = query('SELECT * FROM payment_attempts WHERE payment_reference = ?', [$paymentReference])->fetch(); $order = $attempt === false ? false : query('SELECT * FROM orders WHERE id = ?', [$attempt['order_id']])->fetch(); if ($order === false) { return ['permanent', 'unknown payment']; } $result = read_payment($paymentReference); if ($result['status'] !== 200) { log_failure('read', $result); // 400, 401, 403, 404: fix the configuration; retrying cannot help. Network, 429 and 5xx pass. return in_array($result['status'], [400, 401, 403, 404], true) ? ['permanent', "MPS answered {$result['status']}"] : ['temporary', "MPS answered {$result['status']}"]; } [$outcome, $reason] = settle($order, $attempt, $result['body']['data']); return match ($outcome) { 'paid', 'not-paid' => ['processed', null], // shipped, or nothing to ship 'pending' => ['temporary', $reason], default => ['permanent', $reason], // short, mismatch, paid-twice: a person decides; never ship }; } // Failed rows stay for investigation: SELECT * FROM webhook_inbox WHERE status = 'failed' function record_outcome(array $row, string $outcome, ?string $error): void { if ($outcome === 'processed') { query("UPDATE webhook_inbox SET status = 'processed', last_error = NULL WHERE delivery_id = ?", [$row['delivery_id']]); return; } error_log("Inbox row {$row['delivery_id']}: $outcome failure, $error"); $attempts = $row['attempts'] + ($outcome === 'temporary' ? 1 : 0); if ($outcome === 'permanent' || $attempts >= 8) { query("UPDATE webhook_inbox SET status = 'failed', attempts = ?, last_error = ? WHERE delivery_id = ?", [$attempts, $error, $row['delivery_id']]); return; } // Back off: 10 s, 20 s, 40 s ... at most an hour. query('UPDATE webhook_inbox SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE delivery_id = ?', [$attempts, time() + min(5 * 2 ** $attempts, 3600), $error, $row['delivery_id']]); } // The one place a payment is matched to its order and settled; the return page and the worker both call it. // The read is the source of truth. Ship once, and only for the full amount. Returns [outcome, reason]. function settle(array $order, array $attempt, array $payment): array { // The key only ever reads its own merchant's payments (another merchant's is a 404), so these checks catch // a mix-up on our side: a payment reference stored against the wrong order, or another currency. foreach (['paymentReference' => $attempt['payment_reference'], 'reference' => $order['id'], 'currency' => 'EUR'] as $field => $expected) { if (($payment[$field] ?? null) !== $expected) { return ['mismatch', "$field is " . json_encode($payment[$field] ?? null) . ", expected $expected"]; } } return match ($payment['state']) { 'executed' => $payment['amount'] === $order['total'] // amount = approved amount ? mark_paid($order, $payment['paymentReference']) : ['short', "approved {$payment['amount']} of {$order['total']} cents"], 'failed', 'abandoned' => ['not-paid', null], default => ['pending', "still {$payment['state']}"], // an unknown state is never paid }; } // One atomic statement: only the call that changes the row ships. This is why a duplicate delivery, a // second worker run, or the return page racing the worker can never ship twice. Fulfilment is a placeholder // here: in a live shop, insert a fulfilment job in the same commit, then process that job with retries // and an idempotency key the downstream system accepts. function mark_paid(array $order, string $paymentReference): array { if (query('UPDATE orders SET paid_at = ?, paid_by = ? WHERE id = ? AND paid_at IS NULL', [gmdate('c'), $paymentReference, $order['id']])->rowCount() === 1) { error_log("Order {$order['id']} paid; ship it"); return ['paid', null]; } // Already paid. By this payment: a repeat, nothing to do. By another one: an earlier attempt completed // late (an ANNA payment, for example). Refund it; never ship twice. $paidBy = query('SELECT paid_by FROM orders WHERE id = ?', [$order['id']])->fetchColumn(); return $paidBy === $paymentReference ? ['paid', null] : ['paid-twice', "order already paid by $paidBy; refund $paymentReference"]; } function active_attempt(string $orderId): ?array { return query('SELECT * FROM payment_attempts WHERE order_id = ? AND active = 1', [$orderId])->fetch() ?: null; } // X-Mps-Signature: v1=, two values during a rotation. function is_valid_signature(string $timestamp, string $signatureHeader, string $body): bool { if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) { return false; // a replay } $expected = hash_hmac('sha256', $timestamp . '.' . $body, env('MPS_WEBHOOK_SECRET')); foreach (explode(',', $signatureHeader) as $value) { $value = trim($value); if (str_starts_with($value, 'v1=') && hash_equals($expected, substr($value, 3))) { return true; } } return false; } function read_payment(string $paymentReference): array { return mps('GET', '/api/payments/internet/' . rawurlencode($paymentReference)); } // One call to MPS. Retries a 429 after Retry-After. Retries a 5xx or network error on a read, and on a // create that carries an Idempotency-Key: the key makes the retry return the payment the first call made. // A create without one is never retried, as it could open a second payment. function mps(string $method, string $path, ?array $payload = null, ?string $idempotencyKey = null): array { $headers = ['Authorization: Bearer ' . env('MPS_API_KEY')]; // mps_test_… or mps_live_… // Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if (getenv('MPS_WALLET_NUMBER')) { $headers[] = 'x-wallet-number: ' . getenv('MPS_WALLET_NUMBER'); } if ($payload !== null) { $headers[] = 'Content-Type: application/json'; } if ($idempotencyKey !== null) { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; } $retryable = $method === 'GET' || $idempotencyKey !== null; for ($attempt = 1; ; $attempt++) { $retryAfter = null; $curl = curl_init(MPS . $path); curl_setopt_array($curl, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$retryAfter) { if (preg_match('/^Retry-After:\s*(\d+)/i', $line, $match)) { $retryAfter = (int) $match[1]; } return strlen($line); }, ]); if ($payload !== null) { curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload)); } $text = curl_exec($curl); $status = $text === false ? 0 : curl_getinfo($curl, CURLINFO_RESPONSE_CODE); if ($status === 429 && $attempt < 3 && ($retryAfter ?? 1) <= 10) { sleep($retryAfter ?? 1); continue; } if (($status === 0 || $status >= 500) && $retryable && $attempt < 4) { sleep(2 ** ($attempt - 1)); continue; } $body = $text ? json_decode($text, true) : null; // 409 idempotency_key_in_use: the first call with this key is still running; the retry returns its payment. // Any other code (idempotency_key_expired, one this code does not know, or none) is final: never retried. if ($status === 409 && $idempotencyKey !== null && $attempt < 4 && ($body['code'] ?? null) === 'idempotency_key_in_use') { sleep(1); continue; } return ['status' => $status, 'body' => $body, 'retryAfter' => $retryAfter]; } } function log_failure(string $operation, array $result): void { $status = $result['status']; if ($status === 400 && isset($result['body']['errors'])) { // A problem document: each field with its messages. Fix the request; do not retry it unchanged. foreach ($result['body']['errors'] as $field => $messages) { error_log(sprintf('MPS %s refused %s: %s', $operation, preg_replace('/^Request\./', '', $field), implode('; ', $messages))); } return; } error_log("MPS $operation: " . match ($status) { 401 => '401, the API key is missing, wrong or revoked', 403 => '403, the key lacks the scope, or x-wallet-number is not one of your merchants', 404 => '404, no such payment for this merchant', 429 => "429, rate limited; Retry-After {$result['retryAfter']}s", 0 => 'no response (network error or timeout)', default => (string) $status, }); } // One prepared statement with parameters, never SQL built from strings. function query(string $sql, array $parameters = []): PDOStatement { $statement = db()->prepare($sql); $statement->execute($parameters); return $statement; } // One connection per request (or worker run). The tables are created on first use. function db(): PDO { static $db = null; if ($db === null) { $db = new PDO('sqlite:' . DATABASE, options: [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_TIMEOUT => 5, // the server and the worker write the same file: wait for the lock ]); $db->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see mark_paid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); SQL); } return $db; } function uuid(): string { $bytes = random_bytes(16); $bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // version 4 $bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // RFC 4122 variant return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); } function html(string $body, int $status = 200): void { http_response_code($status); header('Content-Type: text/html; charset=utf-8'); echo "$body"; } function public_base_url(): string { return rtrim(env('PUBLIC_BASE_URL'), '/'); } function env(string $name): string { $value = getenv($name); if ($value === false || $value === '') { throw new RuntimeException("Set $name"); } return $value; } ```
### Try it [#try-it] 1. Open `PUBLIC_BASE_URL` and press **Pay EUR 19.95**: you land on the MPS checkout. 2. Pay with `4111 1111 1111 1111`, any future expiry date, any security code. The return page reads the payment and shows the order paid. A moment later the webhook arrives and is verified, and the worker finds the order already settled. 3. Try again with `4000 0000 0000 0002` for a declined payment, or `4000 0000 0000 0010` to see the page keep re-reading a payment that stays `pending`. To test the verifier on its own, feed it [the webhook you can test against](/webhooks#a-webhook-you-can-test-against) with the five-minute check switched off: its timestamp is fixed in the past.
## Security checklist - **The API key stays on your backend.** Never in a browser, an app or a POS front end. Read it from the environment or a key vault, never from source control. - **Verify every webhook** before you act on it. The webhook URL is public; the signature is what makes a request trustworthy. - **Hash the raw body.** Verify the bytes exactly as received, and parse the JSON only afterwards. - **Compare in constant time** (`CryptographicOperations.FixedTimeEquals`, `timingSafeEqual`, `hmac.compare_digest`, `hash_equals`), against **every** `v1=` value: there are two while the signing secret is rotated. - **Reject stale timestamps**: more than five minutes from your clock is a replay. - **Never log** the API key, the signing secret or `checkoutUrl`: anyone holding the checkout URL can pay that payment. - **Settle from the read, not the redirect.** Landing on your success URL proves nothing. The read endpoint is the source of truth, and an unknown `state` is never paid. - **Check the amount on `executed`.** On a partial approval it is less than you asked for. Ship only when it matches the order total. - **Be idempotent.** A webhook can arrive more than once: drop a duplicate webhook by its `X-Mps-Delivery-Id`, and settle each order by `paymentReference` once. - **Send an `Idempotency-Key` on every create**, one per checkout attempt, stored with the order before the call. Only then is it safe to retry a create that timed out. - **Store the webhook before you answer it.** After a `2xx` MPS does not send it again, so work started after answering, in a thread or a fire-and-forget task, is lost if the process stops. ## Response What each route of the production example answers: | Route | Answers | |---|---| | `GET /` | A page with a **Pay EUR 19.95** button. | | `POST /checkout` | `303` to `checkoutUrl`. If the create fails, `502` with a **Try again** button that resends the same order with the same key. | | `POST /webhooks/mps` | `401` when the signature or the timestamp fails. `200` once the webhook is stored, or when its event is not `payment.received`. `500` when it cannot store the webhook, so MPS retries. | | `GET /return?order=…` | A page: paid, approved for less than the order total, or not paid (with **Try again**). A `pending` payment is re-read every 2 seconds for about 30 seconds. `404` for an unknown order, `502` when the read fails. | ## Errors The examples log each failure of a call to MPS. What the log line means: | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | MPS refused a field of the request; the log names each field. | Fix the request; do not resend it unchanged. See [Errors and rate limits](/errors-and-rate-limits). | | `401` | — | The API key is missing, wrong or revoked. | Check `MPS_API_KEY`. See [Authentication](/authentication). Not retried. | | `403` | — | The key lacks the scope, or `x-wallet-number` is not one of your merchants. | Check the key's scopes and `MPS_WALLET_NUMBER`. See [Choosing the merchant](/authentication#choosing-the-merchant). Not retried. | | `404` | — | No such payment for this merchant. | Check that the order's `paymentReference` was made with this key. | | `409` | `idempotency_key_in_use` | On the create: the first call with this key is still running. | The examples retry after a second with the same key. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). | | `409` | `idempotency_key_expired`, or any other code | On the create: the payment this key made can no longer be returned. | Not retried. Start a new checkout attempt, with a new key. See [Conflicts](/errors-and-rate-limits#conflicts). | | `429` | — | Rate limited. | The examples retry after `Retry-After`. See [Errors and rate limits](/errors-and-rate-limits). | | `5xx` or no answer | — | MPS or the network failed. | The examples retry reads, and creates that carry an `Idempotency-Key`. | | — | — | No webhook arrives: `PUBLIC_BASE_URL` is not a public HTTPS host, or the key has no signing secret. | Put a tunnel in front of port `8000`, and check the signing secret. See [Receive webhooks](/webhooks#receiving-them). | ## Related - [Payment lifecycle](/payment-lifecycle) - [Receive webhooks](/webhooks) - [Production checklist](/production-checklist): go through it before you switch to a live key.