Run an integration example
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: create a payment, redirect, read the result. About 40 lines, to see the flow work.
- Production: 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, 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
Warning
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.Before you start
- 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, and the return page says whether it is paid.
A starting point, not a production integration
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
below does all of it.
.NET 10: dotnet new web, replace Program.cs, then dotnet run.
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<string, string>(); // 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<JsonElement>()).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<JsonElement>(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");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.
Single-instance examples
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:
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 /checkoutstores the order and a payment attempt with a freshIdempotency-Key, and creates the payment withPOST /api/payments/internet/create(amount in cents,reference,successUrl,failureUrl,callbackUrl), sending that key. It storespaymentReferenceandcheckoutUrlagainst the attempt before redirecting, and sends the shopper tocheckoutUrlwith a303. 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.- Trying again after a
failedorabandonedpayment creates a new payment attempt for the same order, with a new idempotency key, and keeps every earlier attempt with itspaymentReference. Apendingpayment 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. Seefailed. POST /webhooks/mpsreads the raw body, checksX-Mps-Timestampis within five minutes, verifiesX-Mps-Signature(HMAC-SHA256 of{timestamp}.{raw body}, lower-case hex, everyv1=value, constant-time), stores the webhook in thewebhook_inboxtable, keyed onX-Mps-Delivery-Idso a duplicate webhook is a no-op, and only then answers2xx. If it cannot store it, it answers500and MPS tries again. It does no other work. See Process webhooks 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, a5xx, a payment stillpending) 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 asfailedwith 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 isphp index.php, run from cron. GET /returnis both thesuccessUrland thefailureUrl. It never trusts the landing: it readsGET /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:paymentReferencematches the stored attempt (compared as opaque strings),referencematches the order,currencymatches the order's (EURhere),stateisexecutedandamountequals 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 apendingpayment every 2 seconds for about 30 seconds.- Errors follow Errors and rate limits: a
400logs each field of the problem document,401and403are configuration problems and are not retried, a429is retried afterRetry-After, and a5xxor network error is retried on reads and on the create, which is safe because it carries anIdempotency-Key. A409is decided on itscode: onlyidempotency_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 and 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 withSELECT * FROM webhook_inbox WHERE status = 'failed'.
Run the production example
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. |
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:8000The 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
.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.
// 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("""<form method="post" action="/checkout"><button>Pay EUR 19.95</button></form>"""));
// 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("<p>This order is already paid.</p>");
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("<p>We could not check your previous payment just now. Try again in a moment.</p>", 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("<p>Your payment was just restarted in another tab. Use that one.</p>", 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($"""<p>We could not start the payment.</p><form method="post" action="/checkout?retry={order.Id}"><button>Try again</button></form>""", 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("<p>We could not check your payment just now. Refresh this page in a moment.</p>", 502);
}
var next = (attempt ?? 0) + 1;
return Settle(found, current, result.Body.GetProperty("data")).Outcome switch
{
Outcome.Paid => Html("<p>Thank you, your order is paid.</p>"),
Outcome.PaidTwice => Html("<p>This order was already paid by an earlier payment. We will refund this one.</p>"),
Outcome.Short => Html("<p>Your card was approved for less than the order total. We have not shipped; please contact us.</p>"),
Outcome.Mismatch => Html("<p>We could not match this payment to your order. We have not shipped; please contact us.</p>"),
// A new attempt for the same order: the order keeps its id and its earlier payments.
Outcome.NotPaid => Html($"""<p>Your payment did not go through.</p><form method="post" action="/checkout?retry={found.Id}"><button>Try again</button></form>"""),
// 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($"""<meta http-equiv="refresh" content="2;url=/return?order={found.Id}&attempt={next}"><p>Confirming your payment…</p>"""),
_ => Html("<p>We are confirming your payment and will e-mail you as soon as it is.</p>"),
};
});
// 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<Confirmation> 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<T> Query<T>(string sql, Func<SqliteDataReader, T> 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<T> rows = [];
while (reader.Read()) rows.Add(map(reader));
return rows;
}
// X-Mps-Signature: v1=<lower-case hex HMAC-SHA256 of "{X-Mps-Timestamp}.{raw body}">, 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<MpsResult> 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($"<!doctype html>{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 lookTry it
- Open
PUBLIC_BASE_URLand press Pay EUR 19.95: you land on the MPS checkout. - 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. - Try again with
4000 0000 0000 0002for a declined payment, or4000 0000 0000 0010to see the page keep re-reading a payment that stayspending.
To test the verifier on its own, feed it the 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 everyv1=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
stateis 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 bypaymentReferenceonce. - Send an
Idempotency-Keyon 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
2xxMPS 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. |
401 | — | The API key is missing, wrong or revoked. | Check MPS_API_KEY. See 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. 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. |
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. |
429 | — | Rate limited. | The examples retry after Retry-After. See 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. |
Related
- Payment lifecycle
- Receive webhooks
- Production checklist: go through it before you switch to a live key.
Need help? Contact MPS at contact@mps-emi.com or +32 55 89 09 77, or the MPS partner you work with. What to include.
Building with an AI assistant? Give it llms.txt, every page in llms-full.txt, this page as Markdown, or the OpenAPI document. See Build with AI.
Last updated on