.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;
}
```