# Receive webhooks (/webhooks) > Receive the webhooks MPS sends to your callbackUrl, verify each one, and process it once, with the delivery and retry rules MPS applies. A webhook tells you about a payment as it happens. MPS sends a signed POST to a URL of yours, server to server, the moment a payment is received and booked. It arrives even when the shopper closes the tab before the return: the cases that polling alone handles badly. A webhook tells you that something happened. The read endpoint stays authoritative for what a payment is now. This page goes from the least you need to the most: - **[Basic](#basic-receive-a-webhook)**: receive a webhook, verify it, read the payment and settle the order, all in the request. Enough when that reliably finishes within 10 seconds. - **[Recommended](#recommended-production-integration)**: what every production integration needs: when to answer `2xx`, retries, duplicates, and checking the payment against the order. - **[Advanced](#advanced-reliability)**: store the webhook, answer, and process it in a worker, so slow work, crashes and restarts lose nothing (the pattern we recommend for production); and rotating the signing secret. > **Server only.** The API cannot be called from a browser. The gateway answers no cross-origin (CORS) requests, and the API key must never reach a browser. Call it from your server. > **Warning.** Landing on successUrl is not proof of payment. Verify the webhook signature, read the payment, and check its state, amount, currency, and reference before marking an order paid. - A test key (`mps_test_…`) and its signing secret, from **Online › API keys** on the MPS platform - An HTTPS endpoint on a public host. While you build, a tunnel in front of a local server works. ## Basic: receive a webhook [#basic-receive-a-webhook] ### Events | Event | Sent when | Channels | |---|---|---| | `payment.received` | The payment is received and booked. Sent once per payment. | `internet` | | `refund.refunded` | A [refund](/refunds) of the payment is paid out. | `internet` | | `refund.failed` | A refund will not be paid out; you can refund its amount again. | `internet` | | `refund.canceled` | A refund was [canceled](/refunds#cancel-a-refund) before it was sent; nothing was paid out. | `internet` | `payment.received` carries `status` `completed`, the webhook's word for a received payment. Read the payment and its `state` is `executed` (see [`state`, `status` and the webhook](/concepts#state-status-and-the-webhook)). A refund event carries the refund's own status (`refunded`, `failed` or `canceled`, as [Get a refund](/refunds#get-a-refund) reads it) and its `refundId`. One refund sends one of the three, once it is decided. A refund still `pending` (waiting for its 4-hour window) sends nothing. A declined, failed, cancelled or abandoned payment sends no webhook. Learn those outcomes by [reading the payment](/online-payments#read-the-outcome) on the shopper's return. MPS may add new events and announces them in the [changelog](/changelog). Route on `eventType` (or the `X-Mps-Event` header), and ignore an event you do not recognise rather than failing on it. ### Pass a callbackUrl [#receiving-them] You register nothing in advance. Pass a `callbackUrl` when you [create the payment](/online-payments#request-body), and that payment's webhooks go there. Omit it and nothing is sent; nothing else about the payment changes. ```json { "amount": 1995, "successUrl": "https://shop.example.com/orders/1234/paid", "failureUrl": "https://shop.example.com/orders/1234/failed", "callbackUrl": "https://shop.example.com/webhooks/mps" } ``` **Your API key needs a [signing secret](#the-signing-secret).** Without one MPS sends no webhook, whatever the create call says. The URL is held to a stricter standard than the return URLs, because **MPS connects to it** rather than redirecting a browser: | Rule | Why | |---|---| | `https://` only | No loopback exemption, unlike `successUrl` and `failureUrl`. | | A publicly routable host | A private or reserved address would point our outbound HTTP at our own network. | | No user name or password in the URL | `https://user:pass@host/` displays as one host and resolves to another. | | At most 2048 characters | — | The create call refuses a URL that breaks any of these with a `400` naming `callbackUrl`. MPS checks the host **again when it connects**: a name that resolves to a private address by then is not dialled, and the attempt counts as a failed delivery. MPS never follows a redirect: answer at the URL you passed, because a `3xx` counts as a failed delivery too. ### Read what arrives [#what-arrives] ```http POST https://shop.example.com/webhooks/mps Content-Type: application/json X-Mps-Event: payment.received X-Mps-Timestamp: 1791892800 X-Mps-Delivery-Id: 00000000-0000-4000-8000-000000000003 X-Mps-Signature: v1=4f2a… { "eventType": "payment.received", "paymentId": "00000000-0000-4000-8000-000000000002", "paymentReference": "00000000-0000-4000-8000-000000000001", "merchantReference": "order-1234", "amount": 1995, "currency": "EUR", "status": "completed", "channel": "internet", "valutaDate": "2026-10-12T00:00:00Z", "occurredAt": "2026-10-12T14:31:07Z" } ``` [Response](#response) describes every field and header. Match a webhook to your order by `paymentReference`, and compare it as the opaque string it is: `paymentId` may differ from it in letter case. ### Verify the signature [#validating-the-signature] **Verify every webhook before you act on it.** Anyone who guesses the URL can reach it; the signature is what makes a request trustworthy. The signed content is the timestamp, a literal full stop, and the **raw request body**: ```text {timestamp}.{body} ``` The signature is HMAC-SHA256 of that content with your signing secret, in lower-case hex, prefixed `v1=`. 1. Read `X-Mps-Timestamp` and the body **exactly as received**, before any JSON parsing or re-serialising. Re-encoding changes bytes, and the signature no longer matches. 2. Compute `HMAC-SHA256(signing secret, timestamp + "." + body)` and hex-encode it in lower case. 3. Compare it against each `v1=` value in `X-Mps-Signature` with a **constant-time** comparison. A plain string equality leaks, through timing, how much of the signature was right. 4. Reject a timestamp too far from your own clock. Five minutes is a reasonable window. Without this check, someone who captured a webhook can replay it verbatim. ```python import hmac, hashlib, time def is_valid(secret: str, body: bytes, timestamp: str, header: str) -> bool: # Unix seconds, digits only: anything else is refused, never an exception. if not (timestamp.isascii() and timestamp.isdigit() and len(timestamp) <= 12): return False if abs(time.time() - int(timestamp)) > 300: return False signed = timestamp.encode() + b"." + body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest().encode() # The header can carry more than one signature during a secret rotation. return any( hmac.compare_digest(expected, candidate.strip()[3:].encode()) for candidate in header.split(",") if candidate.strip().startswith("v1=") ) ``` `is_valid` returns `True` only for a fresh webhook signed with your signing secret, and `False` for anything else, a missing or malformed header included. [Integration examples](/integration-examples) has the same check in C#, TypeScript and PHP. While your signing secret is being rotated, `X-Mps-Signature` carries **two** comma-separated `v1=` values: one for the new signing secret and one for the previous one. Accept the webhook if **either** matches, so deliveries in flight are not lost while you switch. Code that splits on `,` and takes the first value starts rejecting webhooks mid-rotation. #### Get the raw bytes [#getting-the-raw-bytes] "Exactly as received" is the whole difficulty. Most frameworks hand you a parsed object, and re-serialising it is the most common reason a correct signing secret still fails. A body that was reordered, re-indented or given a trailing newline hashes to something else. That failure looks exactly like a wrong signing secret. | Stack | Read the body with | |---|---| | Express | `express.raw({ type: 'application/json' })`, then `req.body` (a `Buffer`), **not** `express.json()` | | Next.js route handler | `await request.text()`, before any `request.json()` | | ASP.NET Core | `context.Request.EnableBuffering()`, then read `Body` and rewind | | Flask | `request.get_data()`, **not** `request.get_json()` | | Go | `io.ReadAll(r.Body)` once, and verify before unmarshalling | Parse the JSON only after the signature checks out. #### A webhook you can test against [#a-webhook-you-can-test-against] These values are consistent with each other, so your verifier returns true for them. The signing secret is an example, not a real one: use your own when you move on to real webhooks. ```text secret example-signing-secret X-Mps-Timestamp 1791892905 X-Mps-Signature v1=82b9a79df151e0e9207ef421fe4085e0a0ca95f3047265a0b92701ad5011c326 Content-Length 333 ``` ```json {"eventType":"payment.received","paymentId":"00000000-0000-4000-8000-000000001042","paymentReference":"00000000-0000-4000-8000-000000001042","merchantReference":"order-1042","amount":100,"currency":"EUR","status":"completed","channel":"internet","valutaDate":"2026-10-13T12:01:42.658852Z","occurredAt":"2026-10-13T12:01:44.0678776Z"} ``` The body above is the exact 333 bytes that were signed: compact JSON, no spaces, no trailing newline. If your implementation disagrees, compare your byte count against `Content-Length` first. A mismatch there means the body was re-encoded before you hashed it, which is the cause far more often than the signing itself. The timestamp in that example is fixed, so a replay-window check rejects it on wall-clock grounds. Test the HMAC on its own first, then put the freshness check back. ### Process, then answer [#the-simple-handler-process-then-answer] The whole integration in one request handler: 1. Receive the webhook at your `callbackUrl`. 2. Verify the signature and timestamp. Answer `401` if they do not check out. 3. Read the payment from MPS. 4. Check it against the order: `state` `executed`, and the order's `amount`, `currency` and `reference`. 5. In one database commit, mark the order paid with an update that only succeeds once, and record a fulfilment job for it. Ship from that job, not from the handler. 6. Answer `2xx`. On a failure, answer `5xx`, and MPS tries again later. Use it when reading the payment and updating the order reliably completes **within the 10-second budget**. ```python # Flask. is_valid is the function from the previous step. db, find_order_by_payment_reference, # mark_paid_once, add_fulfilment_job and flag_for_review are your shop's own. import json, os from urllib.parse import quote import requests from flask import Flask, request app = Flask(__name__) SECRET = os.environ["MPS_WEBHOOK_SECRET"] # the signing secret API_KEY = os.environ["MPS_API_KEY"] # mps_test_… while you build @app.post("/webhooks/mps") def webhook(): body = request.get_data() # 1. the raw bytes if not is_valid(SECRET, body, request.headers.get("X-Mps-Timestamp", "0"), request.headers.get("X-Mps-Signature", "")): return "", 401 # 2. signature and timestamp notification = json.loads(body) if notification["eventType"] != "payment.received": return "", 200 # a new event type: ignore it order = find_order_by_payment_reference(notification["paymentReference"]) if order is None: return "", 200 # not a payment of yours to settle: log it headers = {"Authorization": f"Bearer {API_KEY}"} if order.wallet_number: # a partner key only: the wallet of the merchant the order is for headers["x-wallet-number"] = order.wallet_number reference = quote(notification["paymentReference"], safe="") res = requests.get(f"https://gateway.mps-emi.com/api/payments/internet/{reference}", headers=headers, timeout=5) if res.status_code != 200: return "", 503 # 3. could not read it now: MPS retries payment = res.json()["data"] if payment["state"] == "pending": return "", 503 # not final yet: MPS retries # 4. Check it against the order. 5. Settle once, and record the fulfilment in the same commit. if (payment["state"] == "executed" and payment["amount"] == order.total and payment["currency"] == "EUR" and payment["reference"] == order.id): with db.transaction(): # both rows, or neither: an error answers 5xx and MPS retries if mark_paid_once(order.id): # UPDATE orders SET paid_at = now WHERE id = ? AND paid_at IS NULL add_fulfilment_job(order.id) # INSERT INTO fulfilment_jobs (order_id) VALUES (?), order_id unique elif payment["state"] == "executed": flag_for_review(order, payment) # approved for a different amount: never ship it return "", 200 # 6. answered only after the work is done ``` The handler answers `200` once the order is settled or needs no action, `401` for a webhook that fails verification, and `503` when the payment cannot be read or is not final yet. Shipping is not in the handler. If it were, a shipment that failed after the order was marked paid would be lost: the retried webhook finds the order paid and does nothing. Your own worker takes each job from `fulfilment_jobs`, ships, and marks the job done; a failed shipment leaves the job for the next try. Make shipping safe to repeat (one shipment per `order_id`), since a worker can stop after shipping and before marking the job done. ## Recommended: production integration [#recommended-production-integration] **Synchronous** ([process, then answer](#the-simple-handler-process-then-answer)): verify, read the payment, settle the order, then answer `2xx`. Fine when that reliably finishes within 10 seconds. **Asynchronous** ([store, answer, process](#the-production-pattern-store-answer-process), recommended for production): verify, store the webhook durably, answer `2xx`, then process it from the store. Both answer `2xx` only once the webhook is safe: processed, or stored. ### Delivery Answer **`2xx` only once the webhook is safe with you**: verified, and either processed or stored durably for processing. A `2xx` means you take responsibility for it, and MPS does not send that webhook again. Anything else (a `3xx`, a `4xx`, a `5xx`, or no answer within **10 seconds**) counts as a failed delivery, and MPS retries it. See [Process webhooks reliably](#processing-them-reliably). #### Retries MPS tries a webhook **six times** before it gives up: | Attempt | After the previous one | Since the first | |---|---|---| | 1 | — | — | | 2 | 1 minute | 1 minute | | 3 | 5 minutes | 6 minutes | | 4 | 30 minutes | 36 minutes | | 5 | 2 hours | 2 hours 36 minutes | | 6 | 6 hours | 8 hours 36 minutes | Every attempt is signed again, with its own `X-Mps-Timestamp`: a retry hours later still passes the five-minute check. The body and `X-Mps-Delivery-Id` stay the same on every attempt. After the sixth failure MPS does not send it again. Treat the webhook as the fast path, and reconcile any order you did not hear about by reading the payment. ### Process webhooks reliably [#processing-them-reliably] A webhook tells you **when** to look; the payment read tells you **what** happened. - **Delivery is at-least-once.** The same webhook can arrive more than once. Settle each order with an update that only succeeds the first time (`UPDATE orders SET paid_at = … WHERE id = … AND paid_at IS NULL`). When it changed a row, record the fulfilment job in the same commit, and ship from that job, retrying until it succeeds. - **A `2xx` is an acknowledgement.** Return it only after the webhook is verified **and** either processed or durably stored. Never before: after a `2xx`, MPS does not send it again. - **Work started after answering can be lost.** A thread, a `Task.Run`, a promise you do not await: if the process stops, that work is gone, and nothing sends the webhook again. Store it, answer, and process from what you stored, so a restart picks it up. - **A webhook is not the payment record.** Read the payment and check its `state`, `amount`, `currency` and `reference` against your order before you ship. Your API key only ever reads your own merchant's payments. For a refund event, read the refund the same way, by its `paymentReference` and `refundId`. - **Key on `X-Mps-Delivery-Id`.** One payment can send several webhooks (it is received, then refunded in parts). The delivery id names exactly one of them, and every retry of it repeats it. - **Expect any order.** Webhooks can arrive in a different order than their events happened. Act on the reads, not on the order of arrival. - **Reconcile anyway.** MPS gives a webhook up after six attempts, and sends none at all without a signing secret, for a revoked API key, or to an unreachable URL. Periodically read every order that has a `paymentReference` and is not settled. After 24 hours an unpaid payment reads `abandoned`; only a late ANNA payment changes it, and that sends `payment.received`. ## Advanced: reliability [#advanced-reliability] ### Store, answer, process [#the-production-pattern-store-answer-process] When the work may take longer, or touches systems you cannot promise answer in time, separate **receiving** the webhook from **completing** the business operation: >Endpoint: POST callbackUrl, payment.received Endpoint->>Endpoint: Verify X-Mps-Signature over the raw body
and X-Mps-Timestamp (within 5 minutes) alt Invalid signature or stale timestamp Endpoint-->>MPS: 401 else Valid Endpoint->>Inbox: Store it, keyed on X-Mps-Delivery-Id
(a duplicate webhook is a no-op) alt Store failed Inbox-->>Endpoint: Error Endpoint-->>MPS: 5xx: MPS retries else Stored, or already stored Inbox-->>Endpoint: OK Endpoint-->>MPS: 2xx end end Note over Worker: Later, separately from the request Worker->>Inbox: Take a due pending webhook
(claim it first when running several workers) Inbox-->>Worker: paymentReference Worker->>MPS: GET /api/payments/internet/{paymentReference} MPS-->>Worker: state, amount, currency, reference Worker->>Worker: Check it against the order alt executed, for the order's amount, currency and reference Worker->>Inbox: Settle the order once
(UPDATE ... WHERE paid_at IS NULL), mark processed else Temporary: timeout, 429, 5xx, still pending Worker->>Inbox: Schedule a retry with backoff else Permanent: unknown payment, different amount, refused read Worker->>Inbox: Mark failed, with the reason, for a person end `} /> 1. Verify the signature and timestamp. 2. Store the webhook in a database table (an inbox) or a durable queue, keyed on `X-Mps-Delivery-Id`, so a duplicate webhook is a no-op. If the store fails, answer `5xx`. 3. Answer `2xx`. 4. A worker takes stored webhooks, reads the payment, checks it against the order, settles the order once (recording its fulfilment job in the same commit), and marks the webhook processed. With more than one worker, each first claims a webhook with an update only one of them can win, so two never process the same one. 5. Retry a temporary failure (a timeout, a `5xx`, a payment still `pending`) later, with backoff. Record a permanent one (an unknown payment, a different amount) as failed for someone to look at. Never retry it forever. [Integration examples](/integration-examples) has this as a complete, runnable server in C#, TypeScript, Python and PHP. Each runs a single worker; that page shows the claim to add before running more than one. ### The signing secret MPS signs webhooks with one signing secret per API client. Until that API client has one, MPS sends no webhook at all: an unsigned one would be impossible to tell from a forgery. - A key you generate on the MPS platform (**Online › API keys**), test key or live key, comes with its own signing secret, shown once next to the API key. - For a key MPS issued to you directly, ask MPS for a signing secret when you receive the key. The signing secret is not derived from the API key, and the API does not return it. If you no longer have it, or believe it leaked, ask MPS to issue a new one. A rotation is not a cut-over. MPS keeps signing with the previous signing secret for **24 hours** too, and sends both signatures throughout that window. The second signature appears within about 5 minutes of the rotation; until then webhooks carry the previous signature only. Keep accepting the previous signing secret, and you need no coordinated switch-over: pick the new value up at your convenience within the day. ## Test your endpoint [#testing] Your endpoint must be reachable over HTTPS on a public host. While you build, put a tunnel (ngrok, Cloudflare Tunnel) or a request inspector in front of a local server. MPS refuses `https://localhost` and a private address, at create time and again when it connects. With a [test key](/concepts#keys), a test payment sends `payment.received` like a live one, once a payment paid with a [test card or on ANNA's test screen](/online-payments#test-mode) ends in `executed`. Its refunds send their refund events once decided (a test refund reads `refunded` after its 4-hour window). Each is signed with the test key's own signing secret. Answering it with a `2xx` confirms your endpoint works; nothing has to pass before you create a live key. ## Response The webhook's body, field by field. Only the status code of your answer decides the delivery (see [Delivery](#delivery)). | Field | Type | Required | Description | |---|---|---|---| | `eventType` | string | Yes | `payment.received`, `refund.refunded`, `refund.failed` or `refund.canceled`. New events may be added. | | `paymentId` | string | Yes | The booked payment. May differ from `paymentReference` in letter case. | | `paymentReference` | string | Yes | The `paymentReference` the create call returned: the key you read the payment with. | | `merchantReference` | string | Yes | Your own `reference`, echoed back. Null if you sent none. | | `amount` | integer | Yes | In cents, as received. On a refund event, the refund's amount. | | `currency` | string | Yes | `EUR`. | | `status` | string | Yes | `completed`. On a refund event, `refunded`, `failed` or `canceled`. | | `channel` | string | Yes | `internet`. | | `valutaDate` | string | Yes | The value date of the booking. On a refund event, the same as `occurredAt`. | | `occurredAt` | string | Yes | When MPS established the payment was received, or the refund's outcome. | | `refundId` | string | No | Only on a refund event: the refund, as [Refund a payment](/refunds#refund-a-payment) returned it. | | Header | Meaning | |---|---| | `X-Mps-Event` | The event type, so you can route without parsing the body. | | `X-Mps-Timestamp` | Unix seconds. Part of the signed content: see [Verify the signature](#validating-the-signature). | | `X-Mps-Delivery-Id` | Identifies the webhook: every retry of it carries the same value. Useful in logs and support tickets. | | `X-Mps-Signature` | `v1=`, the HMAC. Two comma-separated values during a rotation of the signing secret. | The API reference describes the same webhook, as `webhook`, on [Create an online payment](/api-reference/online-payments/payments-internet-create). ## Errors | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | The create call refused `callbackUrl`: not `https://`, not a public host, a user name or password in the URL, or longer than 2048 characters. | Fix the URL. See [Pass a callbackUrl](#receiving-them). | | Your `401` | — | The signature does not match: the body was re-encoded before hashing, the signing secret is wrong, or only the first `v1=` value was checked during a rotation. | Hash the raw bytes ([Get the raw bytes](#getting-the-raw-bytes)), check your verifier against [the test webhook](#a-webhook-you-can-test-against), and accept every `v1=` value. | | Your `4xx` or `5xx`, or no answer within 10 seconds | — | MPS counts the delivery as failed. | MPS retries on the [schedule](#retries). After the sixth attempt, reconcile by reading the payment. | | — | — | No webhook arrives: the payment had no `callbackUrl`, your API key has no signing secret or was revoked, the host resolved to a private address when MPS connected, your endpoint answered with a redirect, or the payment did not go through. | Check each cause. Learn the outcome by [reading the payment](/online-payments#read-the-outcome). | ## Related - [Payment lifecycle](/payment-lifecycle) - [Follow a payment's timeline](/payment-timeline): each webhook MPS sent, with your server's answer - [Integration examples](/integration-examples) - [Production checklist](/production-checklist)