# MPS Payments documentation > Take online payments with MPS: payment links without code, shop plugins for WooCommerce, Odoo, Magento and PrestaShop, and the payments API for your own integration. # Online payments with MPS (/) > Choose how you take online payments with MPS, from a payment link without code to an integration your developer builds. MPS takes online payments for your business. Your customer, the **shopper**, pays on the MPS **checkout**: the MPS page where they enter a card or pay by bank. MPS pays the money out to you. These pages cover online payments only; payment terminals, reports and invoices are not described here. Choose the way that fits how you sell. ## How a payment works Every route works the same way for the shopper. Only the first step differs. or the shopper orders in your shop"] --> B["The shopper pays
on the MPS checkout"] B --> C["You see it is paid:
the link reads Paid,
or your shop marks the order paid"] C --> D["MPS pays the money out to you"] `} /> ## Your first steps 1. **[Set up your account](/set-up-your-account).** Sign in to the MPS platform at [main.mps-emi.com](https://main.mps-emi.com) and check that you see the **Online** module. 2. **Pay a test payment yourself.** **Test mode** uses test cards: no card is charged and nothing is paid out. The [test link walkthrough](/payment-links#start-with-a-test-link) takes two minutes. 3. **[Switch to live payments](/take-live-payments)** once MPS has approved your account. In **live mode** shoppers pay for real. --- # Set up your account for online payments (/set-up-your-account) > Check that your MPS platform access has the Online module, and learn what test payments and live payments each need. Every way of taking online payments with MPS starts on the **MPS platform**, the website where you manage your business with MPS. There you create payment links, and get what your webshop or your developer needs to take payments. - Your business registered with MPS, by MPS or by the MPS partner you work with - A sign-in for the MPS platform, set up by MPS or the MPS partner that registered your business ### Sign in and find the Online module Sign in to the MPS platform at [main.mps-emi.com](https://main.mps-emi.com). The **Inloggen** (sign in) button on the MPS website, [mps-emi.com](https://www.mps-emi.com), takes you there too. No sign-in yet, or it does not work? Ask MPS, or the MPS partner that registered your business: they give access to the platform. A business whose contract includes online payments sees the **Online** module, with these screens: | Screen | What you do there | |---|---| | **API keys** | Only for a webshop or your developer: create the **API key**, a long code that lets their software take payments for you. Payment links need none. | | **Payment links** | Create a link for one payment and share it. | | **Shop plugins** | Opens the plugin pages of this site. | | **Documentation** | Opens this site. | No **Online** module? Your contract does not include online payments yet. Contact MPS or your partner. ### Try a test payment You can test as soon as you see the Online module, also while MPS still has to approve your account. **Test mode** uses test cards: no card is charged and nothing is paid out. Test payments show in the platform's transaction monitor, marked test. - Without a website: create a test [payment link](/payment-links) and pay it yourself. - With a webshop: [connect your webshop](/connect-your-webshop), which starts with a test API key. - With a developer: create a test API key and give it to your developer for the [quickstart](/quickstart). ### Get ready for live payments **Live mode** takes real payments, paid out to you. The platform unlocks it step by step: | What you want | What it needs | |---|---| | Test payments | The **Online** module. | | Live payment links | Your account approved by MPS, and a shop name. | | Live payments in a webshop or your own integration | Your account approved by MPS, your contract with MPS signed, and a shop name. | The **shop name** is the name of your place of business. The shopper sees it on the checkout. If the platform says your business has no shop name yet, add a place of business, or ask MPS or your partner to. Until a step is done, the platform says which one is missing, and test mode keeps working. [Switch to live payments](/take-live-payments) covers the rest. ## Partners A partner that sells online sees the same **Online** module. On **API keys** it creates test keys for itself, and live keys for each of its merchants once that merchant has signed its contract. ## Get help These pages cover online payments only. For anything else, or when the platform does not do what these pages say, contact MPS or the MPS partner you work with: | Contact | How | |---|---| | MPS | E-mail [contact@mps-emi.com](mailto:contact@mps-emi.com) or call [+32 55 89 09 77](tel:+3255890977) | | Your MPS partner | The contact your partner gave you. A partner can also ask MPS on your behalf. | Include: - the name of your business, - what you were doing, and the exact message the platform showed, - for a payment: its payment reference, or the reference of the payment link. If your developer reports the problem, they add the details of the failed request, as [Errors and rate limits](/errors-and-rate-limits) describes. ## Troubleshooting | Message on the platform | Cause | What to do | |---|---|---| | No **Online** module | Your contract does not include online payments. | Contact MPS or your partner. | | *Live keys take real payments, so they come once your account is approved. Test keys work meanwhile.* | MPS has not approved your account yet. | Keep testing. Live keys come once MPS approves your account. | | *Your contract is not signed yet. Live keys can be created once it is signed; test keys work meanwhile.* | Your contract with MPS is not signed. | Sign your contract, then create the live key. | | *… has no shop name yet …* | No place of business is registered, so the shopper would see no name. | Add a place of business, then try again. | | *The contract cannot be checked right now, so no live key can be created.* | The platform could not reach MPS. | Try again in a moment. | ## Related - [Send a payment link](/payment-links): a first payment without code - [Connect your webshop](/connect-your-webshop): WooCommerce, Odoo, Magento or PrestaShop - [Switch to live payments](/take-live-payments): what to check before real payments --- # Switch to live payments (/take-live-payments) > Move from test mode to real payments with a payment link, a shop plugin or your own integration, and check what to do before the first one. In **live mode** shoppers pay for real and MPS pays the money out to you. Test mode lets you practise the flow with test cards and a simulated ANNA bank, without real money. To switch, you choose **Live** for a link, or paste a live key in your shop. - A test payment that worked: a test link paid, or a test order marked paid in your shop - Your account approved by MPS. The platform says so while it is not: *… once your account is approved*. - A shop name: the name of your place of business, which the shopper sees on the checkout - For a webshop or your own integration: your contract with MPS signed Ask MPS or your partner about the status of your approval. See [Set up your account](/set-up-your-account#get-ready-for-live-payments) for each requirement. ## Go live with a payment link [#a-payment-link] Once MPS has approved your account, choose **Live** under **Mode** when you create a link, and check the amount and the reference first: a live link takes real money. [Send a live link](/payment-links#send-a-live-link) has the steps. A link you sent by mistake can be canceled while it is open; see [Cancel a link](/payment-links#cancel-a-link). ## Go live with a shop plugin [#a-shop-plugin] Open **Online › API keys**, choose **Live**, and click **Create API key**. Copy the API key, which starts with `mps_live_`, and its webhook signing secret. The platform shows them once. In your shop's MPS settings, replace the test key with the live key, and the test signing secret with the live key's own signing secret. Save. A signing secret belongs to one key: the test one does not work with the live key. Make sure your shop is online and reachable from the internet, so MPS can tell it the moment an order is paid. Without that, orders are confirmed later, and a payment completed hours later may not reach your shop. Your host or developer can confirm it; your shop system's page has the details. Watch your first live orders: each one should be marked paid as your test orders were. To refund from your shop, the live key needs the refund permission: ask MPS to add it. Your shop system's page has the details: [WooCommerce](/woocommerce), [Odoo](/odoo), [Magento](/magento) or [PrestaShop](/prestashop). ## Go live with your own integration [#your-own-integration] Your developer goes through the [Production checklist](/production-checklist) before using a live key: the key kept on the server, webhooks verified, every outcome read from MPS, each order fulfilled once. You create the live key under **Online › API keys** in **Live** mode and hand it over through a safe channel, never by e-mail or chat. A live key belongs on your developer's server only, never in a website or an app that shoppers download. ## Troubleshooting | What you see | Cause | What to do | |---|---|---| | **Live** cannot be chosen, with *… once your account is approved* | MPS has not approved your account yet. | Keep using test mode. | | *Your contract is not signed yet …* | Live API keys need a signed contract. | Sign your contract with MPS. | | *… has no shop name yet …* | No place of business is registered. | Add a place of business, then try again. | | Orders stay unpaid after switching | Possible causes: the shop still has the test signing secret, the shop cannot be reached from the internet, or something else on the shop's side. | Check that the live key's own signing secret is pasted, then follow **Errors** on your shop system's page: [WooCommerce](/woocommerce#errors), [Odoo](/odoo#errors), [Magento](/magento#errors) or [PrestaShop](/prestashop#errors). | ## Related - [Set up your account](/set-up-your-account): what each step of live mode needs - [Send a payment link](/payment-links): the steps for a test link and a live link, and how to follow each one up - [Connect your webshop](/connect-your-webshop): the plugin for your shop system - [Production checklist](/production-checklist): the developer's checks before a live key --- # Send a payment link (/payment-links) > Create a payment link on the MPS platform, share it, and see when it is paid, without writing code. A payment link asks for one payment of a fixed amount. You create it on the MPS platform and share it by e-mail, chat, text message or as a QR code. The shopper, the person who pays, opens it, sees your shop name, the amount and your reference, and pays on the MPS **checkout**: the MPS page where they enter a card or pay by bank. You need no website and no developer. Every link can be paid once. It closes when it is paid, when it expires or when you cancel it. New to payment links? [Start with a test link](#start-with-a-test-link): you pay it yourself, and nothing is charged. - Access to the MPS platform with the **Online** module. See [Set up your account](/set-up-your-account). - For live links: your account approved by MPS, and a place of business, whose name the shopper sees. Test links work without either. ## Start with a test link Pay a test link yourself before you send a real one. It takes two minutes, charges nothing, and shows you exactly what your shopper sees. A test link works before MPS approves your account. Sign in to the MPS platform, open **Online › Payment links**, and click **Create payment link**. A form opens. Fill in the form: | Field | Required | What to enter | |---|---|---| | **Amount (EUR)** | Yes | What the shopper pays, from € 0,01 to € 50.000. The shopper cannot change it. For a test, `1,00`. | | **Reference** | Yes | Up to 64 characters: letters, digits, spaces and `. _ : / # + -`. The shopper sees it, and it is how you recognise the payment, such as `invoice 2026-0042`. For a test, `test 1`. | | **Open for (days)** | No | How long the link can be paid, from 1 to 90 days. Default 10. | | **Shopper's language** | No | The language the link and the checkout open in: English, Dutch or French. Default: the language of the shopper's browser. | | **Mode** | Yes | **Test** for now. A test link takes a test payment: no card is charged and nothing is paid out. Once your account is approved, **Live** is chosen by default, so check this field. | Click **Create payment link** at the bottom of the form. **You see:** *Payment link created. Share it from the details below.* The link's details open beside the list, with its address (of the form `https://pay.mps-emi.com/link/…`), a **Copy link** button and the QR code. The list shows the link as **Open**. Click **Copy link** and open the address in your browser, or scan the QR code with your phone. Click **Pay** (the button shows the amount). **You see:** the MPS checkout, with a **Test mode** banner and the test cards. Pay with this test card: | Card number | Expiry date | Security code | |---|---|---| | `4111 1111 1111 1111` | Any date in the future | Any 3 digits | **You see:** the checkout sends you back to the link, which now reads *This payment request has been paid.* On the platform, the link reads **Paid** in the list, and its details show the payment. To see a refused payment, pay another test link with `4000 0000 0000 0002`. The payment fails, and the link stays **Open** so the shopper can try again. ## Send a live link A live link takes real money, paid out to you. It needs your account approved by MPS and a shop name; see [Switch to live payments](/take-live-payments#a-payment-link). Open **Online › Payment links**, click **Create payment link**, and fill in the form as for the test link, with **Mode** set to **Live**. Check the amount and the reference, then click **Create payment link** at the bottom of the form. The shopper cannot change the amount. **You see:** the link's details, as for the test link, and the link in the list as **Open**. Click **Copy link** and send the address to the shopper by e-mail, chat or text message. To share it as a QR code instead, click **Download QR code** in the details to save it as an image for an invoice, a letter or a counter display. The shopper scans it with a phone camera. To find the details again later, click the link's reference in the list. **You see, once the shopper has paid:** the link reads **Paid** in the list. ## Follow up on a link The list under **Online › Payment links** shows every link with its amount, reference, status and expiry date. A link has one of these statuses: | Status | Meaning | |---|---| | **Open** | The link can be paid. | | **Paid** | A payment on the link succeeded. The link cannot be paid again. | | **Expired** | The link was not paid in time. Create a new one to ask again. | | **Canceled** | You canceled the link. | Click a link's reference to see its details: when it was created and paid, its QR code, and every payment the shopper started on it, with each payment's history. A shopper whose payment fails or who leaves the checkout can open the link again and try again; each try is a payment of its own, and the link is paid once one of them succeeds. A link that is paid stays **Paid**, also after it expires or after you cancel it. A bank transfer that arrives late still completes the payment it belongs to. ## Cancel a link Click the link's reference to open its details, click **Cancel link**, and confirm with **Yes, cancel**. The link can no longer be paid; a shopper who opens it reads that the request was withdrawn. A shopper who is paying at that moment can still finish, and the link then reads **Paid**. ## What the shopper sees The link opens a payment request with your shop name, the amount, your reference and the date until which it can be paid, in the **Shopper's language** you chose, or else in the language of the shopper's browser. **Pay** takes the shopper to the MPS checkout; after paying, the shopper comes back to the link, which says how the payment ended. A link that can no longer be paid says why: paid, expired, or withdrawn by you. ## Troubleshooting | Message on the platform | Cause | What to do | |---|---|---| | *Live links come once … approved.* | You are not approved for live payments yet. | Create a test link meanwhile. | | *… no shop name yet, and a live link needs one.* | No place of business is registered, so there is no name to show the shopper. | Add a place of business, then try again. | | *… cannot create payment links.* | The **Online** module is not enabled for you. | Ask MPS to enable online payments. | | *That payment link is already paid or expired.* | You canceled a link that had closed in the meantime. | Nothing: the list shows its status. | | *Payment links cannot be reached right now.* | The platform could not reach MPS. | Try again in a minute. | ## Related - [Switch to live payments](/take-live-payments#a-payment-link): what to check before your first live link - [Set up your account](/set-up-your-account): the Online module, approval and the shop name - [Accept a payment](/online-payments): for developers, the API that opens a payment from your own website or app - [Test mode](/online-payments#test-mode): every test card and the outcome it gives --- # Connect your webshop (/connect-your-webshop) > Choose your shop system, install the MPS plugin, take a test order and go live, without writing code of your own. MPS has a plugin for five shop systems. A plugin adds MPS as a payment method to your shop's checkout: the shopper pays on the MPS checkout and comes back to your shop, and the plugin marks the order paid. ## Choose your shop system | Shop system | Versions | Worth knowing first | |---|---|---| | [WooCommerce](/woocommerce) | WordPress 6.4+, WooCommerce 8.3+, PHP 7.4+ | Installs from a zip in the WordPress admin. | | [Odoo](/odoo) | Odoo 20, Community or Enterprise | Not on Odoo Online (odoo.com): run Odoo yourself or on Odoo.sh. | | [Magento](/magento) | Magento Open Source or Adobe Commerce 2.4.7 – 2.4.9, or Mage-OS | Needs shell access to the server and Magento's cron. With Hyvä Checkout, also the [Hyvä Checkout add-on](/magento#hyva-checkout). | | [PrestaShop](/prestashop) | PrestaShop 8.0 – 9.x | Needs a task that calls an address every 5 minutes. | | [Drupal Commerce](/drupal) | Drupal 10.3 – 11, Drupal Commerce 3 | Installs with Composer from Drupal.org. Needs access to the server and Drupal's cron. | | [Wix](/wix) | A Wix site on a Premium plan | Needs the files copied into the site's code (Velo). | You write no code for any of them. Magento, and PrestaShop without the **Cron tasks manager** module, need someone who can work on the server your shop runs on: your hosting provider or your developer. Every plugin takes payments in euro only. Your shop system is not listed? A developer can connect it with the payments API: see [Build an integration](/quickstart). - Access to the MPS platform with the **Online** module. See [Set up your account](/set-up-your-account). - Admin access to your shop - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it. A shop on your own computer works for testing, but may confirm an order only when the shopper returns, or later. ### Create a test key On the MPS platform, open **Online › API keys**, choose **Test**, and click **Create API key**. Give it a name you recognise, such as your shop's address. The platform shows two codes, once: - the **API key**, which starts with `mps_test_`. It lets your shop take test payments. - the **webhook signing secret**. Your shop uses it to check that a message about a payment really comes from MPS. Copy both into a password manager, or straight into your shop in the next step, before you close the window. ### Install the plugin and paste the codes Follow **Install and connect** on your shop system's page: [WooCommerce](/woocommerce#install-and-connect), [Odoo](/odoo#install-and-connect), [Magento](/magento#install-and-connect) or [PrestaShop](/prestashop#install-and-connect). Each page has the download. When you save, the plugin checks the API key with MPS and says whether MPS accepted it. ### Take a test order Place an order in your own shop and choose **Powered by MPS** at checkout. The MPS checkout shows a **Test mode** banner. Pay with this test card: | Card number | Expiry date | Security code | |---|---|---| | `4111 1111 1111 1111` | Any date in the future | Any 3 digits | You come back to your shop, and the order is marked paid: | Shop system | The paid order | |---|---| | WooCommerce | **Processing**, or **Completed** when every product is virtual and downloadable | | Odoo | The Odoo transaction **Confirmed**, and the sale order confirmed | | Magento | **Processing** | | PrestaShop | **Payment accepted** | | Drupal Commerce | Checkout complete, the payment **Completed** | To see a refused payment too, pay a second order with `4000 0000 0000 0002`. More test cards are under [Test mode](/online-payments#test-mode). ### Go live Once MPS has approved your account and your contract is signed, create a **live** key and paste it, with its own webhook signing secret, in place of the test key. See [Switch to live payments](/take-live-payments#a-shop-plugin). ## Troubleshooting | What you see | What to do | |---|---| | The plugin says MPS did not accept the key | Copy the key again from where you stored it, or create a new test key. A revoked key never works again. | | MPS is not offered at checkout | Check the plugin is enabled, has an API key, and the shop's currency is euro. | | The order stays unpaid after paying | Possible causes include a shop that cannot be reached from the internet, or a webhook signing secret that is not pasted. Follow **Errors** on your shop system's page: [WooCommerce](/woocommerce#errors), [Odoo](/odoo#errors), [Magento](/magento#errors) or [PrestaShop](/prestashop#errors). | | Anything else | See **Errors** on your shop system's page, or contact MPS with the order's payment reference. | ## Related - [Set up your account](/set-up-your-account): the Online module and what live mode needs - [Switch to live payments](/take-live-payments): from the test key to the live key - [WooCommerce](/woocommerce), [Odoo](/odoo), [Magento](/magento) and [PrestaShop](/prestashop): every setting of each plugin --- # Accept payments in WooCommerce (/woocommerce) > Install the MPS Payments plugin, paste your API key, and take MPS payments in a WooCommerce shop without writing code. The **MPS Payments for WooCommerce** plugin adds **Powered by MPS** as a payment method to your shop's checkout. Your customer pays on the MPS checkout and comes back to your shop, and the plugin marks the order paid once MPS confirms the payment. You install it in the WordPress admin and paste two codes from the MPS platform. The plugin sends the order amount, order number and your shop's return addresses to MPS (Mobile Payment Solutions) to open each payment. [Download mps-payments.zip](https://github.com/mps-emi/plugins/releases/download/woocommerce-latest/mps-payments.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=woocommerce&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/woocommerce). - WordPress 6.4 or later and WooCommerce 8.3 or later, on PHP 7.4 or later. Your host can tell you which versions you have. The block checkout and the classic checkout both work. - Your shop's currency set to euro (EUR) - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it; see [For your host or developer](#for-your-host-or-developer). ## Install and connect In WordPress, open **Plugins › Add New › Upload Plugin**, choose `mps-payments.zip`, and click **Install Now**, then **Activate**. Open **WooCommerce › Settings › Payments** and click **Powered by MPS**, the name the plugin gives the payment method. Under **Connection**, paste your test key in **API key** and its webhook signing secret in **Webhook signing secret**, tick **Enable**, and click **Save changes**. The plugin sends the API key with every call. Saving checks the key with MPS straight away. The plugin shows **Connected to MPS with a test key**, or says that MPS refused the key ([Troubleshooting](#errors)). Place an order in your shop and pay it with one of the [test cards](/online-payments#test-mode). The order moves to **Processing**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: replace the test key with your live key and its webhook signing secret, and click **Save changes**. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Orders still move through paid or failed exactly as they do in live mode. A test key does not expire. It works until you revoke it. ## How payments are confirmed The plugin never takes the shopper's return to your shop as proof of payment. It reads the payment from MPS and moves the order on what MPS says: | MPS payment | WooCommerce order | |---|---| | Paid, full amount | **Processing** (or **Completed** when every product is virtual and downloadable). The payment reference is the order's **Transaction ID**. | | Paid, less than the order total | **On hold**, with a note. A card issuer can approve part of an amount; check before shipping. | | Failed | **Failed**. The shopper is sent back to your shop's checkout to try again. | | Shopper left without paying | Stays **Pending payment**, with a note, so the shopper can try again. | The plugin reads the payment when the shopper comes back, when MPS sends a webhook, and on a schedule at 10 minutes, 30 minutes, 1 hour and 6 hours after the payment was opened. An order is confirmed even when the shopper closes the tab before returning, if it is paid within those 6 hours or a webhook arrives. ## Refunds Refund an MPS order from WooCommerce's order screen: **Refund** → the amount → **Refund € … via MPS Payments**, in full or in parts. The order note says what MPS answered; a refused refund is not saved. A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. ## Updates Installed from a zip on GitHub, upload the new version the same way, in **Plugins › Add New › Upload Plugin**: WordPress offers **Replace current with uploaded** and keeps your settings. To hear about a new version, watch the repository's releases on GitHub (**Watch › Custom › Releases**). Installed from the WooCommerce Marketplace, it is updated by WooCommerce.com instead. ## Not supported yet - Currencies other than EUR. The payment method is hidden at checkout when the shop currency is not EUR. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever runs the server your shop is on: your hosting provider or your developer. ### Webhooks The plugin sends its own webhook address with every payment, so there is no address to register anywhere. MPS sends a webhook the moment the payment arrives when two things are true: - your shop is reachable on a public HTTPS address. MPS cannot reach a shop on `localhost` or a private network; - the **webhook signing secret** for your key is pasted in the plugin. MPS signs every webhook, and the plugin ignores webhooks while it has no signing secret to check them with. When either is missing, an order is confirmed when the shopper returns, or else at the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. That can be hours later, and the scheduled reads stop 6 hours after the payment was opened. A payment completed after that, such as a [late ANNA bank payment](/payment-lifecycle#a-late-anna-payment), while the shopper does not come back, is confirmed only by a webhook. Set up webhooks for a live shop. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. With the signing secret pasted, the plugin checks the signature and that the webhook is less than five minutes old, refuses anything that does not match with `401`, and reads the payment for every webhook that does. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: paste it again when you switch keys. | | Where to paste it | **WooCommerce › Settings › Payments › Powered by MPS**, under **Connection** › **Webhook signing secret** | | When it matters | Only when your shop is on a public HTTPS address: elsewhere MPS cannot reach it anyway | Without the signing secret pasted, the plugin ignores webhooks and settles orders by its scheduled checks and the shopper's return. Paste it to get orders confirmed the moment the payment arrives. Even a signed webhook only tells the plugin to read the payment from MPS, and the order is moved on what MPS answers, so a webhook on its own can never mark an order paid. When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Paste the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from the shop needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. With the webhook signing secret pasted, the plugin also acts on how each refund ends. Paid out (`refund.refunded`) adds a note to the order. Failed or canceled (`refund.failed`, `refund.canceled`) removes the WooCommerce refund, puts a fully refunded order back to the status it had before, and leaves the amount free to refund again. ### Upgrade a shop set up with a client ID and secret [#connect-an-older-setup] MPS Payments 1.0.0 connects with an API key only: a client ID and secret no longer connect. The upgrade deletes the stored client ID and secret, and until you paste an API key MPS is not offered at checkout and the admin says *MPS Payments is enabled but not offered at checkout: it has no API key.* Paste the API key and the webhook signing secret from the MPS platform (**Online › API keys**) under **WooCommerce › Settings › Payments › Powered by MPS**. API keys need plugin version 0.2.0 or later. ### How the key check works [#how-the-key-check-works] For your developer or host. To check a key on save, the plugin reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in your server's logs is the check passing, not a fault. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | MPS Payments is not offered at checkout | It is not enabled, the **API key** is empty, or the shop currency is not EUR. | Tick **Enable**, paste an API key, and set the shop currency to EUR. | | *MPS did not accept these credentials* on save | A wrong or revoked API key (*MPS refused the API key*). A test key works until you revoke it. | Create a new key in **Online › API keys** and paste it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Every call to MPS fails with `429` for a minute at a time, the right key included | More than 10 calls with a wrong API key in one minute came from the server's outgoing address, so MPS refuses that address for 60 seconds. On shared hosting another site on the same address can cause it. | Fix the wrong key; if the address is shared, ask the host for one of the shop's own. See [API key errors](/authentication#api-key-errors). | | *The payment could not be started* at checkout | MPS could not open the payment. | Tick **Debug log**, try again, and read **WooCommerce › Status › Logs**, source `mps-payments`. | | *Webhook refused: signature or timestamp does not match* in the log, with **Debug log** on | The signing secret is not the one for this key (common after switching to another key), or the shop's clock is more than five minutes off. | Paste the signing secret shown with your key, and set the server clock right. See [Webhook signing secret](#webhook-signing-secret). | | *Webhook ignored: no signing secret configured* in the log, with **Debug log** on | No webhook signing secret is pasted. | Paste the one shown with your key in **Online › API keys**. | | An order stays *Pending payment* after paying | No webhook was acted on (the shop is not on a public HTTPS address, or no webhook signing secret is pasted), and the shop could not reach MPS when the shopper returned. | Wait for the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. Paid after the 6-hour read, it is confirmed only by a webhook: set up [Webhooks](#webhooks), and contact MPS with the order's MPS payment reference. | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Accept payments in Odoo (/odoo) > Install the MPS payment provider, paste your API key, and take MPS payments in Odoo without writing code. The **MPS** payment provider for Odoo adds **Powered by MPS** as a payment method to your Odoo: on the eShop, on Odoo's own payment links and on portal invoices. Your customer pays on the MPS checkout and comes back to Odoo, and the payment is registered once MPS confirms it. You install it as an Odoo app and paste two codes from the MPS platform. The provider sends the order amount, order number and your shop's return addresses to MPS (Mobile Payment Solutions) to open each payment. Get it from the [Odoo Apps Store](https://apps.odoo.com/apps/modules/20.0/payment_mps), or [download payment_mps.zip](https://github.com/mps-emi/plugins/releases/download/odoo-latest/payment_mps.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=odoo&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/odoo). - Odoo 20, Community or Enterprise, on your own server or on Odoo.sh - Orders in euro (EUR) - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it; see [For your host or developer](#for-your-host-or-developer). Odoo Online (the odoo.com SaaS) does not install third-party addons, from the Apps Store or uploaded. Run Odoo yourself or on Odoo.sh to use the MPS provider. ## Install and connect Get the addon from the [Odoo Apps Store](https://apps.odoo.com/apps/modules/20.0/payment_mps). It is free. - **On Odoo.sh:** click **Deploy on Odoo.sh** on the listing, or commit the `payment_mps` folder to your repository. - **On your own server:** click **Download for v 20.0** (or use the download above), unzip it into a folder on your addons path, and restart Odoo. Turn on developer mode, open **Apps**, click **Update Apps List**, search for **MPS** and click **Activate**. Open **Invoicing › Configuration › Payment Providers** (or **Website › Configuration › Payment Providers**) and click **Powered by MPS**. On the **Configuration** tab, paste your test key in **API Key**, and under **Advanced** its webhook signing secret in **Webhook Signing Secret**. Click **Publish** so the provider is offered at checkout, and save. The provider sends the API key with every call. Saving checks the key with MPS straight away. If MPS refuses the key, Odoo says so and nothing is saved ([Troubleshooting](#errors)). While a test key is in use, the provider form shows *This is a test key*. Pay an order, a payment link or a portal invoice with one of the [test cards](/online-payments#test-mode). The Odoo transaction moves to **Confirmed**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: replace the test key with your live key and its webhook signing secret, and save. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. A provider needs an API key to be enabled or published; without one, saving says *Fill in the API key from the MPS platform (Online › API keys) before enabling or publishing MPS.* ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Payments still confirm or fail exactly as they do in live mode. A test key does not expire. It works until you revoke it. Odoo's own **Live** switch on the provider makes no difference to MPS: the key decides. ## How payments are confirmed The provider never takes the shopper's return to Odoo as proof of payment. It reads the payment from MPS and moves the Odoo transaction on what MPS says: | MPS payment | Odoo transaction | |---|---| | Paid, full amount | **Confirmed**: the payment is registered and the sale order confirmed (unless the quotation still waits for the shopper's online signature: Odoo confirms only signed quotations). The payment reference is the Odoo transaction's **Provider Reference**. | | Paid, less than the order total | **Pending**, with a message. A card issuer can approve part of an amount; check before delivering. | | Failed | **Canceled**. The shopper can pay again. | | Shopper left without paying | **Canceled**. The order stays payable. | The provider reads the payment when the shopper comes back, when MPS sends a webhook, and on a schedule at 10 minutes, 30 minutes, 1 hour and 6 hours after the payment was opened. A payment is confirmed even when the shopper closes the tab before returning, if it is paid within those 6 hours or a webhook arrives. ## Refunds Refund an MPS payment with Odoo's **Refund** button on the payment record: open the paid invoice and its payment. Refund in full or in parts. A refund still in progress is checked again after 10 minutes, 30 minutes, 1 hour and 6 hours. A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. ## Updates Odoo does not update addons by itself. To update, replace the `payment_mps` folder with the one from the latest version (on the [Odoo Apps Store](https://apps.odoo.com/apps/modules/20.0/payment_mps) or in the download above), restart Odoo, and click **Upgrade** on the MPS app in **Apps**. ## Not supported yet - Currencies other than EUR. The provider is not offered when the order's currency is not EUR. - Saving cards for later payments. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever runs the server your shop is on: your hosting provider or your developer. ### Webhooks The provider sends its own webhook address with every payment, so there is no address to register anywhere. MPS sends a webhook the moment the payment arrives when two things are true: - your Odoo is reachable on a public HTTPS address (its **web.base.url**). MPS cannot reach an Odoo on `localhost` or a private network; - the **webhook signing secret** of your key is pasted in the provider. The provider ignores every webhook while the field is empty. When either is missing, a payment is confirmed when the shopper returns, or else at the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. That can be hours later, and the scheduled reads stop 6 hours after the payment was opened. A payment completed after that, such as a [late ANNA bank payment](/payment-lifecycle#a-late-anna-payment), while the shopper does not come back, is confirmed only by a webhook. Set up webhooks for a live shop. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. With the signing secret pasted, the provider checks the signature and that the webhook is less than five minutes old, and refuses anything that does not match with `401`. A webhook for a payment this Odoo database does not know is answered `200` and ignored, unchecked. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: paste it again when you switch keys. | | Where to paste it | The MPS provider › **Configuration** › **Advanced** › **Webhook Signing Secret** | | When it matters | Only when your Odoo is on a public HTTPS address: without the signing secret pasted, the provider ignores webhooks | Without the signing secret pasted, the provider ignores webhooks and confirms payments by its scheduled reads and the shopper's return. Paste it to get orders confirmed the moment the payment arrives. Even a checked webhook only tells the provider to read the payment from MPS, and the Odoo transaction is moved on what MPS answers, so a forged webhook cannot mark an order paid. When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Paste the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from the shop needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. ### Upgrade a shop set up with a client ID and secret [#connect-an-older-setup] The MPS add-on 20.0.2.0.0 connects with an API key only: a client ID and secret no longer connect. The upgrade deletes the stored client ID and secret and takes a provider without an API key offline, so MPS is not offered at checkout until you paste the API key from the MPS platform (**Online › API keys**) on the provider and enable it again. API keys need addon version 20.0.1.1.0 or later. ### How the key check works [#how-the-key-check-works] For your developer or host. To check a key on save, the provider reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in your server's logs is the check passing, not a fault. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | MPS is not offered at checkout | The provider is not published, the order is not in EUR, or the MPS payment method is disabled on the **Payment Methods** tab. | Click **Publish**, enable the MPS payment method, and use EUR. | | *MPS did not accept these credentials* on save | A wrong or revoked API key. A test key works until you revoke it. | Create a new key in **Online › API keys** and paste it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Every call to MPS fails with `429` for a minute at a time, the right key included | More than 10 calls with a wrong API key in one minute came from the server's outgoing address, so MPS refuses that address for 60 seconds. On shared hosting another site on the same address can cause it. | Fix the wrong key; if the address is shared, ask the host for one of the shop's own. See [API key errors](/authentication#api-key-errors). | | *Fill in the API key from the MPS platform (Online › API keys) before enabling or publishing MPS.* on save | The provider is enabled or published without an API key. | Paste an API key. | | *Success URL must be an absolute HTTPS URL* in the log | Odoo runs behind a reverse proxy that ends HTTPS, without `proxy_mode = True` in its configuration, so it sends MPS `http://` return addresses. | Turn on proxy mode and make the proxy pass `X-Forwarded-Proto` and `X-Forwarded-Host`. | | The checkout shows an error instead of sending the shopper to MPS | Opening the payment at MPS failed. | Read the Odoo server log, logger `odoo.addons.payment_mps`: every call to MPS is logged with its answer. | | *Notification refused: signature or timestamp does not match* in the log | The signing secret is not the one for this key (common after switching to another key), or the server's clock is more than five minutes off. | Paste the signing secret shown with your key, and set the server clock right. See [Webhook signing secret](#webhook-signing-secret). | | An Odoo transaction stays *Pending* after paying | No webhook was acted on (Odoo is not on a public HTTPS address, or the webhook signing secret is not pasted in the provider), and Odoo could not reach MPS when the shopper returned. | Wait for the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. Paid after the 6-hour read, it is confirmed only by a webhook: set up [Webhooks](#webhooks), and contact MPS with the MPS payment reference. | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Accept payments in Magento (/magento) > Install the MPS Payments module on your Magento server, paste your API key, and take MPS payments without writing code of your own. The **MPS Payments** module for Magento adds **Powered by MPS** as a payment method to your shop's checkout. Your customer pays on the MPS checkout and comes back to your shop, and the module marks the order paid once MPS confirms the payment. You paste two codes from the MPS platform in the admin. The module sends the order amount, order number and your shop's return addresses to MPS (Mobile Payment Solutions) to open each payment. [Download mps-module-payments.zip](https://github.com/mps-emi/plugins/releases/download/magento-latest/mps-module-payments.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=magento&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/magento). You write no code, but installing runs commands on the server your shop runs on, and the module relies on Magento's cron. If you do not manage that server yourself, ask your hosting provider or the developer who looks after your shop to do the install step. - Magento Open Source or Adobe Commerce 2.4.7 – 2.4.9, or Mage-OS on the same versions, on PHP 8.1 – 8.5 (whichever your Magento version runs on). Your host or developer can tell you which you have. - Someone with shell access to the server, and Magento's cron running, as for any production shop - Your store's currency set to euro (EUR) - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it; see [For your host or developer](#for-your-host-or-developer). ## Install and connect Install the zip. Either way of installing a Magento module works. **From the zip**, into `app/code`: ```bash mkdir -p app/code/Mps/Payments unzip mps-module-payments.zip -d app/code/Mps/Payments bin/magento module:enable Mps_Payments bin/magento setup:upgrade bin/magento setup:di:compile # in production mode bin/magento setup:static-content:deploy # in production mode bin/magento cache:flush ``` **With Composer**, using the zip as an artifact repository. Put the zip in a folder of its own: ```bash composer config repositories.mps artifact /path/to/folder-with-the-zip composer require mobilepaymentsolutions/module-payments bin/magento setup:upgrade ``` In the admin, open **Stores › Configuration › Sales › Payment Methods** and expand **Powered by MPS**. Paste your test key in **API key** and its webhook signing secret in **Webhook signing secret**, set **Enabled** to **Yes**, and click **Save Config**. The module sends the API key with every call. Saving checks the key with MPS straight away. The module shows **Connected to MPS with a test key**, or says that MPS refused the key ([Troubleshooting](#errors)). The **API key** and **Webhook signing secret** are stored encrypted. Place an order in your shop and pay it with one of the [test cards](/online-payments#test-mode). The order moves to **Processing**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: replace the test key with your live key and its webhook signing secret, and click **Save Config**. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. ## Use Hyvä Checkout [#hyva-checkout] Hyvä Checkout is a checkout from Hyvä that replaces Magento's own. The MPS Payments module draws its part of the checkout in Magento's checkout only, so a shop on Hyvä Checkout also needs the **MPS Payments for Hyvä Checkout** add-on. A shop on the Hyvä theme that keeps Magento's checkout (Hyvä's Luma checkout fallback) needs only the MPS Payments module. [Download mps-module-payments-hyva.zip](https://github.com/mps-emi/plugins/releases/download/magento-hyva-latest/mps-module-payments-hyva.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=magento-hyva&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/magento-hyva). Hyvä Checkout lists every enabled payment method. Without the add-on, a shopper who chooses **Powered by MPS** there places an order that is never sent to the MPS checkout, and the order stays in **Pending Payment** until Magento cancels it. Install and connect the MPS Payments module first, as in [Install and connect](#install-and-connect). The add-on needs MPS Payments 1.0.0 or later, and Hyvä Checkout 1.1.13 or later. Install the add-on the same way as the module. **From the zip**, into `app/code`: ```bash mkdir -p app/code/Mps/PaymentsHyva unzip mps-module-payments-hyva.zip -d app/code/Mps/PaymentsHyva bin/magento module:enable Mps_PaymentsHyva bin/magento setup:upgrade bin/magento setup:di:compile # in production mode bin/magento setup:static-content:deploy # in production mode bin/magento cache:flush ``` **With Composer**: put the zip in the same folder as `mps-module-payments.zip` and run: ```bash composer require mobilepaymentsolutions/module-payments-hyva bin/magento setup:upgrade ``` Place an order in your shop with a test key. At the payment step, choose **Powered by MPS**: it shows your **Description**, and a test-mode notice while the key is a test key. **Place Order** sends you to the MPS checkout. Pay with one of the [test cards](/online-payments#test-mode). The add-on has no settings of its own. How orders are confirmed, refunds and every setting below are the same as in Magento's checkout. When MPS cannot open the payment, the order is canceled and the shopper is sent back to their cart, as in Magento's checkout. ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Orders still move through paid or failed exactly as they do in live mode. A test key does not expire. It works until you revoke it. ## How payments are confirmed The order is placed in **Pending Payment**, and the shopper goes on to the MPS checkout. The order confirmation e-mail is held back until MPS says the order is paid. The module never takes the shopper's return to your shop as proof of payment. It reads the payment from MPS and moves the order on what MPS says: | MPS payment | Magento order | |---|---| | Paid, full amount | Invoiced, **Processing** (or **Complete** for virtual products), and the confirmation e-mail goes out. The payment reference is the payment's **Transaction ID**. | | Paid, less than the order total | **On Hold**, with a comment. A card issuer can approve part of an amount; check before shipping. | | Failed | **Canceled**, with a comment. The shopper is sent back to their cart to try again. | | Shopper left without paying | **Canceled**, with a comment. The shopper is sent back to their cart to try again. | A retry is a new order from the same cart: a Magento order is paid once. The module reads the payment when the shopper comes back, when MPS sends a webhook, and from Magento's cron at 10 minutes, 30 minutes, 1 hour and 6 hours after the payment was opened. An order is confirmed even when the shopper closes the tab before returning, if it is paid within those 6 hours or a webhook arrives. Magento itself cancels an order left in **Pending Payment** after **Stores › Configuration › Sales › Sales › Orders Cron Settings › Pending Payment Order Lifetime** (8 hours by default). Keep it longer than 6 hours. ## Settings | Setting | Scope | What it does | |---|---|---| | **Enabled** | Website | Offer MPS at checkout. | | **Title**, **Description** | Store view | What the shopper sees at checkout. The default title is *Powered by MPS*, the same in every language. Set them per store view to change the wording per language; the default description is translated into Dutch and French. | | **API key** | Website | Your API key, sent with every call; stored encrypted. A key starting `mps_test_` is a test key: MPS test cards only, no card charged. Without it, MPS is not offered. | | **Webhook signing secret** | Website | See [Webhook signing secret](#webhook-signing-secret). | | **Gateway URL** | Website | Leave as is unless MPS asks you to change it. | | **Debug log** | Website | Logs every call to MPS in `var/log/mps_payments.log`, never the API key, the webhook signing secret or payment links. | | **Payment from Applicable Countries**, **Payment from Specific Countries** | Website | Magento's usual restriction by billing country: all countries, or only the ones you select. | | **Sort Order** | Website | Where MPS appears among the payment methods at checkout. | Every setting can also be set with `bin/magento config:set payment/mps_payments/ `, or in `app/etc/env.php`, which locks it in the admin. ## Refunds Refund an MPS order with an online credit memo, opened **from the invoice** (Invoices → the invoice → **Credit Memo** → **Refund**), in full or in parts. A credit memo MPS refuses is not saved, and the message says why. A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. ## Updates Install the new zip the same way (unzip it over `app/code/Mps/Payments`, or put it in the artifact folder and run `composer update mobilepaymentsolutions/module-payments`), then run `bin/magento setup:upgrade`. Update the [Hyvä Checkout add-on](#hyva-checkout) the same way: unzip it over `app/code/Mps/PaymentsHyva`, or run `composer update mobilepaymentsolutions/module-payments-hyva`. ## Not supported yet - **Ordering from the admin.** MPS is a checkout payment method; it is not offered when an order is created in the admin. - Currencies other than EUR. The payment method is hidden at checkout when the store's currency is not EUR. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever runs the server your shop is on: your hosting provider or your developer. ### Webhooks The module sends its own webhook address with every payment, so there is no address to register anywhere. MPS sends a webhook the moment the payment arrives when two things are true: - your shop is reachable on a public HTTPS address. MPS cannot reach a shop on `localhost` or a private network; - the key's **webhook signing secret** is pasted in the module. MPS signs every webhook, and the module ignores webhooks while no signing secret is set. When either is missing, an order is confirmed when the shopper returns, or else at the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. That can be hours later, and the scheduled reads stop 6 hours after the payment was opened. A payment completed after that, such as a [late ANNA bank payment](/payment-lifecycle#a-late-anna-payment), while the shopper does not come back, is confirmed only by a webhook. Set up webhooks for a live shop. A webhook is matched to its order by the order number MPS echoes back, and only when the payment reference stored on that order is the webhook's. The payment reference is shown with the payment on the order in the admin. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. With the signing secret pasted, the module checks the signature and that the webhook is less than five minutes old, and refuses anything that does not match with `401`. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: paste it again when you switch keys. | | Where to paste it | **Stores › Configuration › Sales › Payment Methods › Powered by MPS**, **Webhook signing secret** | | When it matters | Only when your shop is on a public HTTPS address: without it the module ignores webhooks | Without the signing secret pasted, the module ignores webhooks and settles orders by its scheduled checks and the shopper's return. Paste it to get orders confirmed the moment the payment arrives. Either way a webhook only tells the module to read the payment from MPS, and the order is moved on what MPS answers, so a forged webhook cannot mark an order paid. When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Paste the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from the shop needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. ### Upgrade a shop set up with a client ID and secret [#connect-an-older-setup] The MPS Payments module 1.0.0 connects with an API key only: a client ID and secret no longer connect. The upgrade deletes the stored client ID and secret, and until you paste an API key MPS is not offered at checkout and the admin says *MPS Payments is enabled but has no API key, so it is not offered at checkout.* Paste the API key and the webhook signing secret from the MPS platform (**Online › API keys**) under **Stores › Configuration › Sales › Payment Methods › Powered by MPS**. API keys need module version 0.2.0 or later. ### How the key check works [#how-the-key-check-works] For your developer or host. To check a key on save, the module reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in your server's logs is the check passing, not a fault. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | In Hyvä Checkout, **Place Order** with MPS goes to the order confirmation without the MPS checkout | The [Hyvä Checkout add-on](#hyva-checkout) is not installed or not enabled. The order stays in **Pending Payment** until Magento cancels it. | Install the add-on and run `bin/magento setup:upgrade`. | | MPS Payments is not offered at checkout | It is not enabled, the **API key** is empty, the store currency is not EUR, or the billing country is not allowed. | Set **Enabled** to **Yes**, paste an API key, use EUR, and check **Payment from Applicable Countries**. | | *MPS did not accept these credentials* on save | A wrong or revoked API key (*MPS refused the API key*). A test key works until you revoke it. | Create a new key in **Online › API keys** and paste it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Every call to MPS fails with `429` for a minute at a time, the right key included | More than 10 calls with a wrong API key in one minute came from the server's outgoing address, so MPS refuses that address for 60 seconds. On shared hosting another site on the same address can cause it. | Fix the wrong key; if the address is shared, ask the host for one of the shop's own. See [API key errors](/authentication#api-key-errors). | | *The payment could not be started* at checkout | MPS could not open the payment. The order is canceled and the cart restored. | Set **Debug log** to **Yes**, try again, and read `var/log/mps_payments.log`. | | *Webhook refused: signature or timestamp does not match* in the log, with **Debug log** on | The signing secret is not the one for this key (common after switching to another key), or the server's clock is more than five minutes off. | Paste the signing secret shown with your key, and set the server clock right. See [Webhook signing secret](#webhook-signing-secret). | | *Webhook ignored: no signing secret configured* in the log, with **Debug log** on | No webhook signing secret is pasted. Until then orders are confirmed by the return and the scheduled reads. | Paste the key's **Webhook signing secret**. | | An order stays *Pending Payment* after paying | No webhook was acted on (the shop is not on a public HTTPS address, or no webhook signing secret is pasted), the shop could not reach MPS when the shopper returned, and Magento's cron is not running. | Check that `bin/magento cron:run` runs every minute. See [Webhooks](#webhooks). | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Accept payments in PrestaShop (/prestashop) > Install the MPS Payments module, paste your API key, and take MPS payments in a PrestaShop shop without writing code. The **MPS Payments** module for PrestaShop adds **Powered by MPS** as a payment option to your shop's checkout. Your customer pays on the MPS checkout and comes back to your shop, and the module makes the order once MPS confirms the payment. You install it in the back office and paste two codes from the MPS platform. The module sends the order amount, order number and your shop's return addresses to MPS (Mobile Payment Solutions) to open each payment. [Download mpspayments.zip](https://github.com/mps-emi/plugins/releases/download/prestashop-latest/mpspayments.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=prestashop&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/prestashop). You install the module from the back office and write no code. The module also needs an address called every 5 minutes. PrestaShop's **Cron tasks manager** module can do that; if it is not available on your shop, ask your hosting provider or the developer who looks after your shop to set up the task. - PrestaShop 8.0 to 9.x, on the PHP version it needs (7.2.5 or later for PrestaShop 8) with the `curl` extension. The module refuses to install without it. Your host can confirm these. - Carts in euro (EUR) - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. - A way to call an address every 5 minutes: PrestaShop's **Cron tasks manager** module, or a crontab on your server ([Scheduled checks](#scheduled-checks)) - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it; see [For your host or developer](#for-your-host-or-developer). ## Install and connect In the back office, open **Modules › Module Manager**, click **Upload a module**, and drop `mpspayments.zip` on it. PrestaShop installs it straight away. Click **Configure** on **Powered by MPS**. Paste your test key in **API key** and its webhook signing secret in **Webhook signing secret**, and click **Save**. The module sends the API key with every call. Saving checks the key with MPS straight away. The module shows **Connected to MPS with a test key**, or says that MPS refused the key ([Troubleshooting](#errors)). Copy the address under **Scheduled checks** and have it called every 5 minutes, as [Scheduled checks](#scheduled-checks) describes. Pay a cart in your shop with one of the [test cards](/online-payments#test-mode). The order is made in **Payment accepted**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: paste your live key and its webhook signing secret, and click **Save**. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. The API key and the webhook signing secret are never shown again: leave a field empty when you save to keep what is stored. A saved API key cannot be cleared from the form: an empty field keeps it; paste a new key to replace it. MPS is offered for every currency the module is allowed for in **Payment › Preferences**, but only when the cart is in EUR. ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Orders are still made or not exactly as they are in live mode. A test key does not expire. It works until you revoke it. ## How payments are confirmed The module makes the order only once MPS says the cart was paid. Until then there is no order: no confirmation e-mail goes out and no stock is set aside, and a payment that does not go through leaves the shopper's cart exactly as it was. The module never takes the shopper's return to your shop as proof of payment. It reads the payment from MPS and acts on what MPS says: | MPS payment | PrestaShop | |---|---| | Paid, full amount | The order is made in **Payment accepted**, and the confirmation e-mail goes out. The payment reference is the order payment's **Transaction ID**. | | Paid, less than the order total | The order is made with the approved amount as the amount paid, so PrestaShop puts it in **Payment error**. A private note gives both amounts. A card issuer can approve part of an amount; check before shipping. | | Failed | No order. The shopper is sent back to the payment step, with their cart, to try again. | | Shopper left without paying | No order. The cart stays as it was. | The module reads the payment when the shopper comes back, when MPS sends a webhook, and on the scheduled checks at 10 minutes, 30 minutes, 1 hour and 6 hours after the payment was opened. An order is made even when the shopper closes the tab before returning, if it is paid within those 6 hours or a webhook arrives. A shopper who comes back before MPS has finished sees a short *We are confirming your payment* page that looks again by itself. If a shopper manages to pay the same cart twice (two tabs, say), there is still one order. It gets a private note naming the second payment, to refund in MPS: only the order's own payment is refunded from PrestaShop. ## Settings | Setting | What it does | |---|---| | **API key** | Your API key, sent with every call. A key starting `mps_test_` is a test key. Never shown again; an empty field on save keeps the stored key. Without it, MPS is not offered. | | **Webhook signing secret** | See [Webhook signing secret](#webhook-signing-secret). | | **Gateway URL** | Leave as is unless MPS asks you to change it. Only an `https://` address is saved (empty means the default); anything else is refused and the previous one kept. | | **Debug log** | Logs every call to MPS in **Advanced Parameters › Logs**, never the API key, the webhook signing secret or payment links. | | **Title**, **Description** | What the shopper sees at checkout. Left empty, the title is *Powered by MPS*, the same in every language, and the description a standard text in the shopper's language (English, Dutch or French). | | **Scheduled checks** | The address to call every 5 minutes. | In a multistore, each shop has its own settings: pick the shop at the top of the back office before you configure. ## Refunds A partial refund, standard refund or product return on an MPS order refunds the payment: the credit slip's amount (tax and shipping included) is sent to MPS, and the order gets a private message with the answer. Ticking **Generate a voucher** refunds with the voucher instead, and nothing is sent to MPS. A shopper whose group sees prices tax excluded, such as a B2B group, is the exception: a credit slip with a chosen amount or a deducted voucher does not say how much that is tax included. The module then sends nothing to MPS and says so in the order's private message. Refund that amount yourself through the [refund API](/refunds#refund-a-payment). A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. ## Updates Upload the new zip the same way, in **Modules › Module Manager › Upload a module**. PrestaShop sees it is a newer version of a module already installed and upgrades it, keeping your settings. ## Not supported yet - **Orders from the back office.** Choosing *Powered by MPS* as the payment method of an order created in the back office takes no payment; it only labels the order. - Currencies other than EUR. The payment option is hidden at checkout when the cart is not in EUR. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever runs the server your shop is on: your hosting provider or your developer. ### Scheduled checks PrestaShop has no scheduler of its own, so the checks run when an address is called. The module's settings page shows the address, with its `token` parameter, for example `https:///module/mpspayments/cron?token=…`. Call it every 5 minutes, either with a crontab line on your server: ```bash */5 * * * * curl -fsS "https:///module/mpspayments/cron?token=…" >/dev/null ``` or with PrestaShop's **Cron tasks manager** module. A call without the right `token` is refused with `403`. Each call reads the open payments that are due: a payment is checked on the first call 10 minutes, 30 minutes, 1 hour and 6 hours after it was opened, and not after that. Without the checks, an order is still made when the shopper returns or MPS sends a webhook. The checks are the safety net for a shopper who closes the tab on a shop MPS cannot reach. ### Webhooks The module sends its own webhook address with every payment, so there is no address to register anywhere. MPS sends a webhook the moment the payment arrives when two things are true: - your shop is reachable on a public HTTPS address. MPS cannot reach a shop on `localhost` or a private network; - the key's **webhook signing secret** is pasted in the module. MPS signs every webhook; without the signing secret the module ignores them. When either is missing, an order is made when the shopper returns, or else at the next scheduled check: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. That can be hours later, and the scheduled checks stop 6 hours after the payment was opened. A payment completed after that, such as a [late ANNA bank payment](/payment-lifecycle#a-late-anna-payment), while the shopper does not come back, is confirmed only by a webhook. Set up webhooks for a live shop. Webhooks and the scheduled checks keep working while the shop is in maintenance mode. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. With the signing secret pasted, the module checks the signature and that the webhook is less than five minutes old, and refuses anything that does not match with `401`. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: paste it again when you switch keys. | | Where to paste it | **Modules › Module Manager › Powered by MPS › Configure**, **Webhook signing secret**. To remove it, switch **Remove the webhook signing secret** on and save. | | When it matters | Only when your shop is on a public HTTPS address, where MPS can send webhooks at all | Without the signing secret pasted, the module ignores webhooks and settles orders by its scheduled checks and the shopper's return. Paste it to get orders confirmed the moment the payment arrives. Either way, a webhook only tells the module to read the payment from MPS, and the order is made on what MPS answers, so a forged webhook cannot make an order. When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Paste the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from the shop needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. ### Upgrade a shop set up with a client ID and secret [#connect-an-older-setup] The MPS Payments module 1.0.0 connects with an API key only: a client ID and secret no longer connect. The upgrade deletes the stored client ID and secret, and until you paste an API key MPS is not offered at checkout and the admin says *Not configured: MPS is not offered at checkout until an API key is saved.* Paste the API key and the webhook signing secret from the MPS platform (**Online › API keys**) in the module settings. API keys need module version 0.2.0 or later. ### How the key check works [#how-the-key-check-works] For your developer or host. To check a key on save, the module reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in your server's logs is the check passing, not a fault. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | MPS is not offered at checkout | The **API key** is empty, the cart is not in EUR, or the module is not allowed for the currency, country or carrier in **Payment › Preferences**. | Paste an API key, and allow the module in **Payment › Preferences**. | | *MPS did not accept these credentials* on save | A wrong or revoked API key (*MPS refused the API key*). A test key works until you revoke it. | Create a new key in **Online › API keys** and paste it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Every call to MPS fails with `429` for a minute at a time, the right key included | More than 10 calls with a wrong API key in one minute came from the server's outgoing address, so MPS refuses that address for 60 seconds. On shared hosting another site on the same address can cause it. | Fix the wrong key; if the address is shared, ask the host for one of the shop's own. See [API key errors](/authentication#api-key-errors). | | *The payment could not be started* at checkout | MPS could not open the payment. | Switch **Debug log** on, try again, and read **Advanced Parameters › Logs**, filtered on `MpsPayments`. | | *Webhook refused: signature or timestamp does not match* in the log, with **Debug log** on | The signing secret is not the one for this key (common after switching to another key), or the server's clock is more than five minutes off. | Paste the signing secret shown with your key, and set the server clock right. See [Webhook signing secret](#webhook-signing-secret). | | The shopper paid but there is no order | No webhook arrived (the shop is not on a public HTTPS address, or the webhook signing secret is not pasted in the module), the shopper did not come back, and the scheduled-check address is not being called. | Call the address once by hand: it reads every open payment whose next check is due, and makes the order. Then set up the [Scheduled checks](#scheduled-checks). | | *cart … was paid (payment …) but no order was made* in the log | The shopper was deleted from the shop, the module was disabled, or MPS is no longer allowed for the cart's country, currency or the shopper's group in **Payment › Preferences**. | Fix it; the next scheduled check makes the order, if one is still due (the last comes 6 hours after the payment was opened). After that, a webhook makes it, or contact MPS with the payment reference. | | An order is in *Payment error* | MPS approved less than the order total, or the cart was changed after the payment was opened. | Read the order's private note: it gives the amounts. | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Accept payments in Drupal Commerce (/drupal) > Install the Commerce MPS module on your Drupal server, paste your API key, and take MPS payments without writing code of your own. The **Commerce MPS** module adds **Powered by MPS** as a payment gateway to your Drupal Commerce checkout. Your customer pays on the MPS checkout and comes back to your shop, and the module marks the payment completed once MPS confirms it. You paste two codes from the MPS platform in the admin. The module sends the order amount, order ID and your shop's return addresses to MPS (Mobile Payment Solutions) to open each payment. Get it from the [Drupal.org project page](https://www.drupal.org/project/commerce_mps), or [download commerce_mps.zip](https://github.com/mps-emi/plugins/releases/download/drupal-latest/commerce_mps.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=drupal&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/drupal). You write no code, but installing puts the module on the server your shop runs on, and the module relies on Drupal's cron. If you do not manage that server yourself, ask your hosting provider or the developer who looks after your shop to do the install step. - Drupal 10.3 – 11 with Drupal Commerce 3, on PHP 8.1 or later. Your host or developer can tell you which you have. - Someone with access to the server, and Drupal's cron running (a system cron, or the **Automated Cron** module) - Your store's currency set to euro (EUR) - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. - For orders confirmed the moment they are paid: your shop online and reachable from the internet. Your host or developer can confirm it; see [For your host or developer](#for-your-host-or-developer). ## Install and connect Install the module from [Drupal.org](https://www.drupal.org/project/commerce_mps) with Composer, and enable it: ```bash composer require 'drupal/commerce_mps:^1.0' drush pm:install commerce_mps ``` Without Drush, open **Extend**, tick **Commerce MPS** and click **Install**. A site not managed with Composer can unzip the download above into `web/modules/custom` instead (the zip holds the folder `commerce_mps`), then enable the module the same way. In the admin, open **Commerce › Configuration › Payment gateways**, click **Add payment gateway**, and choose **Powered by MPS**. Paste your test key in **API key** and its webhook signing secret in **Webhook signing secret**, and click **Save**. The module sends the API key with every call. Saving checks the key with MPS straight away. The module shows **Connected to MPS with a test key**, or says that MPS refused the key ([Troubleshooting](#errors)). Place an order in your shop and pay it with one of the [test cards](/online-payments#test-mode). Checkout completes, and the order's payment is **Completed**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: replace the test key with your live key and its webhook signing secret, and click **Save**. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Orders still move through paid or failed exactly as they do in live mode. The key decides the gateway's mode: there is no separate test or live switch. A test key does not expire. It works until you revoke it. ## How payments are confirmed On the review step the shopper clicks **Pay and complete purchase** and goes on to the MPS checkout. The order stays the shopper's cart until MPS says it is paid. The module never takes the shopper's return to your shop as proof of payment. It reads the payment from MPS and moves the order on what MPS says: | MPS payment | Drupal Commerce | |---|---| | Paid, full amount | The payment **Completed**, the order placed, and the order receipt goes out. The MPS payment reference is the payment's **Remote ID**. | | Paid, less than the order total | The payment **Completed** for what MPS approved, the order placed with a balance left, and a note in the order's activity. A card issuer can approve part of an amount; check before shipping. | | Failed | The payment **Authorization (Voided)**. The shopper is back on the review step with the cart intact, to pay again. | | Shopper left without paying | The payment **Authorization (Voided)**. The shopper is back on the review step with the cart intact, to pay again. | Each try to pay is a payment of its own on the order's **Payments** tab: a declined try stays there as voided next to the one that was paid. The module reads the payment when the shopper comes back, when MPS sends a webhook, and from Drupal's cron at 10 minutes, 30 minutes, 1 hour and 6 hours after the payment was opened. An order is confirmed even when the shopper closes the tab before returning, if it is paid within those 6 hours or a webhook arrives. ## Settings | Setting | What it does | |---|---| | **Name**, **Display name** | The gateway's name in the admin, and what the shopper sees at checkout. **Display name** starts as *Powered by MPS*, the same in every language. | | **API key** | Your API key, sent with every call. A key starting `mps_test_` is a test key: MPS test cards only, no card charged. Without it, MPS is not offered. | | **Webhook signing secret** | See [Webhook signing secret](#webhook-signing-secret). | | **Advanced › Gateway URL** | Leave as is unless MPS asks you to change it. | | **Advanced › Debug log** | Logs every call to MPS in the site log (**Reports › Recent log messages**, type `commerce_mps`), never the API key, the webhook signing secret or payment links. | | **Conditions** | Drupal Commerce's usual conditions, such as stores or order total, for when MPS is offered. | The settings are Drupal configuration. To keep the API key and the webhook signing secret out of a configuration export, set them in `settings.php`: ```php $config['commerce_payment.commerce_payment_gateway.mps']['configuration']['api_key'] = getenv('MPS_API_KEY'); $config['commerce_payment.commerce_payment_gateway.mps']['configuration']['webhook_secret'] = getenv('MPS_WEBHOOK_SECRET'); ``` Replace `mps` with the machine name you gave the gateway. ## Refunds Refund an MPS payment from the order's **Payments** tab: **Refund** on the completed payment, in full or in parts. A refund MPS refuses is not recorded, and the message says why. A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. ## Updates With Composer, run `composer update drupal/commerce_mps`; without Composer, unzip the new zip over `web/modules/custom/commerce_mps`. Then run `drush updatedb` and `drush cache:rebuild`. Drupal's **Reports › Available updates** shows when a new version is out on Drupal.org. ## Not supported yet - **Payments added in the admin.** MPS is a checkout payment gateway; an order's payment cannot be added through MPS from the admin. - Currencies other than EUR. The gateway is hidden at checkout when the order's currency is not EUR. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever runs the server your shop is on: your hosting provider or your developer. ### Webhooks The module sends its own webhook address (`/payment/notify/`) with every payment, so there is no address to register anywhere. MPS sends a webhook the moment the payment arrives when two things are true: - your shop is reachable on a public HTTPS address. MPS cannot reach a shop on `localhost` or a private network; - the key's **webhook signing secret** is pasted in the module. MPS signs every webhook, and the module ignores webhooks while no signing secret is set. When either is missing, an order is confirmed when the shopper returns, or else at the next scheduled read: 10 minutes, 30 minutes, 1 hour or 6 hours after the payment was opened. That can be hours later, and the scheduled reads stop 6 hours after the payment was opened. A payment completed after that, such as a [late ANNA bank payment](/payment-lifecycle#a-late-anna-payment), while the shopper does not come back, is confirmed only by a webhook. Set up webhooks for a live shop. A webhook is matched to its order by the payment reference stored on the order's payment, and only when the order ID MPS echoes back is that order's. A webhook that places the order before the shopper is back is fine: the returning shopper sees the completed order. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. With the signing secret pasted, the module checks the signature and that the webhook is less than five minutes old, and refuses anything that does not match with `401`. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: paste it again when you switch keys. | | Where to paste it | **Commerce › Configuration › Payment gateways**, the MPS gateway, **Webhook signing secret** | | When it matters | Only when your shop is on a public HTTPS address: without it the module ignores webhooks | Either way a webhook only tells the module to read the payment from MPS, and the order is moved on what MPS answers, so a forged webhook cannot mark an order paid. When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Paste the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from the shop needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. ### How the key check works [#how-the-key-check-works] To check a key on save, the module reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in your server's logs is the check passing, not a fault. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | MPS is not offered at checkout | The gateway is disabled, the **API key** is empty, the order's currency is not EUR, or a condition excludes the order. | Enable the gateway, paste an API key, use EUR, and check the gateway's **Conditions**. | | *MPS refused the API key (401)* on save | A wrong or revoked API key. A test key works until you revoke it. | Create a new key in **Online › API keys** and paste it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Every call to MPS fails with `429` for a minute at a time, the right key included | More than 10 calls with a wrong API key in one minute came from the server's outgoing address, so MPS refuses that address for 60 seconds. On shared hosting another site on the same address can cause it. | Fix the wrong key; if the address is shared, ask the host for one of the shop's own. See [API key errors](/authentication#api-key-errors). | | *Payment failed at the payment server* at checkout | MPS could not open the payment. The cart is kept. | Tick **Debug log**, try again, and read **Reports › Recent log messages** (type `commerce_mps`). | | *Webhook refused: signature or timestamp does not match* in the log, with **Debug log** on | The signing secret is not the one for this key (common after switching to another key), or the server's clock is more than five minutes off. | Paste the signing secret shown with your key, and set the server clock right. See [Webhook signing secret](#webhook-signing-secret). | | *Webhook ignored: no signing secret configured* in the log, with **Debug log** on | No webhook signing secret is pasted. Until then orders are confirmed by the return and the scheduled reads. | Paste the key's **Webhook signing secret**. | | A payment stays **New** after paying | No webhook was acted on (the shop is not on a public HTTPS address, or no webhook signing secret is pasted), the shop could not reach MPS when the shopper returned, and Drupal's cron is not running. | Check that cron runs (**Reports › Status report** shows when it last ran). See [Webhooks](#webhooks). | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Accept payments on a Wix site (/wix) > Copy the MPS files into your Premium Wix site, save your API key in the Secrets Manager, and take MPS payments at the Wix checkout. The MPS files add **Powered by MPS** as a payment method to the checkout of your own Wix site. Your customer pays on the MPS checkout and comes back to your site, and Wix marks the order paid once MPS confirms it. You copy a few files into the site's code and save two codes from the MPS platform. The files send the order amount, the reference Wix gives the payment and the site's return addresses to MPS (Mobile Payment Solutions) to open each payment. [Download mps-payments-wix.zip](https://github.com/mps-emi/plugins/releases/download/wix-latest/mps-payments-wix.zip) — always the latest version. Every version is in its [releases on GitHub](https://github.com/mps-emi/plugins/releases?q=wix&expanded=true), with the [source](https://github.com/mps-emi/plugins/tree/main/wix). You write no code, but installing copies files into your site's code in the Wix editor (Velo). If you do not work in the editor's code panel yourself, ask the developer who looks after your site to do the install steps. - A Wix site on a Premium plan that takes payments, with Wix Stores or another Wix app that has a checkout - Your site's currency set to euro (EUR) - Your site published at least once, at the address shoppers use - A test API key and its webhook signing secret, from **Online › API keys** on the MPS platform. [Connect your webshop](/connect-your-webshop#create-a-test-key) shows how. ## Install and connect Unzip `mps-payments-wix.zip`. It holds the folder `mps-payments/backend` with the files laid out as the Wix code panel shows them. In the Wix editor, turn on the code panel (**Dev Mode** in the Wix Editor, the **Code** icon in Wix Studio) and open **Public & Backend**. Under **Service Plugins**, click **+**, choose **Payment**, enter the name `mps-payments` exactly, and click **Add & Edit Code**. Wix creates the folder `payment-provider/mps-payments` with two files. Replace the content of each with the file of the same name from the zip: | In the Wix code panel | From the zip | |---|---| | `payment-provider/mps-payments/mps-payments.js` | `backend/service-plugins/payment-provider/mps-payments/mps-payments.js` | | `payment-provider/mps-payments/mps-payments-config.js` | `backend/service-plugins/payment-provider/mps-payments/mps-payments-config.js` | Under **Backend**, add a folder `mps` and, in it, a file for each file in the zip's `backend/mps/` folder, with the same name and content: `api.js`, `outcome.js`, `provider.js`, `refund.js`, `signature.js`, `version.js` and `wix.js`. Under **Backend**, add the file `http-functions.js` from the zip. If your site already has one, add the zip's two `import` lines and its `post_mpsWebhook` function to it instead. In your site's dashboard, open **Developer Tools › Secrets Manager** and add two entries: | Name | Value | |---|---| | `mps_api_key` | Your test key, starting `mps_test_` | | `mps_webhook_secret` | The key's webhook signing secret, starting `whsec_` | The code reads them on Wix's servers; they never reach the browser. Publish the site. Wix reads the payment method's name and settings when you publish. In the dashboard, open **Settings › Accept Payments**, click **See More Payment Options**, find **Powered by MPS** and click **Connect**. Enter your site's address as shoppers open it, such as `https://www.myshop.be` (on a free Wix address, `https://.wixsite.com/`), and click **Connect**. Connecting checks the API key with MPS straight away. **Powered by MPS (test key)** shows as connected, or Wix shows why MPS refused ([Troubleshooting](#errors)). Place an order on your site and pay it with one of the [test cards](/online-payments#test-mode). You come back to the Wix confirmation, and the order is paid in **Orders**, as [How payments are confirmed](#how-payments-are-confirmed) describes. Go live: in the Secrets Manager, replace `mps_api_key` with your live key and `mps_webhook_secret` with the live key's webhook signing secret. See [Switch to live payments](/take-live-payments#a-shop-plugin) for what MPS needs first. ## Test mode A test key is an API key starting `mps_test_`. A card payment made with a test key is a **test payment**: the checkout shows a test-mode banner and takes only the [test cards](/online-payments#test-mode), no card is charged and nothing is paid out. Orders still move through paid or failed exactly as they do in live mode. The key decides the mode: there is no separate test or live switch. A test key does not expire. It works until you revoke it. ## How payments are confirmed The shopper clicks **Place Order** and goes on to the MPS checkout. Wix keeps the order waiting for payment until MPS confirms it. The MPS files never take the shopper's return to your site as proof of payment. When MPS sends its webhook, they read the payment from MPS and tell Wix what MPS says: | MPS payment | Wix | |---|---| | Paid, full amount | Wix is told the order is paid. | | Paid, less than the order total | Wix is told the payment is declined, and the code logs that a part was paid. A card issuer can approve part of an amount: refund that part in MPS. | | Failed | Wix is told the payment is declined. | | Shopper left without paying | Wix is told the shopper canceled. | MPS sends its webhook the moment a payment arrives. Wix learns that an order is paid only from that webhook, so the webhook signing secret is required: connecting refuses to finish without it. ## Settings | Setting | Where | What it does | |---|---|---| | `mps_api_key` | **Secrets Manager** | Your API key, sent with every call. A key starting `mps_test_` is a test key: MPS test cards only, no card charged. | | `mps_webhook_secret` | **Secrets Manager** | The key's webhook signing secret. See [Webhook signing secret](#webhook-signing-secret). | | `mps_gateway_url` | **Secrets Manager**, optional | Leave it out unless MPS asks you to set it. | | Site address | **Accept Payments › Powered by MPS** | The address MPS sends its webhooks to: your site's address followed by `/_functions/mpsWebhook`. | The name shoppers and the dashboard see is **Powered by MPS**, the same in every language. ## Refunds Refund an order paid with MPS from **Orders** in your dashboard, in full or in parts. A refund MPS refuses is not made, and Wix shows why. A test key can always refund. A live key needs the refund permission first: ask MPS to add it to your key. Every refund waits 4 hours before it is sent, and can be [canceled in MPS](/refunds#cancel-a-refund) until then. Wix shows a refund as made as soon as MPS accepts it: a refund you cancel in MPS stays refunded in Wix, so correct the order yourself. ## Updates Replace the content of each file in your site with the file of the same name from the new zip, then publish the site. `backend/mps/version.js` names the version you have. ## Not supported yet - Currencies other than EUR. Wix refuses to connect MPS on a site whose currency is not EUR, and a payment in another currency is declined. - A logo next to **Powered by MPS** at checkout. - Listing MPS in the Wix App Market. These files are for your own site. ## For your host or developer [#for-your-host-or-developer] The details below are for whoever looks after your site's code. ### Webhooks Every payment carries the webhook address built from the site address you entered when connecting, so there is no address to register anywhere. The address is your site's address followed by `/_functions/mpsWebhook`, served by `post_mpsWebhook` in `backend/http-functions.js`. A webhook only tells the code to read the payment from MPS, and Wix is told what MPS answers, so a forged webhook cannot mark an order paid. A payment MPS still reads as pending is answered `503`, and MPS delivers the webhook again later. A repeated webhook tells Wix the same thing again and changes nothing. ### Webhook signing secret Every webhook MPS sends is signed with a signing secret that belongs to your key. Every key issued in the MPS platform, test or live, comes with one. The code checks the signature and that the webhook is less than five minutes old, and refuses anything that does not match with `401`. | | | |---|---| | What it looks like | `whsec_` followed by 43 characters | | Where to get it | Shown with your key in **Online › API keys**. A new key comes with a new signing secret: save it again when you switch keys. | | Where to save it | **Developer Tools › Secrets Manager**, as `mps_webhook_secret` | When MPS issues you a new signing secret, the previous one keeps being accepted for 24 hours and webhooks carry both signatures in that time. Save the new signing secret whenever it suits you within that day; no webhook is lost. ### Refund permission [#refund-permission] Refunding from Wix needs the `payments:refund` scope on the API key: a test key always has it, a live key only once MPS granted it. ### How the key check works [#how-the-key-check-works] To check the key when you connect, the code reads a payment that does not exist. MPS answers `404` to a key it accepts, and `401` or `403` to a key it refuses. A `404` for that call in **Logs** is the check passing, not a fault. ### Logs The code writes every call to MPS to the site's logs (**Developer Tools › Logging Tools**), each line starting `[MPS]`: never the API key, the webhook signing secret or payment links. ## Troubleshooting [#errors] | What you see | Cause | What to do | |---|---|---| | **Powered by MPS** is not in **See More Payment Options** | The site is not published since the files were added, or the service plugin is not named `mps-payments`. | Check the folder name, then publish the site. | | Connecting says the API key is missing | No `mps_api_key` in the Secrets Manager, or it does not start `mps_live_` or `mps_test_`. | Add the key in **Developer Tools › Secrets Manager**. | | Connecting says the webhook signing secret is missing | No `mps_webhook_secret` in the Secrets Manager. | Add the key's webhook signing secret. | | Connecting says MPS refused the API key | A wrong or revoked API key. A test key works until you revoke it. | Create a new key in **Online › API keys** and save it with its webhook signing secret. See [API key errors](/authentication#api-key-errors). | | Connecting says the site address is not valid | The address does not start `https://`, or is not a public address. | Enter the address shoppers open, such as `https://www.myshop.be`. | | An order stays waiting for payment after paying | The webhook did not reach the site, or was refused. | In the logs, look for *Webhook refused: signature or timestamp does not match* (the signing secret is not this key's), or for no `[MPS] Webhook` line at all (check the site address you connected with). | ## Related - [Connect your webshop](/connect-your-webshop): the other shop systems, and the steps from test order to live - [Switch to live payments](/take-live-payments#a-shop-plugin): from the test key to the live key - For your developer: [Webhooks](/webhooks), [Payment lifecycle](/payment-lifecycle), [Refunds](/refunds) and [Test mode and test cards](/online-payments#test-mode) --- # Build with AI (/build-with-ai) > Choose the AI tool you build with, and follow its page with the ready-made prompt and the test checklist. Building your site or app with an AI tool? You write no code of your own: you give the assistant these pages and a ready-made prompt, and it builds the payments. Choose the tool you use. ## How it works 1. **Get a test API key.** On the MPS platform, open **Online › API keys**, choose **Test** and click **Create API key**. The API key is the code your app uses to take payments; a test key takes test payments only, so no card is charged. The platform shows it once, with its signing secret. 2. **Paste the prompt** from your tool's page. It tells the assistant to read these pages and follow them. 3. **Test every case** on [the checklist](/build-with-ai/vibe-coding#done-means) before you use a live key. The assistant writes the code, but it takes payments for your business and moves your money, so you decide what goes live. Give it a test key only, never a live key, and test every case on [the checklist](/build-with-ai/vibe-coding#done-means) before you switch to live mode. Taking payments without building anything? A [payment link](/payment-links) or a shop plugin such as [WooCommerce](/woocommerce) needs no assistant. ## Why the assistant needs these pages An assistant that guesses an API gets payments wrong in quiet ways: an amount in euros instead of cents, a key in the browser, an order marked paid on the return page alone. Each page hands your assistant the exact contract and a prompt to start from. ## Related - [Accept a payment](/online-payments): the contract every assistant has to follow - [Integration examples](/integration-examples): one runnable server in C#, TypeScript, Python and PHP --- # Build an app with a vibe-coding platform (/build-with-ai/vibe-coding) > Paste one prompt into Lovable, Bolt, v0 or a similar platform and get a shop that creates, opens and confirms MPS payments from its server side. Describe your shop to Lovable, Bolt, v0 or Replit and let it build the payments too. Start from the prompt below: it points the platform at this page, which holds everything it has to follow. Then test every case on the list at the end. - A test key (`mps_test_…`) and its signing secret, shown once together under **Online › API keys** on the MPS platform - A Lovable, Bolt, v0 or Replit project with a server side: Edge Functions, server functions or route handlers > **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. ## Paste this prompt [#prompt] Replace the bracketed part with your shop, and paste it as your first message: ```text Build [a shop for my three candles, with a product page, a cart and a checkout]. Take payments with MPS. Read https://docs.mps-emi.com/llms.mdx/docs/build-with-ai/vibe-coding/content.md and follow it exactly; do not invent endpoints, fields or headers that are not documented there. - Call MPS only from the server side this project has (Supabase Edge Functions in Lovable, server functions or route handlers elsewhere). Keep MPS_API_KEY and MPS_WEBHOOK_SECRET as server secrets; they never appear in browser code. - Compute the total in cents on the server, save the order, then create the payment with an Idempotency-Key stored with the order. - Open the checkout with the openCheckout helper from that page: never in a frame. - Mark an order paid only after reading the payment on the server: state executed, the full amount, EUR and the order's reference, with an update that only succeeds once. - Add the webhook route that verifies the signature on the raw body before it answers. - Build the return URLs from the origin of the request that creates the payment, as that page shows. Do not ask me for the app's address: it is different in the preview, the published app and a custom domain, and the code reads it. Ask me for the API key and the signing secret as secrets when you need them, and for nothing else. ``` The platform asks for your test key and its signing secret; paste them into the platform's settings for server values, never into the chat. Then work through [Test every case](#done-means) in the preview and in the published app. ## What the platform has to follow [#requirements] 1. **Server side only.** The API key, the signing secret and every call to MPS live on the server. The gateway answers no cross-origin (CORS) requests, so a call from the page fails anyway. 2. **Price and order on the server.** Compute the total in cents on the server from your own product list, save the order, then create the payment with an `Idempotency-Key` generated once per checkout attempt and stored with the order. A retry of the same create sends the same key and body. 3. **Never show the checkout in a frame.** It refuses to load in one (`frame-ancestors 'none'`), and an app builder's preview *is* one: opened in place, it is a gray screen. Use the [helper below](#open-the-checkout): it navigates the page when the app stands alone, opens a new tab from the click when it is framed, and always shows a link, a copy button and the address. 4. **Paid means read and checked on the server.** The return URL proves nothing. Read the payment and mark the order paid only when `state` is `executed`, `amount` equals the order total, `currency` is `EUR` and `reference` is the order's — with an update that only succeeds once. 5. **Signed webhook.** Verify the signature on the raw body, then settle exactly as the return page does. The same webhook can arrive twice. 6. **Done means tested.** See [Done means](#done-means). > **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. ### Use the server side your project has [#the-server-side-use-the-one-your-project-has] Look at the project first and use its server architecture; do not add another platform's. | Project | Create and read a payment | Webhook route (raw body) | Where the settings live | |---|---|---|---| | TanStack Start (current Lovable projects) | A server function (`createServerFn`) | A server route, `await request.text()` | Server environment variables — never `VITE_` | | Supabase Edge Functions (earlier Lovable projects, Bolt) | An Edge Function | An Edge Function with `verify_jwt = false` in `supabase/config.toml` (MPS sends no Supabase token) | Supabase's function settings (`supabase secrets set`), read with `Deno.env.get` | | Next.js (v0) | A route handler or server action | `app/api/…/route.ts`, `await request.text()` | Environment variables — never `NEXT_PUBLIC_` | | Express, Fastify, others | A route | See [Webhooks › raw body](/webhooks#validating-the-signature) | Environment variables | Two settings: `MPS_API_KEY` and `MPS_WEBHOOK_SECRET`, both shown once, together, when you generate a test key on the MPS platform under **Online › API keys**. There is no setting for the app's own address: the server reads it from the request that creates the payment, so the same code serves the builder's preview, the published app, a custom domain and local development. Every runtime above has `fetch` and Web Crypto (`crypto.subtle`), so the code below runs in all of them. Node's `crypto` and `Buffer` do not exist in Deno or a browser. ### Create, read and settle the payment Add these functions to your server side: ```ts const GATEWAY = "https://gateway.mps-emi.com"; // Your server's settings: process.env in Node, TanStack Start and Next.js; Deno.env.get in Supabase. const MPS_API_KEY = process.env.MPS_API_KEY!; const MPS_WEBHOOK_SECRET = process.env.MPS_WEBHOOK_SECRET!; // The app's own address, read from the request that creates the payment: the preview, the published // app, a custom domain and localhost all work without a setting. Behind the platform's proxy the // public host is in the forwarded headers; otherwise it is the request's own URL. // `request` is what the runtime hands you: getRequest() in a TanStack Start server function, the // handler's argument in Next.js, Supabase and Express. function appOrigin(request: Request): string { const url = new URL(request.url); const proto = request.headers.get("x-forwarded-proto")?.split(",")[0].trim() ?? url.protocol.replace(":", ""); const host = request.headers.get("x-forwarded-host")?.split(",")[0].trim() ?? url.host; const origin = `${proto}://${host}`; const local = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(origin); if (!origin.startsWith("https://") && !local) throw new Error(`Return URLs need https; got ${origin}`); return origin; } // Create: one Idempotency-Key per checkout attempt, stored with the order before the call. async function createPayment(request: Request, order: { id: string; totalCents: number; idempotencyKey: string }) { const origin = appOrigin(request); // The webhook endpoint is MPS's address for your server, not the shopper's return page. It has to be // a public https address, so it is left out on localhost: the return page still settles the order. // Supabase: the Edge Function's address, `${Deno.env.get("SUPABASE_URL")}/functions/v1/mps-webhook`. const callbackUrl = origin.startsWith("https://") ? `${origin}/api/mps-webhook` : undefined; const response = await fetch(`${GATEWAY}/api/payments/internet/create`, { method: "POST", headers: { Authorization: `Bearer ${MPS_API_KEY}`, "Content-Type": "application/json", "Idempotency-Key": order.idempotencyKey, }, body: JSON.stringify({ amount: order.totalCents, // integer cents: 1995 = EUR 19.95 reference: `order-${order.id.slice(0, 8)}`, // letters, digits, spaces and . _ : / # + -, at most 64 successUrl: `${origin}/return?order=${order.id}`, failureUrl: `${origin}/return?order=${order.id}`, callbackUrl, }), }); if (!response.ok) throw new Error(`MPS create answered ${response.status}`); // 5xx, network error or 409 idempotency_key_in_use: retry with the same key and body; 409 idempotency_key_expired: new key const { data } = await response.json(); return data as { paymentReference: string; checkoutUrl: string }; // store both with the order } // Read: the only proof of payment. async function readPayment(paymentReference: string) { const response = await fetch(`${GATEWAY}/api/payments/internet/${paymentReference}`, { headers: { Authorization: `Bearer ${MPS_API_KEY}` }, }); if (!response.ok) throw new Error(`MPS read answered ${response.status}`); return (await response.json()).data as { state: string; amount: number; currency: string; reference: string }; } // Settle: the return page and the webhook both call this. Paid only when everything matches. async function settleOrder(order: { id: string; status: string; totalCents: number; paymentReference: string }) { if (order.status !== "open") return order.status; const payment = await readPayment(order.paymentReference); const matches = payment.amount === order.totalCents && payment.currency === "EUR" && payment.reference === `order-${order.id.slice(0, 8)}`; if (payment.state === "executed" && matches) { await markPaidIfOpen(order.id); // UPDATE orders SET status = 'paid' WHERE id = $1 AND status = 'open' return "paid"; } return payment.state; // executed with a smaller amount, pending, failed, abandoned: see the table below } ``` ### Apply each state to the order [#what-each-state-means-for-the-order] The return page and the webhook both read the payment and apply this; call MPS only while the order is still open. | Read | Order | The shopper sees | |---|---|---| | `executed`, and amount, currency and reference match | `paid`, with an update that only matches an open order | Thank you | | `executed` with a smaller `amount` (a partial approval) | Not paid in full: do not ship; refund or settle it with the shopper — see [Payment lifecycle](/payment-lifecycle#executed) | Contact the shop | | `pending` | Open. On the return, read every 2 seconds for about 30 seconds | "We are confirming your payment", and **Back to checkout** with the stored `checkoutUrl`: a shopper who chose *Back to the shop* can still pay it | | `failed` (declined) or `abandoned` | Open. The next **Pay** creates a new payment with a **new** `Idempotency-Key` | Declined, try again | While an order has a `pending` payment, **Pay** opens its stored `checkoutUrl` again instead of creating a second payment. ### Open the checkout Copy this as it is. Call `openCheckout` from the Pay button's click handler, with nothing awaited before it; `createPayment` calls *your* server function. ```ts // checkout.ts: open the MPS checkout from the Pay button, in a standalone app and in a framed preview. export type CheckoutView = | { status: "creating" } | { status: "ready"; checkoutUrl: string } | { status: "error"; message: string }; export async function openCheckout( createPayment: () => Promise<{ checkoutUrl: string }>, show: (view: CheckoutView) => void, ): Promise { // An app builder's preview runs the app in an iframe, where the checkout refuses to load. const embedded = window.self !== window.top; // A browser opens a tab only during the click itself: reserve it now, before any await. const tab = embedded ? window.open("about:blank", "_blank") : null; show({ status: "creating" }); let checkoutUrl: string; try { ({ checkoutUrl } = await createPayment()); } catch { tab?.close(); show({ status: "error", message: "The payment could not be started. Please try again." }); return; } // Shown every time: some mobile hosts swallow a new tab without a trace. show({ status: "ready", checkoutUrl }); if (!embedded) window.location.assign(checkoutUrl); else if (tab) tab.location.href = checkoutUrl; } ``` Render the `ready` view as all three of a link, a copy button and the address: ```tsx import { useState } from "react"; export function CheckoutLink({ checkoutUrl }: { checkoutUrl: string }) { const [copyState, setCopyState] = useState<"idle" | "copied" | "blocked">("idle"); const copy = async () => { try { await navigator.clipboard.writeText(checkoutUrl); setCopyState("copied"); } catch { // The clipboard can be blocked inside a frame: say so, and point at the selectable address. setCopyState("blocked"); } }; return (
Continue to checkout e.currentTarget.select()} /> {copyState === "blocked" &&

Copying is blocked here. Select the address above and copy it.

}
); } ```
### Add the webhook route [#the-webhook-route] The [basic handler](/webhooks) fits an app builder, which has no background worker: verify, settle, then answer. ```ts async function isValidSignature(secret: string, timestamp: string, header: string, rawBody: string) { if (!/^\d{1,12}$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; // Unix seconds, five-minute window const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${timestamp}.${rawBody}`)); const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join(""); return header.split(",").map((part) => part.trim()).filter((part) => part.startsWith("v1=")).some((part) => { const given = part.slice(3); let diff = given.length ^ expected.length; // constant time: no early exit for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i); return diff === 0; }); } export async function handleMpsWebhook(request: Request): Promise { const rawBody = await request.text(); // before any JSON parsing const valid = await isValidSignature( MPS_WEBHOOK_SECRET, request.headers.get("X-Mps-Timestamp") ?? "", request.headers.get("X-Mps-Signature") ?? "", rawBody, ); if (!valid) return new Response(null, { status: 401 }); const event = JSON.parse(rawBody); if (event.eventType !== "payment.received") return new Response(null, { status: 200 }); // refunds and future events const order = await findOrderByPaymentReference(event.paymentReference); if (!order) return new Response(null, { status: 200 }); // not this app's payment: log it, do not retry try { await settleOrder(order); // reads the payment and applies the table above; settles once return new Response(null, { status: 200 }); } catch { return new Response(null, { status: 500 }); // MPS retries } } ``` ### Test every case [#done-means] Opening the checkout is not a payment test. With a [test key](/online-payments#test-mode), every one of these has to hold: - [ ] **Pay** opens the checkout in the published app *and* in the builder's preview. - [ ] After paying, the shopper lands on the return page of the app they started from: the preview, the published app or the custom domain, never a hardcoded address. - [ ] With the new tab blocked, the link, the copy button and the address still let the shopper pay. - [ ] `4111 1111 1111 1111`: the return page says paid, the webhook arrives and verifies, the order is paid once. - [ ] `4000 0000 0000 0002` (declined): the order stays open, and **Pay** again creates a new payment. - [ ] `4000 0000 0000 0010` (stays pending): the return page says it is confirming; nothing is shipped. - [ ] *Back to the shop* on the checkout: the failure URL, still `pending`, and **Back to checkout** pays it. - [ ] The same create sent twice with the same `Idempotency-Key` gives one payment. - [ ] The same webhook delivered twice settles the order once; a wrong signature answers `401` and changes nothing. - [ ] `mps_test_` appears nowhere in the code the browser downloads.
## Response `createPayment` returns the create's `data`, and `readPayment` the read's: | Field | Type | Required | Description | |---|---|---|---| | `paymentReference` | string | Yes | Create and read. The MPS reference of the payment, `test-…` in test mode. Store it with the order. | | `checkoutUrl` | string | Yes | Create. The checkout address. Open it exactly as returned, with `openCheckout`. | | `state` | string | Yes | Read. `pending`, `executed`, `failed` or `abandoned`. See [Payment lifecycle](/payment-lifecycle). | | `amount` | integer | Yes | Read. The amount in euro cents. | | `currency` | string | Yes | Read. `EUR`. | | `reference` | string | Yes | Read. Your order reference, as you sent it, or `null` if you sent none. | ## Errors | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | A field is invalid, for example an `amount` of zero, a `reference` with other characters, or a `callbackUrl` that is not a public `https://` address. | Fix the field the body names. Do not retry unchanged. See [Validation errors](/errors-and-rate-limits#validation-errors). | | `401` | — | No API key, or a wrong or revoked one. | Check `MPS_API_KEY` in the server settings. Do not retry. See [Authentication](/authentication). | | `403` | — | The key lacks `internet:create` or `internet:read`, or the merchant has no shop name registered yet. | Check the key's scopes, or contact MPS. See [Status codes](/errors-and-rate-limits#status-codes). | | `404` | — | The read found no such payment for the merchant the key acts for. | Check the `paymentReference` stored with the order. | | `409` | `idempotency_key_in_use` | A create with the same `Idempotency-Key` is still running. | Retry after a second with the same key and body. See [Conflicts](/errors-and-rate-limits#conflicts). | | `409` | `idempotency_key_expired` | The payment this key made can no longer be returned. | Create a new payment with a new key. | | `429` | — | The key's 100 requests a minute, shared by every endpoint. | Wait `Retry-After` seconds, then retry. See [Rate limits](/errors-and-rate-limits#rate-limits). | | `5xx` | — | A problem on the MPS side. | Retry the create with the same key and body, and the read with backoff. See [Retry policy](/errors-and-rate-limits#retry-policy). | ## Related - [Build with an AI coding assistant](/build-with-ai/coding-assistant): the same integration in your own code editor - [Payment lifecycle](/payment-lifecycle): every state and what to do with it - [Webhooks](/webhooks): the basic handler, retries and duplicates - [Integration examples](/integration-examples): one runnable server in C#, TypeScript, Python and PHP --- # Build with an AI coding assistant (/build-with-ai/coding-assistant) > Point Cursor, Claude Code, Copilot or Codex at the MPS documentation and a ready-made prompt, then check what it wrote before you go live. A coding assistant in your own project writes the integration with you: the backend calls, the return page and the webhook route. Give it the exact contract and the prompt below, and check its work against the mistakes assistants make. - A test key (`mps_test_…`) and its signing secret from **Online › API keys** on the MPS platform - Cursor, Claude Code, Copilot, Codex or another assistant that edits your project > **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. ### Give it the documentation An assistant that fetches URLs only needs [`/llms.txt`](/llms.txt): it follows the links to the pages it needs. One that cannot fetch needs [`/llms-full.txt`](/llms-full.txt) attached or added to the project. For a typed client, give it [`/openapi.json`](/openapi.json) as well. See [Ask a chat assistant](/build-with-ai/chat-assistant) for every file. ### Paste this prompt [#prompt] Replace the bracketed parts: ```text You are helping me integrate the MPS payment gateway. Read the MPS documentation at https://docs.mps-emi.com/llms.txt and follow it exactly; do not invent endpoints, fields or headers that are not documented there. My stack: [e.g. Node.js 22 + Express backend]. I have these scopes: [internet:create internet:read]. My API key covers [one wallet | several merchant wallets]. Build: 1. A backend module that sends my API key in the Authorization header as a Bearer key on every call, keeping the key server-side. 2. A checkout endpoint that stores the order with a new Idempotency-Key, creates an online payment sending that key (retrying a failed create with the same key and body), stores paymentReference with the order, and redirects the shopper to checkoutUrl. 3. A return handler that reads the payment on the backend and marks the order paid only on executed with the full amount, with an update that only succeeds once. 4. A webhook receiver that verifies the signature and timestamp, stores the webhook in a database inbox keyed on X-Mps-Delivery-Id, and only then answers 2xx — no work started after answering. A worker processes the inbox: reads the payment, checks state, amount, currency and reference against the order, settles it once, retries temporary failures with backoff and records permanent ones. Include error handling for every status code in the docs. ``` ### Check what it wrote Go through the [Errors](#errors) below: each is a mistake assistants make often. ### Test every case Run the cases in [Test every case](/build-with-ai/vibe-coding#done-means) with the [test cards](/online-payments#test-mode) before you switch to a live key. ## Errors | What the assistant did | What happens | Fix | |---|---|---| | Added an OAuth exchange | An API key is sent as it is on every call; there is nothing to exchange it for. | Send the key in `Authorization` on every call. See [Authentication](/authentication). | | Put the API key in a browser or an app | Anyone can read it and create payments for you. | Keep it on your backend only. | | Called the API from the page | The gateway allows no CORS: the call fails. | Call it from a server function. | | Opened the checkout in a frame, or a tab after an `await` | A gray screen, or a blocked popup. | Open the tab in the click handler, then point it at `checkoutUrl`. See [Open the checkout](/build-with-ai/vibe-coding#open-the-checkout). | | Sent a merchant header with a merchant key | A test or merchant key acts for its own wallet. | Only a partner key names the merchant, with `x-wallet-number`. | | Sent amounts in euros | `19.95` is refused, `19` asks for 19 cents. | Every amount is an integer number of cents. | | Invented a discount field | There are no discount fields: a payment takes one price. | Send the final price in `amount`. | | Retried a create without an `Idempotency-Key` | A retry opens a second payment. | Generate a key once per checkout attempt and retry with the same key and body. | | Trusted the success URL | Anyone can open it: an order is marked paid that was not. | Confirm with the read endpoint first. | | Answered the webhook, then worked in the background | Work after the `2xx` is lost if the process stops, and the webhook is not sent again. | Store it first, then answer. See [Webhooks](/webhooks). | ## Related - [Build an app with a vibe-coding platform](/build-with-ai/vibe-coding): the same integration in Lovable, Bolt or v0 - [Integration examples](/integration-examples): one runnable server in C#, TypeScript, Python and PHP - [Payment lifecycle](/payment-lifecycle): every state and what to do with it --- # Ask a chat assistant (/build-with-ai/chat-assistant) > Give ChatGPT, Claude, Gemini or your own agent one MPS page or the whole documentation as Markdown, so its answers follow the real contract. Every page on this site is also published as plain Markdown, so a chat assistant answers from the exact contract instead of guessing. The site is public: an assistant that fetches URLs can be handed [`/llms.txt`](/llms.txt) and follow it to whichever page it needs. ## The files | URL | What it is | Use it when | |---|---|---| | [`/llms.txt`](/llms.txt) | An index following the [llms.txt](https://llmstxt.org) convention: a summary, the key facts, and a link to the Markdown of every page | **Start here.** An agent that fetches URLs and follows the links it needs | | [`/llms-full.txt`](/llms-full.txt) | Every page concatenated into one file | Loading the whole documentation at once, or adding it to a project or knowledge base | | `/llms.mdx/docs//content.md` | One page as Markdown — e.g. [`/llms.mdx/docs/authentication/content.md`](/llms.mdx/docs/authentication/content.md) | Giving an assistant just the part you are working on | | [`/openapi.json`](/openapi.json) | The OpenAPI 3.0 document of every public endpoint — the one the [API reference](/api-reference) is built from | Generating a typed client, or giving a coding agent the exact request and response schemas | Every page names these files at its foot, and in its HTML head as `` (the page's own Markdown, `llms.txt` and `/openapi.json`), so an agent that is handed a page's URL finds them without being told. Each page also has **Copy Markdown** and **Open** (in ChatGPT, Claude, Cursor or Codex) buttons under its title: the first puts the page on your clipboard, the second starts a conversation about it. ## Related - [Build with an AI coding assistant](/build-with-ai/coding-assistant): a prompt for building the integration - [Build an app with a vibe-coding platform](/build-with-ai/vibe-coding): a prompt for Lovable, Bolt or v0 - [Accept a payment](/online-payments): the contract every answer has to follow --- # Take your first online payment (/quickstart) > Create a test payment from a terminal, pay it on the MPS checkout and read it back in five minutes, with one test key. The developer quickstart. Create a payment with two API calls, pay it on the MPS checkout with a test card, and read it back. In test mode nothing is charged. Not a developer? A [payment link](/payment-links) or a [shop plugin](/connect-your-webshop) takes payments without code. [Start here](/) to choose. ## Five minutes, in a terminal - A test key (`mps_test_…`) from **Online › API keys** on the MPS platform. No test key yet? The merchant creates one; see [online payment setup](/set-up-your-account). - A terminal with `curl` and `uuidgen`, or your language's runtime, and a browser > **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. ### Set your key ```bash export MPS_API_KEY="mps_test_…" ``` Every call sends it as `Authorization: Bearer`. You do not exchange it for anything first. ### Create a payment Amounts are integers in **euro cents**. The `Idempotency-Key` makes a retry safe: send the same key again and you get the same payment back, never a second one. Pick your language. Each example runs as it is with the key from the step above; the choice is kept for the page. ```bash tab="curl" tab-group="lang" IDEMPOTENCY_KEY=$(uuidgen) # one per checkout attempt; reuse it to retry this create curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/internet/create" \ -H "Authorization: Bearer $MPS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{ "amount": 1995, "reference": "order-42", "successUrl": "https://example.com/paid", "failureUrl": "https://example.com/failed" }' ``` ```csharp tab="C#" // dotnet new console, replace Program.cs, then: dotnet run using System.Net.Http.Json; using System.Text.Json; using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") }; mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY")); using var create = new HttpRequestMessage(HttpMethod.Post, "create") { Content = JsonContent.Create(new { amount = 1995, // cents reference = "order-42", successUrl = "https://example.com/paid", failureUrl = "https://example.com/failed", }), }; create.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); // one per checkout attempt using var response = await mps.SendAsync(create); if (!response.IsSuccessStatusCode) { // 400 names the field, 401 and 403 the key: see Errors below. Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); return 1; } var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); Console.WriteLine($"paymentReference: {data.GetProperty("paymentReference")}"); // keep it for the read Console.WriteLine($"checkoutUrl: {data.GetProperty("checkoutUrl")}"); // open it in a browser return 0; ``` ```ts tab="TypeScript" // node create.ts (Node 23.6 or later) import { randomUUID } from 'node:crypto'; const response = await fetch('https://gateway.mps-emi.com/api/payments/internet/create', { method: 'POST', headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID(), // one per checkout attempt }, body: JSON.stringify({ amount: 1995, // cents reference: 'order-42', successUrl: 'https://example.com/paid', failureUrl: 'https://example.com/failed', }), }); if (!response.ok) { // 400 names the field, 401 and 403 the key: see Errors below. throw new Error(`MPS answered ${response.status}: ${await response.text()}`); } const { data } = (await response.json()) as { data: { paymentReference: string; checkoutUrl: string } }; console.log('paymentReference:', data.paymentReference); // keep it for the read console.log('checkoutUrl:', data.checkoutUrl); // open it in a browser ``` ```python tab="Python" # pip install requests, then: python create.py import os import sys import uuid import requests response = requests.post( "https://gateway.mps-emi.com/api/payments/internet/create", headers={ "Authorization": f"Bearer {os.environ['MPS_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), # one per checkout attempt }, json={ "amount": 1995, # cents "reference": "order-42", "successUrl": "https://example.com/paid", "failureUrl": "https://example.com/failed", }, timeout=10, ) if response.status_code != 200: # 400 names the field, 401 and 403 the key: see Errors below. sys.exit(f"MPS answered {response.status_code}: {response.text}") data = response.json()["data"] print("paymentReference:", data["paymentReference"]) # keep it for the read print("checkoutUrl:", data["checkoutUrl"]) # open it in a browser ``` ```php tab="PHP" true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('MPS_API_KEY'), 'Content-Type: application/json', 'Idempotency-Key: ' . bin2hex(random_bytes(16)), // one per checkout attempt ], CURLOPT_POSTFIELDS => json_encode([ 'amount' => 1995, // cents 'reference' => 'order-42', 'successUrl' => 'https://example.com/paid', 'failureUrl' => 'https://example.com/failed', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ]); $body = (string) curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { // 400 names the field, 401 and 403 the key: see Errors below. fwrite(STDERR, "MPS answered $status: $body\n"); exit(1); } $data = json_decode($body, true)['data']; echo "paymentReference: {$data['paymentReference']}\n"; // keep it for the read echo "checkoutUrl: {$data['checkoutUrl']}\n"; // open it in a browser ``` ```json title="200 OK" { "data": { "paymentReference": "test-…", "checkoutUrl": "https://pay.mps-emi.com/…" } } ``` ### Pay on the checkout Open `checkoutUrl` in a browser and pay with card `4111 1111 1111 1111`, any future expiry date and any security code. The checkout sends you on to your `successUrl`. > **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. ### Read it back Put the `paymentReference` from the create in `PAYMENT_REFERENCE`, then read the payment. ```bash tab="curl" tab-group="lang" export PAYMENT_REFERENCE="test-…" curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```csharp tab="C#" // dotnet new console, replace Program.cs, then: PAYMENT_REFERENCE=test-… dotnet run using System.Net.Http.Json; using System.Text.Json; using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") }; mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY")); var reference = Environment.GetEnvironmentVariable("PAYMENT_REFERENCE")!; using var response = await mps.GetAsync(Uri.EscapeDataString(reference)); if (!response.IsSuccessStatusCode) { // 404: no such payment for this key. See Errors below. Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); return 1; } var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); Console.WriteLine($"state: {data.GetProperty("state")}, amount: {data.GetProperty("amount")}"); return 0; ``` ```ts tab="TypeScript" // PAYMENT_REFERENCE=test-… node read.ts (Node 23.6 or later) const reference = process.env.PAYMENT_REFERENCE!; const response = await fetch( `https://gateway.mps-emi.com/api/payments/internet/${encodeURIComponent(reference)}`, { headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}` } }, ); if (!response.ok) { // 404: no such payment for this key. See Errors below. throw new Error(`MPS answered ${response.status}: ${await response.text()}`); } const { data } = (await response.json()) as { data: { state: string; amount: number } }; console.log(`state: ${data.state}, amount: ${data.amount}`); ``` ```python tab="Python" # PAYMENT_REFERENCE=test-… python read.py import os import sys from urllib.parse import quote import requests reference = os.environ["PAYMENT_REFERENCE"] response = requests.get( f"https://gateway.mps-emi.com/api/payments/internet/{quote(reference, safe='')}", headers={"Authorization": f"Bearer {os.environ['MPS_API_KEY']}"}, timeout=10, ) if response.status_code != 200: # 404: no such payment for this key. See Errors below. sys.exit(f"MPS answered {response.status_code}: {response.text}") data = response.json()["data"] print(f"state: {data['state']}, amount: {data['amount']}") ``` ```php tab="PHP" ['Authorization: Bearer ' . getenv('MPS_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ]); $body = (string) curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { // 404: no such payment for this key. See Errors below. fwrite(STDERR, "MPS answered $status: $body\n"); exit(1); } $data = json_decode($body, true)['data']; echo "state: {$data['state']}, amount: {$data['amount']}\n"; ``` ```json title="200 OK" { "data": { "paymentReference": "test-…", "state": "executed", "amount": 1995, "currency": "EUR", "reference": "order-42" } } ``` `executed` means paid. That is your first payment. Cards that decline or stay pending are under [Test mode](/online-payments#test-mode). ## Response The create answers `200` with: | Field | Type | Required | Description | |---|---|---|---| | `paymentReference` | string | Yes | The MPS reference of the payment. `test-…` in test mode. Store it with the order. | | `checkoutUrl` | string | Yes | The checkout address. Open it exactly as returned. | The read answers `200` with: | Field | Type | Required | Description | |---|---|---|---| | `paymentReference` | string | Yes | The payment you read. | | `state` | string | Yes | `pending`, `executed`, `failed` or `abandoned`. See [Payment lifecycle](/payment-lifecycle). | | `amount` | integer | Yes | The amount in euro cents. | | `currency` | string | Yes | `EUR`. | | `amountRefunded` | integer | Yes | What has been refunded so far, in euro cents. See [Refunds](/refunds). | | `amountRemaining` | integer | Yes | What can still be refunded, in euro cents. | | `reference` | string | Yes | Your order reference, as you sent it, or `null` if you sent none. | ## Errors | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | A field is invalid, for example an `amount` of zero or a `successUrl` that is not `https://`. | Fix the field the body names. Do not retry unchanged. See [Validation errors](/errors-and-rate-limits#validation-errors). | | `401` | — | No API key, or a wrong or revoked one. | Check `MPS_API_KEY`. Do not retry. See [Authentication](/authentication). | | `403` | — | The key lacks the scope (`internet:create` or `internet:read`), or the merchant has no shop name registered yet. | Check the key's scopes, or contact MPS. See [Status codes](/errors-and-rate-limits#status-codes). | | `404` | — | The read found no such payment for the merchant the key acts for. | Check the `paymentReference` you stored. | | `409` | `idempotency_key_in_use` | A create with the same `Idempotency-Key` is still running. | Retry after a second with the same key and body. See [Conflicts](/errors-and-rate-limits#conflicts). | | `409` | `idempotency_key_expired` | The payment this key made can no longer be returned. | Create a new payment with a new key. | | `429` | — | The key's 100 requests a minute, shared by every endpoint. | Wait `Retry-After` seconds, then retry. See [Rate limits](/errors-and-rate-limits#rate-limits). | ## Then, in your backend The same calls, on your server. The API key never goes to a browser or an app. 1. **Create** the payment, store `paymentReference` with the order, and redirect the shopper to `checkoutUrl`. Pass a `callbackUrl` to receive a webhook when it is paid. 2. **Confirm** before you ship. In your [webhook](/webhooks) handler, verify the signature and timestamp, read the payment, and check its `state`, `amount`, `currency` and `reference` against the order. Mark the order paid with an update that only succeeds once, and only then answer `2xx`. On a failure answer `5xx` and MPS retries. This works as long as the handler finishes within 10 seconds. [The basic handler](/webhooks#the-simple-handler-process-then-answer) shows it, and [the production pattern](/webhooks#the-production-pattern-store-answer-process) covers the rest. 3. **Handle every state**: `executed` (check the amount), `failed`, `abandoned` after 24 hours, and `pending` until then. See [Payment lifecycle](/payment-lifecycle). [Integration examples](/integration-examples) has all of it as one runnable server in C#, TypeScript, Python and PHP. Partner key? Add `x-wallet-number` with the merchant's wallet. See [Choosing the merchant](/authentication#choosing-the-merchant). ## Related - [Payment lifecycle](/payment-lifecycle): what each state means and what to do with it - [Webhooks](/webhooks): receive and verify webhooks - [Integration examples](/integration-examples): one runnable server in four languages - [Production checklist](/production-checklist): the checks before you switch to a live key - [Switch to live payments](/take-live-payments#your-own-integration): what the merchant needs before a live key works --- # Accept a payment (/online-payments) > Create an online payment, send the shopper to the MPS checkout, and read the outcome when they come back. You create the payment on your backend, send the shopper to the returned `checkoutUrl`, and MPS collects the payment. The shopper comes back to your success or failure URL, and you read the payment to confirm the outcome. The checkout leads with a QR code for **ANNA**, MPS's pay-by-bank app: the shopper scans it, chooses their bank and confirms in their banking app. **Continue with card** opens the card form instead. Either way you get the same states, the same webhook and the same read. In test mode ANNA simulates the bank (see [Test mode](#test-mode)). MPS collects the card details on its own checkout, so card data never touches your systems. > **Server only.** The API cannot be called from a browser. The gateway answers no cross-origin (CORS) requests, and the API key must never reach a browser. Call it from your server. > **Warning.** Landing on successUrl is not proof of payment. Verify the webhook signature, read the payment, and check its state, amount, currency, and reference before marking an order paid. >Backend: Check out Backend->>MPS: Create the payment MPS-->>Backend: paymentReference, checkoutUrl Backend-->>Shopper: Redirect to checkoutUrl Shopper->>MPS: Pay on the checkout MPS-->>Shopper: Redirect to successUrl or failureUrl MPS-)Backend: Webhook payment.received, once paid Backend->>MPS: Read the payment MPS-->>Backend: state, amount Backend-->>Shopper: Confirm the order `} /> The return and the webhook can arrive in either order. [Payment lifecycle](/payment-lifecycle) draws the detail. - A test key (`mps_test_…`) from **Online › API keys** on the MPS platform. See [Authentication](/authentication). - The scopes `internet:create` to create and `internet:read` to read. Every key holds them. - A server that can make outbound HTTPS calls. Every call carries your API key as `Authorization: Bearer`. - With a partner key: the merchant's wallet, sent as `x-wallet-number` on every call, the read included. ### Create a payment Send the amount in euro cents and your two return URLs. Add an `Idempotency-Key`, one per checkout attempt, so a retry never opens a second payment. Pick your language; each example runs as it is with your test key in `MPS_API_KEY`, and the choice is kept for the whole page. ```http tab="HTTP" tab-group="lang" POST https://gateway.mps-emi.com/api/payments/internet/create Authorization: Bearer mps_test_… Content-Type: application/json Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91 { "amount": 1995, "reference": "order-1234", "successUrl": "https://shop.example.com/orders/1234/paid", "failureUrl": "https://shop.example.com/orders/1234/failed" } ``` ```bash tab="curl" # Prerequisite: export MPS_API_KEY=mps_test_… curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/internet/create" \ -H "Authorization: Bearer $MPS_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{ "amount": 1995, "reference": "order-1234", "successUrl": "https://shop.example.com/orders/1234/paid", "failureUrl": "https://shop.example.com/orders/1234/failed" }' ``` ```csharp tab="C#" // dotnet new console, replace Program.cs, then: MPS_API_KEY=mps_test_… dotnet run using System.Net.Http.Json; using System.Text.Json; using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") }; mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY")); using var create = new HttpRequestMessage(HttpMethod.Post, "create") { Content = JsonContent.Create(new { amount = 1995, // cents reference = "order-1234", successUrl = "https://shop.example.com/orders/1234/paid", failureUrl = "https://shop.example.com/orders/1234/failed", }), }; create.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); // one per checkout attempt using var response = await mps.SendAsync(create); if (!response.IsSuccessStatusCode) { // 400 names the field, 401 and 403 the key: see Errors below. Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); return 1; } var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); Console.WriteLine($"paymentReference: {data.GetProperty("paymentReference")}"); // store it with the order Console.WriteLine($"checkoutUrl: {data.GetProperty("checkoutUrl")}"); // send the shopper here return 0; ``` ```ts tab="TypeScript" // node create.ts (Node 23.6 or later), with MPS_API_KEY=mps_test_… in the environment import { randomUUID } from 'node:crypto'; const response = await fetch('https://gateway.mps-emi.com/api/payments/internet/create', { method: 'POST', headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}`, 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID(), // one per checkout attempt }, body: JSON.stringify({ amount: 1995, // cents reference: 'order-1234', successUrl: 'https://shop.example.com/orders/1234/paid', failureUrl: 'https://shop.example.com/orders/1234/failed', }), }); if (!response.ok) { // 400 names the field, 401 and 403 the key: see Errors below. throw new Error(`MPS answered ${response.status}: ${await response.text()}`); } const { data } = (await response.json()) as { data: { paymentReference: string; checkoutUrl: string } }; console.log('paymentReference:', data.paymentReference); // store it with the order console.log('checkoutUrl:', data.checkoutUrl); // send the shopper here ``` ```python tab="Python" # pip install requests, then: MPS_API_KEY=mps_test_… python create.py import os import sys import uuid import requests response = requests.post( "https://gateway.mps-emi.com/api/payments/internet/create", headers={ "Authorization": f"Bearer {os.environ['MPS_API_KEY']}", "Idempotency-Key": str(uuid.uuid4()), # one per checkout attempt }, json={ "amount": 1995, # cents "reference": "order-1234", "successUrl": "https://shop.example.com/orders/1234/paid", "failureUrl": "https://shop.example.com/orders/1234/failed", }, timeout=10, ) if response.status_code != 200: # 400 names the field, 401 and 403 the key: see Errors below. sys.exit(f"MPS answered {response.status_code}: {response.text}") data = response.json()["data"] print("paymentReference:", data["paymentReference"]) # store it with the order print("checkoutUrl:", data["checkoutUrl"]) # send the shopper here ``` ```php tab="PHP" true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('MPS_API_KEY'), 'Content-Type: application/json', 'Idempotency-Key: ' . bin2hex(random_bytes(16)), // one per checkout attempt ], CURLOPT_POSTFIELDS => json_encode([ 'amount' => 1995, // cents 'reference' => 'order-1234', 'successUrl' => 'https://shop.example.com/orders/1234/paid', 'failureUrl' => 'https://shop.example.com/orders/1234/failed', ]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ]); $body = (string) curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { // 400 names the field, 401 and 403 the key: see Errors below. fwrite(STDERR, "MPS answered $status: $body\n"); exit(1); } $data = json_decode($body, true)['data']; echo "paymentReference: {$data['paymentReference']}\n"; // store it with the order echo "checkoutUrl: {$data['checkoutUrl']}\n"; // send the shopper here ``` The gateway answers `200` with a `paymentReference` and a `checkoutUrl`. The fields are in [Request body](#request-body) and [Response](#response). Add a `callbackUrl` to be told when the payment is received: see [Webhooks](#webhooks). ### Store the payment reference Store `paymentReference` with your order **before** you redirect. It is the only key the read accepts, and nothing is appended to your return URLs to tell you which payment came back. ### Send the shopper to the checkout Redirect the shopper's browser to `checkoutUrl`: an HTTP `303` from your backend, or `window.location.assign`. When they finish, they land on your `successUrl` or `failureUrl`. The checkout refuses to load inside an iframe (`frame-ancestors 'none'`). Redirect the top-level window, with `window.top.location.href = checkoutUrl` from inside a frame, or open it in a new tab. This applies to embedded previews, widgets and site builders that render your page in a frame, too. Open a new tab **in the click handler, before any `await`**. A browser allows `window.open` only during the click itself, so opening it after creating the payment is blocked, silently in some mobile app shells. Open `about:blank` first and point it at `checkoutUrl` once you have it. If the tab was blocked anyway, show `checkoutUrl` as a link the shopper can click. ### Read the outcome When the shopper comes back, or when the webhook arrives, read the payment on your backend. The examples take the `paymentReference` from `PAYMENT_REFERENCE`. ```http tab="HTTP" tab-group="lang" GET https://gateway.mps-emi.com/api/payments/internet/{paymentReference} Authorization: Bearer mps_test_… ``` ```bash tab="curl" # Prerequisite: export MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```csharp tab="C#" // dotnet new console, replace Program.cs, then: MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… dotnet run using System.Net.Http.Json; using System.Text.Json; using var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") }; mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY")); var reference = Environment.GetEnvironmentVariable("PAYMENT_REFERENCE")!; // as stored with the order using var response = await mps.GetAsync(Uri.EscapeDataString(reference)); if (!response.IsSuccessStatusCode) { // 404: no such payment for this key. See Errors below. Console.Error.WriteLine($"MPS answered {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}"); return 1; } var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); var paid = data.GetProperty("state").GetString() == "executed" && data.GetProperty("amount").GetInt64() == 1995; Console.WriteLine(paid ? "Paid" : $"Not paid: {data.GetProperty("state")}"); return 0; ``` ```ts tab="TypeScript" // node read.ts (Node 23.6 or later), with MPS_API_KEY and PAYMENT_REFERENCE in the environment const reference = process.env.PAYMENT_REFERENCE!; // as stored with the order const response = await fetch( `https://gateway.mps-emi.com/api/payments/internet/${encodeURIComponent(reference)}`, { headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}` } }, ); if (!response.ok) { // 404: no such payment for this key. See Errors below. throw new Error(`MPS answered ${response.status}: ${await response.text()}`); } const { data } = (await response.json()) as { data: { state: string; amount: number } }; const paid = data.state === 'executed' && data.amount === 1995; console.log(paid ? 'Paid' : `Not paid: ${data.state}`); ``` ```python tab="Python" # pip install requests, then: MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… python read.py import os import sys from urllib.parse import quote import requests reference = os.environ["PAYMENT_REFERENCE"] # as stored with the order response = requests.get( f"https://gateway.mps-emi.com/api/payments/internet/{quote(reference, safe='')}", headers={"Authorization": f"Bearer {os.environ['MPS_API_KEY']}"}, timeout=10, ) if response.status_code != 200: # 404: no such payment for this key. See Errors below. sys.exit(f"MPS answered {response.status_code}: {response.text}") data = response.json()["data"] paid = data["state"] == "executed" and data["amount"] == 1995 print("Paid" if paid else f"Not paid: {data['state']}") ``` ```php tab="PHP" ['Authorization: Bearer ' . getenv('MPS_API_KEY')], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, ]); $body = (string) curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { // 404: no such payment for this key. See Errors below. fwrite(STDERR, "MPS answered $status: $body\n"); exit(1); } $data = json_decode($body, true)['data']; $paid = $data['state'] === 'executed' && $data['amount'] === 1995; echo $paid ? "Paid\n" : "Not paid: {$data['state']}\n"; ``` The gateway answers `200` with the payment's `state` and `amount`. Fulfil the order only when `state` is `executed` and `amount` equals the order total. See [Coming back](#coming-back) for what to do while it is still `pending`. ## Request body | Field | Type | Required | Description | |---|---|---|---| | `amount` | integer | Yes | Amount to collect, in cents, as a JSON number. `1995` = EUR 19.95. At least `1`, at most `5000000` (EUR 50,000). A decimal (`19.95`) or a string (`"1995"`) is refused with `400` naming `amount`. | | `reference` | string | No | Your own order reference, shown to the shopper and echoed back. At most 64 characters: letters `A-Z`, digits, spaces and `. _ : / # + -`. Never required to be unique, never a lookup key. | | `successUrl` | string | Yes | Absolute HTTPS URL the shopper returns to after a successful payment. `http://` only on `localhost`, for local development. | | `failureUrl` | string | Yes | Absolute HTTPS URL the shopper returns to after a failed or cancelled payment. `http://` only on `localhost`. | | `cancelUrl` | string | No | Absolute HTTPS URL the shopper goes to when they choose **Go back** on the checkout instead of paying, such as your basket. Without it, **Go back** leads to `failureUrl`. `http://` only on `localhost`. | | `callbackUrl` | string | No | HTTPS URL MPS posts this payment's webhooks to, server to server: `payment.received` once the payment is received, and the outcome of each of its refunds. At most 2048 characters. See [Webhooks](/webhooks). | | `locale` | string | No | Language the checkout opens in: `en`, `nl` or `fr`. A language tag with a region, such as `nl-BE`, is accepted and used as its language (`nl`). Without it, the checkout follows the language of the shopper's browser, and English when the browser asks for none of these. Any other value is refused with `400` naming `locale`. | The currency is EUR. Every return URL must be `https://`, except `http://` on `localhost`. Pass `locale` when you know the shopper's language, such as the language of your shop or of the order. The checkout then opens in that language whatever the shopper's browser asks for. ## Response ### Create ```json title="200 OK" { "data": { "paymentReference": "test-00000000-0000-4000-8000-000000000001", "checkoutUrl": "https://pay.mps-emi.com/…" } } ``` | Field | Type | Required | Description | |---|---|---|---| | `paymentReference` | string | Yes | The MPS payment reference. The only key the read endpoint accepts: store it against your order **before** you redirect. | | `checkoutUrl` | string | Yes | The checkout to send the shopper to. | Anyone holding `checkoutUrl` can pay this payment. Redirect the shopper to it. Do not log it, e-mail it to anyone else, or put it where it can leak. ### Read ```json title="200 OK" { "data": { "paymentReference": "test-00000000-0000-4000-8000-000000000001", "state": "executed", "amount": 1995, "currency": "EUR", "amountRefunded": 0, "amountRemaining": 1995, "reference": "order-1234" } } ``` | Field | Type | Required | Description | |---|---|---|---| | `paymentReference` | string | Yes | As returned by create. | | `state` | string | Yes | Currently `pending`, `executed`, `failed` or `abandoned`. See [States](#states). | | `amount` | integer | Yes | In cents. Once `executed`, the amount actually approved. | | `currency` | string | Yes | ISO currency code of `amount`. | | `amountRefunded` | integer | Yes | In cents: what has been paid back so far, the refunds that are `refunded`. A `pending` refund is not in it yet. See [Refunds](/refunds). | | `amountRemaining` | integer | Yes | In cents: what can still be refunded, the executed amount less every `refunded` **and every `pending`** refund. `0` until `executed`. | | `reference` | string | Yes | Your own order reference, echoed back verbatim. Null when you sent none. | ### The payment reference is an opaque string Store and compare `paymentReference` as a string, exactly as you received it. Today a live reference is a GUID and a test one is `test-` followed by a GUID (41 characters). **Do not validate it as a UUID** or parse it: a test reference already fails that check. Treat it as opaque: letters, digits, `-` and `_`, and allow up to 64 characters where you store it. ### States `pending` changes; `executed` (paid) never does. `failed` and `abandoned` (not paid within 24 hours) are final for the card, with one exception: an ANNA bank payment the shopper completes afterwards still turns the payment `executed`, and sends `payment.received`. Treat a state you do not recognise as `pending`: it never means paid. [Payment lifecycle](/payment-lifecycle) explains each one and what to do with it. On a partial approval the executed `amount` is **less** than you asked for, and this field is the only signal that a shortfall occurred. Compare it with the order total before shipping. You can poll the read every few seconds while the shopper is on the page. ## Retry safely with Idempotency-Key [#retrying-safely-idempotency-key] Without a key, every create opens a new payment, so two calls for one order open two separately payable checkouts. To retry safely after a timeout or a dropped connection, send an `Idempotency-Key` header (`X-Idempotency-Key` is accepted too). Generate its value once per checkout attempt, such as a UUID: ```http POST https://gateway.mps-emi.com/api/payments/internet/create Authorization: Bearer mps_live_… Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91 ``` - A retry with the **same key and the same body** returns the payment the first call made: the same `paymentReference` and `checkoutUrl`, and no second payment. - The **same key with a different body** is a `400` naming `Idempotency-Key`. Use a new key for a new payment. - A retry while the first call is **still running** is a `409` with `code` `idempotency_key_in_use`. Wait a second and send it again, unchanged. - A request refused as **invalid** (`400`) does not use up its key: fix the body and send it with the same key. - After a **`5xx` or a network error** you cannot tell whether the payment was made. Send the same request with the same key: you get the payment the first call made, or a new one if it made none. - A key belongs to your merchant and its mode: the same key from a test key and a live key, or from two merchants, makes two payments. - At most 255 characters: letters, digits and punctuation, no spaces. A key is kept for **24 hours** from the moment its payment was created, as long as that payment can be paid. Retries do not extend it. | You send the key again… | Same body | Different body | |---|---|---| | Within 24 hours | The first payment, `200` | `400` naming `Idempotency-Key` | | Within 24 hours, but the first payment can no longer be read (rare) | `409` `idempotency_key_expired`: create a new payment with a new key | `400` naming `Idempotency-Key` | | After 24 hours | A **new** payment | A new payment | After 24 hours the first payment is abandoned unless it was paid. Before you open a new payment for an order that already had one, read the first payment: if it is `executed`, the order is paid. Keep every `paymentReference` an order had, so a late payment can still be matched to it. ## Coming back MPS sends the shopper to your URLs **exactly as you passed them**. Nothing is appended: no payment reference, no state. To know which payment a return belongs to, keep the `paymentReference` with the order (or in the shopper's session) before redirecting. Or put your own order id in the URLs you pass, such as `https://shop.example.com/orders/1234/paid`. | The shopper lands on | When | `state` when you read it | |---|---|---| | `successUrl` | The payment went through | `executed` | | `failureUrl` | The payment was declined or failed | `failed` | | `cancelUrl`, or `failureUrl` without one | The shopper chose **Go back** on the checkout | Still `pending`: not paid | | `failureUrl` | The payment expired, 24 hours after it was created, while the checkout was still open | `abandoned` | On return, read the payment once on your backend. If it is still `pending`, poll it every 2 seconds for up to about 30 seconds. Then show "we are confirming your payment" and let the [webhook](#webhooks) or a later read settle the order. Never mark an order paid because the shopper reached your success URL. ## Card attempts are limited A **declined card ends the payment**: it is `failed`, and the shopper is sent to your failure URL. To let them try another card, create a new payment, with a new `Idempotency-Key`. Cards that end in neither an approval nor a decline leave the payment `pending`: an abandoned 3-D Secure step, or a card refused before the issuer decided. The shopper may try again on the same checkout, at most **five** cards per payment. After the fifth the checkout refuses further cards and tells the shopper so. Nothing is sent to your return URLs, and the payment stays `pending` until it is abandoned, 24 hours after it was created. A payment that has already been paid never takes a second card. ## Webhooks Pass a `callbackUrl` when you create the payment, and MPS posts a signed `payment.received` webhook to it, server to server, once the payment has been received and booked. It arrives even when the shopper closes the tab before coming back. A payment that does not go through sends none: read it. [Webhooks](/webhooks) shows how to verify the signature, what the body carries, and how retries work. ## Test mode A payment created with a **test key**, an API key starting `mps_test_`, is a test payment. It works as it does in live mode: the same endpoints, the same checkout URL, the same states and the same webhook. But no card is charged, no bank is contacted, and nothing is booked or paid out. - The `paymentReference` starts with `test-`, such as `test-00000000-0000-4000-8000-000000000001`; a live one is the GUID alone. It is the same reference everywhere (the checkout URL, the read endpoint and the webhook), so your system can tell a test payment from a live one by its reference alone. - The checkout shows a **Test mode** banner and lists the test cards below. - Only the test cards are accepted. Any other card number is refused under the card number field, and uses up one of the payment's five [card attempts](#card-attempts-are-limited). - The card number decides the outcome. Any future expiry date and any security code will do. | Card number | Scheme | Outcome | |---|---|---| | `4111 1111 1111 1111` | Visa | `executed` | | `5555 5555 5555 4444` | Mastercard | `executed` | | `4000 0000 0000 0002` | Visa | `failed` | | `5200 0000 0000 0007` | Mastercard | `failed` | | `4000 0000 0000 0010` | Visa | stays `pending` | The ANNA QR code opens ANNA's test screen, under a **Test mode** banner. The shopper chooses a bank as in live mode, then chooses how the bank answers instead of confirming in their banking app: | Choice | Outcome | |---|---| | Paid | `executed` | | Rejected by the bank | the bank payment fails | | Cancelled at the bank | the bank payment fails | | Stays pending | stays `pending` | A failed bank payment fails the payment once the card cannot pay it either, as in live mode: while the card form can still be used, the payment stays `pending`. An `executed` test payment sends the `payment.received` webhook to your `callbackUrl`, signed with the test key's own signing secret. It is shown once, next to the API key, when you generate the key. A test key has no 3-D Secure step. ## End-to-end example A minimal backend for a shop: the cart posts to `/pay`, the shopper pays on the MPS checkout, comes back to `/orders/:id/return`, and the backend reads the outcome. Run it with a **test key** and pay with `4111 1111 1111 1111` (any future expiry, any security code) for a paid order, or `4000 0000 0000 0002` for a declined one. See [Test mode](#test-mode). ```bash tab="curl" # Prerequisite: export MPS_API_KEY=mps_test_… (and jq installed) # 1. Create. Keep paymentReference with your order. One Idempotency-Key per checkout attempt: # resend the same one to retry, and you get the same payment back. IDEMPOTENCY_KEY=$(uuidgen) CREATED=$(curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/internet/create" \ -H "Authorization: Bearer $MPS_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEMPOTENCY_KEY" \ -d '{"amount":1995,"reference":"order-1234", "successUrl":"https://shop.example.com/orders/1234/return", "failureUrl":"https://shop.example.com/orders/1234/return"}') || { echo "$CREATED"; exit 1; } PAYMENT_REFERENCE=$(echo "$CREATED" | jq -r '.data.paymentReference') # 2. Open checkoutUrl in a browser and pay with a test card. echo "Pay here: $(echo "$CREATED" | jq -r '.data.checkoutUrl')" read -r -p "Press Enter once you have paid. " # 3. Read the outcome curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```ts tab="TypeScript" import express from 'express'; import { randomUUID } from 'node:crypto'; const API = 'https://gateway.mps-emi.com'; const app = express(); app.use(express.urlencoded({ extended: false })); // Your own order store; paymentReference is kept as a plain string. One order to try it with. const orders = new Map(); orders.set('1234', { total: 1995 }); // Your API key, from your vault or environment. Sent on every call; there is nothing to fetch first. const auth = { Authorization: `Bearer ${process.env.MPS_API_KEY}` }; async function readPayment(reference: string) { const res = await fetch(`${API}/api/payments/internet/${encodeURIComponent(reference)}`, { headers: auth, }); if (!res.ok) throw new Error(`Read failed: ${res.status}`); return (await res.json()).data as { state: string; amount: number }; } // Cart → MPS checkout app.post('/orders/:id/pay', async (req, res) => { const order = orders.get(req.params.id); if (!order) return res.sendStatus(404); const returnUrl = `https://shop.example.com/orders/${req.params.id}/return`; // One key per checkout attempt, stored with the order: a retry sends it again and gets the same payment. order.idempotencyKey ??= randomUUID(); try { const created = await fetch(`${API}/api/payments/internet/create`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': order.idempotencyKey }, body: JSON.stringify({ amount: order.total, // cents reference: req.params.id, successUrl: returnUrl, failureUrl: returnUrl, }), }); if (!created.ok) return res.status(502).send(await created.text()); const { data } = await created.json(); order.paymentReference = data.paymentReference; // store BEFORE redirecting res.redirect(303, data.checkoutUrl); // top-level redirect: the checkout cannot be framed } catch (err) { // A network error or a timeout: the payment may exist. Retry with the same idempotencyKey. console.error(err); res.status(502).send('We could not start your payment. Please try again.'); } }); // MPS → back to the shop. Nothing is appended to the URL; the order id in the path is enough. app.get('/orders/:id/return', async (req, res) => { const order = orders.get(req.params.id); if (!order?.paymentReference) return res.sendStatus(404); try { let payment = await readPayment(order.paymentReference); for (let i = 0; i < 15 && payment.state === 'pending'; i++) { await new Promise((r) => setTimeout(r, 2000)); payment = await readPayment(order.paymentReference); } if (payment.state === 'executed' && payment.amount === order.total) { order.paid = true; return res.send('Thank you, your order is paid.'); } if (payment.state === 'pending') return res.send('We are confirming your payment.'); res.send('Your payment did not go through. Please try again.'); } catch (err) { // The read failed: leave the order open, and let the webhook or a later read settle it. console.error(err); res.send('We are confirming your payment.'); } }); app.listen(3000); ``` The curl version prints the checkout and then the payment with `"state": "executed"` once you paid with `4111 1111 1111 1111`. In production, also pass a `callbackUrl` and settle orders from the [webhook](#webhooks): a shopper who closes the tab after paying never reaches your return URL. ## Errors Every status the create and read endpoints answer, with its body, is listed in [Errors and rate limits](/errors-and-rate-limits#by-endpoint). The ones you meet here: | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | Validation failed: an amount of zero, a non-HTTPS return URL, a `callbackUrl` that is not an absolute HTTPS URL on a publicly routable host, or an `Idempotency-Key` reused for a different request. The body names the field. | Fix the named field. See [Validation errors](/errors-and-rate-limits#validation-errors). | | `401` | — | No API key, or a wrong or revoked one. | Check the key. See [API key errors](/authentication#api-key-errors). | | `403` | — | The key lacks the scope; a partner key sent no `x-wallet-number`, or one that is not one of your merchants; or the merchant has no shop name registered yet. | Check the scope and the wallet. With a partner key, send `x-wallet-number`. For a missing shop name, contact MPS. See [Authentication errors](/errors-and-rate-limits#authentication-errors). | | `404` | — | Read only: no such payment for this merchant, or a partner key sent no `x-wallet-number`. | Check that the reference reached you unchanged, and read it for the wallet it was created with (with a partner key, the same `x-wallet-number`). See [Not found](/errors-and-rate-limits#not-found). | | `409` | `idempotency_key_in_use` | Create only: a payment with this `Idempotency-Key` is still being created. | Retry after a second with the same key and body. See [Conflicts](/errors-and-rate-limits#conflicts). | | `409` | `idempotency_key_expired` | Create only: the payment this key made can no longer be returned. | Create a new payment with a new key. See [Conflicts](/errors-and-rate-limits#conflicts). | | `429` | — | Rate limited. | Wait `Retry-After` seconds. See [Rate limits](/errors-and-rate-limits#rate-limits). | ## Related - [Receive webhooks](/webhooks) - [Payment lifecycle](/payment-lifecycle) - [Refund a payment](/refunds) --- # 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) --- # Payment lifecycle (/payment-lifecycle) > The states an online payment moves through, how the checkout redirect, the webhook and the read fit together, and what to do with each outcome. An online payment starts `pending` and ends in one of three states: `executed`, `failed` or `abandoned`. Your backend learns which one from the [read endpoint](/online-payments#read-the-outcome); the shopper's return and the [webhook](/webhooks) only tell you when to read. > **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. ## States pending: create pending --> executed: paid pending --> failed: declined or failed pending --> abandoned: nothing paid for 24 hours failed --> executed: late ANNA payment abandoned --> executed: late ANNA payment executed --> [*] note right of pending Not paid. Also the state after the shopper cancels on the checkout page, or after five cards that were neither approved nor declined. end note note right of executed Paid. Compare amount with the order total: a partial approval reports less than you asked for. end note `} /> | `state` | Trigger | Final | Timeout | What you do | |---|---|---|---|---| | `pending` | You create the payment. Not paid yet: the shopper may still be on the checkout, or cancelled it and was sent to your failure URL. | No | Becomes `abandoned` 24 hours after it was created, if still unpaid. | Never treat it as paid. Poll on return, then let the webhook or a later read settle it. See [`pending`](#pending). | | `executed` | The payment is paid. `amount` is the amount actually approved. | Yes | — | Compare `amount` with the order total, then fulfil once. See [`executed`](#executed). | | `failed` | The card was declined or the payment did not go through. | Yes, except for a late ANNA payment | — | Offer a new payment. See [`failed`](#failed). | | `abandoned` | Not paid within **24 hours** of being created. The checkout no longer takes a payment for it. | Yes, except for a late ANNA payment | — | Release held stock, or create a new payment. See [`abandoned`](#abandoned). | `executed` never changes. `failed` and `abandoned` change only when an ANNA bank payment the shopper started on the checkout completes afterwards: the payment becomes `executed` and sends `payment.received`. See [A late ANNA payment](#a-late-anna-payment). A state you do not recognise is `pending`, never paid. ## From create to fulfilment >Backend: Place order Backend->>API: POST /api/payments/internet/create
Authorization: Bearer API key
Idempotency-Key: one per checkout attempt API-->>Backend: paymentReference, checkoutUrl Note over Backend: Store paymentReference
with the order first Backend-->>Shopper: 303 to checkoutUrl Shopper->>Checkout: Pay by card, or by ANNA alt Paid Checkout-->>Shopper: Redirect to successUrl else Declined or failed Checkout-->>Shopper: Redirect to failureUrl else Cancelled Checkout-->>Shopper: Redirect to failureUrl, still pending end Note over Shopper,Checkout: The return and the webhook arrive in either order, or only one of them par The shopper's return Shopper->>Backend: Lands on your return URL Backend->>API: GET /api/payments/internet/{paymentReference} API-->>Backend: state, amount and The webhook (once the payment is received and booked, and a callbackUrl was passed) API->>Backend: POST callbackUrl, payment.received
signed with X-Mps-Signature Backend->>Backend: Verify the signature and timestamp
(401 if invalid) Backend->>Backend: Store it, keyed on X-Mps-Delivery-Id
(5xx if that fails) Backend-->>API: 2xx, only now Note over Backend: Later, a worker reads the payment Backend->>API: GET /api/payments/internet/{paymentReference} API-->>Backend: state, amount end Note over Backend: Fulfil once, on whichever comes first:
state is executed and amount equals the order total `} /> Points the diagram cannot show: - **Nothing is appended to your return URLs.** Match the return to its order by your own order id in the URL, or by the `paymentReference` you stored before redirecting. - **The return and the webhook arrive in either order**, and a shopper who closes the tab never returns at all. Settle the order on whichever comes first, after reading the payment, and make the second a no-op: key on `paymentReference`. - **`payment.received` is the only payment webhook.** It is sent once a payment has been received and booked — for a test payment, once it is `executed`. A `failed`, `abandoned` or still `pending` payment sends nothing. Its refunds send their own events once decided (`refund.refunded`, `refund.failed`, `refund.canceled`; see [Webhooks](/webhooks#events)). No `callbackUrl`, or no [signing secret](/webhooks#the-signing-secret) on your key, and nothing is sent either. - **Delivery is at least once.** A webhook is attempted up to six times over about 8½ hours; see [Delivery](/webhooks#delivery). > **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. ## Processing a webhook Verify the webhook, then either read the payment, settle the order and answer `2xx` ([process, then answer](/webhooks#the-simple-handler-process-then-answer)), or store the webhook, answer `2xx` and settle the order from a worker ([store, answer, process](/webhooks#the-production-pattern-store-answer-process)), as the [integration examples](/integration-examples) do. ## Handling each outcome ### `pending` Never treat it as paid. On the shopper's return, poll the read every 2 seconds for up to about 30 seconds. If it is still `pending`, show "we are confirming your payment" and let the webhook or a later read settle the order. Do not poll faster: payment requests are limited to 100 a minute. A shopper who cancelled on the checkout page lands on your failure URL with the payment still `pending`, and can still pay it: send them back to the same `checkoutUrl`. After five cards that were neither approved nor declined (see [Card attempts](/online-payments#card-attempts-are-limited)) the checkout refuses more cards and does not send the shopper back; the payment stays `pending`. ### `executed` The payment is paid. Compare `amount` with the order total before you ship: on a partial approval it is **less** than you asked for, and this field is the only signal. Fulfil the order once, even if the webhook and the return both report it. **A partial approval** (`amount` less than the order total) is paid, but not in full. Do not ship it. Either refund it ([Refund a payment](/refunds#refund-a-payment), with no `amount`) and ask the shopper to pay again with a new payment, or settle the difference with them yourself. Never mark the order paid in full. **Fulfil once, act once.** Marking the order paid with an update that only succeeds once (`… WHERE paid_at IS NULL`) makes the *record* exact. Shipping, an e-mail or a call to another system can still fail or run twice. Record what must happen in the same database commit that marks the order paid (an outbox table), and have a worker carry it out, with an idempotency key of its own towards the other system. ### `failed` The card was declined or the payment failed. Let the shopper try again with a **new** payment: create is per checkout attempt, and a failed payment takes no new card. Keep the order open rather than cancelling it on the first decline: see [A late ANNA payment](#a-late-anna-payment). ### `abandoned` Nothing was paid within 24 hours of the payment being created, so MPS gave up on it and the checkout stops taking a payment for it. No webhook is sent. Release any stock you held, or create a new payment if the shopper comes back. Until those 24 hours are up an unpaid payment is `pending`: the shopper may still come back to the checkout page and pay. ### A late ANNA payment The checkout also offers ANNA, a bank payment the shopper confirms in their banking app. A shopper can start one, then let the payment fail on a card or expire, and complete the bank payment afterwards. The money then arrives: the payment turns `executed` and `payment.received` is sent, even though you already saw `failed` or `abandoned`. Keep handling `payment.received` for orders you closed. Reopen and fulfil the order, or [refund the payment](/refunds#refund-a-payment) if you can no longer deliver. ## Reconcile what you did not hear about The webhook is the fast path, not a guarantee: it can be given up after its last retry, and only a received payment sends one. For any order still waiting, read the payment by its `paymentReference` — the read is always authoritative. A schedule for the orders still open: 1. **Every 15 minutes**, take the orders that have a `paymentReference` and are neither settled nor closed. 2. **Read each one**, spread over the run rather than all at once: it shares the [rate limit](/errors-and-rate-limits#rate-limits) with your checkout. 3. **Act on the state.** `executed`: settle it once, as above. `failed` or `abandoned`: close the order or offer a new payment. `pending`: leave it for a later run, reading it less often as it ages (15 minutes, then hourly). 4. **Stop at 24 hours.** An unpaid payment reads `abandoned` 24 hours after it was created. Only a late ANNA payment changes it after that, and that sends `payment.received`. 5. **Escalate** what does not resolve: a read that keeps failing, or a payment still `pending` well after 24 hours. That needs a person, not another retry. **What this schedule does not cover:** a [late ANNA payment](#a-late-anna-payment) that arrives after you stopped reading, when every delivery of its `payment.received` failed. The payment reads `executed`, but nothing tells you. Keep the `paymentReference` of every payment an order had, closed orders included, so it can always be read. If your business must catch this case, keep reading the `failed` and `abandoned` payments of closed orders once a day, at a low rate, for as long as you would still fulfil or refund such an order. Money you cannot match to an order: contact MPS with the `paymentReference`, the time (UTC) and `state` of your last read, and the [`traceparent`](/errors-and-rate-limits#traceparent) header of that read. **A create whose answer you never got** has no `paymentReference` to read. Send the same request with the same `Idempotency-Key` within 24 hours: you get the payment it made, or a new one if it made none. There is no search by your own `reference`, which is why the key is stored before the call. ## Related - [Follow a payment's timeline](/payment-timeline): every step a payment went through, to explain its state - [Process webhooks reliably](/webhooks#processing-them-reliably) - [Accept a payment](/online-payments) - [Integration examples](/integration-examples) - [Production checklist](/production-checklist) --- # Authentication (/authentication) > Your backend sends its MPS API key in the Authorization header of every call. Your backend authenticates every call with an **API key**: one string, sent on every request. There is nothing to fetch, cache or refresh first. > **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. ```http POST https://gateway.mps-emi.com/api/payments/internet/create Authorization: Bearer mps_test_… Content-Type: application/json Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91 ``` The MPS platform issues an API key, together with a [webhook signing secret](/webhooks), when you generate a test key or a live key in **Online**. Both are shown **once**: store them in your backend's vault or environment straight away. An API key acts for your merchant until it is revoked. Never put it in a browser, a mobile app or a POS front end: anything shipped to a device can be extracted from it. Let the app call your backend, and your backend call MPS. ## The API key [#the-key] ```text mps_live__ mps_test__ ``` | Part | Meaning | |---|---| | `mps_live_` / `mps_test_` | A **live key** takes real payments. A **test key** takes test payments on your own wallet: nothing is charged, booked or paid out. | | `` | 12 lower-case letters and digits. Not confidential: it is how MPS and the platform's key list refer to the key. | | `` | The confidential part. It can itself contain `_`. | Treat the whole string as one opaque value: copy it exactly, never split it or build it yourself. ## Send the key [#send-it] Send the key on **every** call in the `Authorization` header, with the `Bearer` scheme: ```http Authorization: Bearer mps_live_… ``` That is the only place it is read: not a query parameter, not an `X-Api-Key` header, not HTTP Basic. ```bash tab="curl" # Prerequisite: export MPS_API_KEY=mps_test_… and PAYMENT_REFERENCE= curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/$PAYMENT_REFERENCE" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```ts tab="TypeScript" // Prerequisite: MPS_API_KEY=mps_test_… and PAYMENT_REFERENCE in the environment. Node 18 or later. const paymentReference = process.env.PAYMENT_REFERENCE ?? ''; const res = await fetch(`https://gateway.mps-emi.com/api/payments/internet/${encodeURIComponent(paymentReference)}`, { headers: { Authorization: `Bearer ${process.env.MPS_API_KEY}` }, }); if (!res.ok) throw new Error(`Read failed: ${res.status}`); // 401: check the key; 403: the scope or the wallet console.log((await res.json()).data); ``` Both print the payment, with its `state` and `amount`. ## Test keys and live keys [#test-and-production-keys] A test key works on the same host and the same endpoints as a live key, so the only thing that changes when you go live is the key. Test payments are recognisable on their own: their payment reference starts with `test-`. See [Accept a payment › Test mode](/online-payments#test-mode). Keys are created under **Online › API keys** on the MPS platform, test and live alike, each with a name so you recognise it. You can hold several test keys at once, for example one per shop or developer. A live key can be created once the merchant it is for has signed its contract with MPS; until then test keys work as usual. API keys do not expire, test or live: a key works until you revoke it. ## Choose the merchant [#choosing-the-merchant] Every payment is for **exactly one merchant wallet**. Which one depends on the kind of key you hold: | Your key | Send `x-wallet-number`? | |---|---| | A **test key** (`mps_test_…`) | **No.** It acts for your own wallet, in test mode; a header you send is ignored. | | A **merchant key**, issued for your own wallet | **No.** It acts for that wallet; a header you send is ignored. | | A **partner key** (you take payments for merchants you onboard) | **Yes, on every call**, even while you have only one merchant: `x-wallet-number: BE0000000000`. | ```http POST https://gateway.mps-emi.com/api/payments/internet/create Authorization: Bearer mps_live_… x-wallet-number: BE0000000000 Content-Type: application/json Idempotency-Key: 4f9c2e1a-7b3d-4c8e-9a1f-0d6e5b2c7a91 ``` The wallet you name must be one of your merchants. Anything else is refused with `403` and the same message: another merchant's wallet, or one that cannot trade. A key cannot be used to discover wallets: ```json title="403 Forbidden" { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ``` Without `x-wallet-number`, a partner key names no merchant. Creating a payment then answers `403` with no body, and reading one answers `404`. An integration that still sends the header's former name, `x-card-number`, keeps working. Send one of the two: naming two different wallets answers `403` with `invalid_request`. Send the wallet number exactly as MPS shows it: upper case, no spaces, such as `BE0000000000`. Read back a payment with the same wallet it was created with: a payment created for one merchant cannot be read as another. ## Keep the key on your backend MPS shows the confidential part once and stores it hashed. It can only be replaced, never recovered. - Keep it in your backend's vault or environment, never in source control. - Never send it to a browser, an app or a POS front end, and never log it. Its `mps_live_` / `mps_test_` prefix makes a key quick to find in logs and repositories, and for leak scanners to flag. - Use a test key everywhere except production. ## Rotate a key Rotate a key, test or live, without downtime: Create a new key under **Online › API keys**. Your old key keeps working. Deploy the new key to your backend and confirm calls succeed with it. Revoke the old key on the same screen. Every key issued in the MPS platform, test or live, comes with its own webhook signing secret: deploy the new key's signing secret with it. Revoke a key at once if you think it has leaked. Revocation takes effect within about **30 seconds**; after that, every call with the key answers `401`. ## Scopes Every endpoint needs a scope: | Scope | Grants | |---|---| | `internet:create` | Create an online (card) payment | | `internet:read` | Read an online payment's status | | `payments:refund` | Refund a payment, and read and cancel its refunds. A live key holds it only on request; every test key holds it. See [Refunds](/refunds). | | `payment-links:create` | Make a payment link, and cancel one. A partner's key makes test links only. See [Create a payment link with the API](/payment-links-api). | | `payment-links:read` | List and read payment links. | | `registration-links:manage` | Make, list, read and revoke a live partner's personal registration links. Held by the live key a live partner makes for itself; a merchant's key, a partner's key for a merchant and a test key never hold it. See [Create a registration link](/registration-links). | Every key holds `internet:create` and `internet:read`. A test key also holds `payments:refund` and the payment-link scopes; a live key holds the payment-link scopes from this release on, and `payments:refund` only when MPS granted it. A live key holds it only once MPS granted it, so ask for it when you request the key. A call that needs a scope the key does not hold answers `403`. ## API key errors | Status | Code | Cause | Resolution | |---|---|---|---| | `401` | — | The key is wrong, malformed or revoked, or sent to a host other than `gateway.mps-emi.com`. The response carries `WWW-Authenticate: Bearer error="invalid_token"`. | Check the key; do not retry in a loop. See [Authentication errors](/errors-and-rate-limits#authentication-errors). | | `403` | `invalid_request` | The `x-wallet-number` you sent is not one of your merchants. Body as shown [above](#choosing-the-merchant). | Send a wallet your key covers. | | `403` | — | Create a payment with a partner key and no `x-wallet-number`. No body. A read without it answers `404`. | Send `x-wallet-number` on every call. | | `403` | — | The key is valid but lacks the endpoint's scope. No body. | See [Scopes](#scopes). | | `429` | — | Too many failed key attempts from your address (more than 10 in a minute). | Wait `Retry-After` seconds and fix the key before trying again. See [Rate limits](/errors-and-rate-limits#rate-limits). | ## Related - [Accept a payment](/online-payments) - [Errors and rate limits](/errors-and-rate-limits) - [Integration examples](/integration-examples) --- # Concepts (/concepts) > The keys, wallets, identifiers and payment states every page of these docs refers to, explained in one place. ## Keys Every integration authenticates with an **API key**, sent as `Authorization: Bearer` on every call from your backend. What a key can do depends on its kind: > **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. | Kind | Recognised by | Takes payments for | Send `x-wallet-number`? | |---|---|---|---| | **Test key** | Starts with `mps_test_` | Your own wallet, as test payments: nothing is charged, booked or paid out. It does not expire. | No | | **Merchant key** | Starts with `mps_live_`, issued for one merchant | That merchant's wallet | No | | **Partner key** | Starts with `mps_live_`, issued to a partner that onboards merchants | Any merchant the partner onboarded, named per call | Yes, always | You create keys under **Online › API keys** on the MPS platform: as many test keys as you like, and live keys per merchant once that merchant has signed its contract. A key generated on the platform comes with its own webhook **signing secret**, shown once, which signs the webhooks MPS sends to your `callbackUrl`. For a key MPS issued to you directly, ask MPS for one: see [The signing secret](/webhooks#the-signing-secret). The API key and the signing secret can be replaced, never recovered. Keep both on your backend: see [Keep the key on your backend](/authentication#keep-the-key-on-your-backend). ## Wallets and merchants A **wallet** identifies a merchant at MPS, written like `BE0000000000`. Every call acts for exactly one wallet, and every payment it creates is for that wallet. A test key or a merchant key acts for its own wallet and ignores any you send; a partner key names the merchant on every call with `x-wallet-number`. A payment created for one merchant cannot be read as another. See [Choosing the merchant](/authentication#choosing-the-merchant). ## Scopes An API key carries every scope it was issued: | Scope | Allows | |---|---| | `internet:create`, `internet:read` | Creating and reading [online payments](/online-payments) | | `payments:refund` | Refunding a payment, and reading and cancelling its refunds. See [Refunds](/refunds) | | `payment-links:create`, `payment-links:read` | Making, cancelling, listing and reading payment links. See [Create a payment link with the API](/payment-links-api) | | `registration-links:manage` | A live partner's personal registration links. See [Create a registration link](/registration-links) | ## Hosts Your backend calls the API at `https://gateway.mps-emi.com`; the shopper's browser opens the checkout at `https://pay.mps-emi.com`. Test keys and live keys use the same hosts: see [The hosts](/overview#the-hosts). ## Identifiers | Identifier | Where it comes from | What it is for | |---|---|---| | `paymentReference` | Create, and every webhook | The MPS reference of an online payment, and the only key its read accepts. `test-` + a GUID for a test payment. In a webhook it identifies the payment the same way. | | `reference` | You, on create | Your own order reference, shown to the shopper. Echoed back on the read, and as `merchantReference` in the webhook. At most 64 characters: letters, digits, spaces and `. _ : / # + -`. Never a lookup key. | | `Idempotency-Key` | You, on create and on a refund | One value per attempt — a payment's checkout attempt, or one refund — stored before you send it. A retry with the same key and body returns the first result instead of making a second. At most 255 characters: letters, digits and punctuation, no spaces. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). | | `refundId` | Refund create | The refund, and the key Get a refund and Cancel a refund take; also in every refund webhook. | | `paymentId` | The webhook | The booking MPS made for a received payment. | | `traceId` | Every error (problem document) | One call in MPS's logs. Quote it when you contact MPS about a failed call. | | `X-Mps-Delivery-Id` | The webhook headers | One webhook, for logs and support. Every retry of it carries the same value, so it marks a repeat; settle orders by `paymentReference`. | Treat every identifier MPS returns as an opaque string: store it exactly as returned, allow up to 64 characters, and never parse or validate its format. The `Idempotency-Key` is yours, and can be up to 255 characters. ## Payment lifecycle The read answers a `state`: `pending` until it is decided, then `executed` (paid), `failed` or `abandoned` (not paid within 24 hours). Only a late ANNA bank payment turns `failed` or `abandoned` into `executed`. [Payment lifecycle](/payment-lifecycle) explains each one, draws how the states, the redirect and the webhook fit together, and says what to do with each. ### `state`, `status` and the webhook Two fields name an outcome, in three places. They are not interchangeable: | Where | Field | Values | |---|---|---| | Reading a payment | `state` | `pending`, `executed`, `failed`, `abandoned` | | The `payment.received` webhook | `status` | Always `completed`: the payment was received. Reading it then answers `state` `executed`. | | A refund, read or in a refund webhook | `status` | `pending`, `refunded`, `failed`, `canceled` | Decide on the read's `state`. A webhook's `status` tells you which event it is, not what to ship. A state you do not recognise is `pending`, never paid. New states may be added: see the [changelog](/changelog#what-counts-as-non-breaking). ## Related - [Payment lifecycle](/payment-lifecycle): every state, the redirect and the webhook in one diagram - [Authentication](/authentication): keys, choosing the merchant and scopes - [Webhooks](/webhooks): receive and verify webhooks - [Overview](/overview): the hosts and the shape of every integration --- # Run an integration example (/integration-examples) > Run a minimal example or a production starting point in C#, TypeScript, Python or PHP that creates payments, verifies and stores webhooks and settles orders, to which you add durable fulfilment and reconciliation before a live shop uses it. Two starting points, each in C#, TypeScript, Python and PHP: - **[Minimal](#minimal-example)**: create a payment, redirect, read the result. About 40 lines, to see the flow work. - **[Production](#production-example)**: a production starting point, a whole backend in one file: a shop that sells one EUR 19.95 order. Start it, pay with a [test card](/online-payments#test-mode), and watch the order settle from the return page and from the webhook. The four do the same thing in the same order, so you can read the one you know and port it. > **Server only.** The API cannot be called from a browser. The gateway answers no cross-origin (CORS) requests, and the API key must never reach a browser. Call it from your server. > **Warning.** Landing on successUrl is not proof of payment. Verify the webhook signature, read the payment, and check its state, amount, currency, and reference before marking an order paid. - A test key (`mps_test_…`) and its signing secret, from **Online › API keys** on the MPS platform - The runtime of the language you pick: .NET 10, Node 22.13 or later, Python 3.10 or later, or PHP 8.1 or later (8.2 for the production example) - For the production example: a public HTTPS address for port `8000`, such as a tunnel (ngrok, Cloudflare Tunnel) ## Minimal example The smallest useful integration: create a payment, send the shopper to the checkout, and read the result when they come back. Open `http://localhost:8000/checkout`, pay with a [test card](/online-payments#test-mode), and the return page says whether it is paid. It keeps the order in memory, makes a new `Idempotency-Key` per click, receives no webhook and retries nothing. A production integration also verifies webhooks, stores the order and its key before calling MPS, and fulfils each order once: the [production example](#production-example) below does all of it. .NET 10: `dotnet new web`, replace `Program.cs`, then `dotnet run`. ```csharp title="Program.cs" using System.Text.Json; var app = WebApplication.CreateBuilder(args).Build(); var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com/api/payments/internet/") }; mps.DefaultRequestHeaders.Authorization = new("Bearer", Environment.GetEnvironmentVariable("MPS_API_KEY")); var payments = new Dictionary(); // order id -> paymentReference: your database in a real shop app.MapGet("/checkout", async () => { var order = "order-42"; var back = $"http://localhost:8000/return?order={order}"; using var create = new HttpRequestMessage(HttpMethod.Post, "create") { Content = JsonContent.Create(new { amount = 1995, reference = order, successUrl = back, failureUrl = back }) }; create.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString()); using var response = await mps.SendAsync(create); if (!response.IsSuccessStatusCode) return Results.Text($"MPS answered {(int)response.StatusCode}", statusCode: 502); var data = (await response.Content.ReadFromJsonAsync()).GetProperty("data"); payments[order] = data.GetProperty("paymentReference").GetString()!; return Results.Redirect(data.GetProperty("checkoutUrl").GetString()!); }); app.MapGet("/return", async (string order) => { if (!payments.TryGetValue(order, out var reference)) return Results.NotFound("Unknown order"); var data = (await mps.GetFromJsonAsync(Uri.EscapeDataString(reference))).GetProperty("data"); var state = data.GetProperty("state").GetString(); var paid = state == "executed" && data.GetProperty("amount").GetInt64() == 1995; return Results.Text(paid ? "Paid" : $"Not paid: {state}"); }); app.Run("http://localhost:8000"); ``` Run it: `npx tsx server.ts` (on Node 23.6 or later, `node server.ts` works too). ```ts title="server.ts" import { createServer } from 'node:http'; import { randomUUID } from 'node:crypto'; const API = 'https://gateway.mps-emi.com/api/payments/internet'; const auth = { Authorization: `Bearer ${process.env.MPS_API_KEY}` }; const payments = new Map(); // order id -> paymentReference: your database in a real shop createServer(async (req, res) => { const url = new URL(req.url ?? '/', 'http://localhost:8000'); if (url.pathname === '/checkout') { const order = 'order-42'; const back = `http://localhost:8000/return?order=${order}`; const created = await fetch(`${API}/create`, { method: 'POST', headers: { ...auth, 'Content-Type': 'application/json', 'Idempotency-Key': randomUUID() }, body: JSON.stringify({ amount: 1995, reference: order, successUrl: back, failureUrl: back }), }); if (created.status !== 200) return res.writeHead(502).end(`MPS answered ${created.status}`); const { data } = await created.json(); payments.set(order, data.paymentReference); res.writeHead(303, { Location: data.checkoutUrl }).end(); } else if (url.pathname === '/return') { const reference = payments.get(url.searchParams.get('order') ?? ''); if (!reference) return res.writeHead(404).end('Unknown order'); const read = await fetch(`${API}/${encodeURIComponent(reference)}`, { headers: auth }); const { data } = await read.json(); const paid = data.state === 'executed' && data.amount === 1995; res.end(paid ? 'Paid' : `Not paid: ${data.state}`); } else { res.writeHead(404).end(); } }).listen(8000); ``` `pip install flask requests`, then `python app.py`. ```python title="app.py" import os, uuid from urllib.parse import quote import requests from flask import Flask, redirect, request API = "https://gateway.mps-emi.com/api/payments/internet" AUTH = {"Authorization": f"Bearer {os.environ['MPS_API_KEY']}"} app = Flask(__name__) payments = {} # order id -> paymentReference: your database in a real shop @app.get("/checkout") def checkout(): order = "order-42" back = f"http://localhost:8000/return?order={order}" res = requests.post(f"{API}/create", timeout=10, headers={**AUTH, "Idempotency-Key": str(uuid.uuid4())}, json={"amount": 1995, "reference": order, "successUrl": back, "failureUrl": back}) if res.status_code != 200: return f"MPS answered {res.status_code}", 502 data = res.json()["data"] payments[order] = data["paymentReference"] return redirect(data["checkoutUrl"], 303) @app.get("/return") def back(): reference = payments.get(request.args.get("order", "")) if reference is None: return "Unknown order", 404 payment = requests.get(f"{API}/{quote(reference, safe='')}", headers=AUTH, timeout=10).json()["data"] paid = payment["state"] == "executed" and payment["amount"] == 1995 return "Paid" if paid else f"Not paid: {payment['state']}" if __name__ == "__main__": app.run(port=8000) ``` PHP 8.1 or later with curl: `php -S localhost:8000 index.php`. ```php title="index.php" paymentReference: your database in a real shop const API = 'https://gateway.mps-emi.com/api/payments/internet'; function mps(string $url, ?array $body = null): array { $headers = ['Authorization: Bearer ' . getenv('MPS_API_KEY'), 'Content-Type: application/json']; $ch = curl_init($url); if ($body !== null) { $headers[] = 'Idempotency-Key: ' . bin2hex(random_bytes(16)); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); } curl_setopt_array($ch, [CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]); $response = json_decode((string) curl_exec($ch), true); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); if ($status !== 200) { http_response_code(502); exit("MPS answered $status"); } return $response['data']; } $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); if ($path === '/checkout') { $order = 'order-42'; $back = "http://localhost:8000/return?order=$order"; $data = mps(API . '/create', ['amount' => 1995, 'reference' => $order, 'successUrl' => $back, 'failureUrl' => $back]); $_SESSION[$order] = $data['paymentReference']; header('Location: ' . $data['checkoutUrl'], true, 303); } elseif ($path === '/return') { $reference = $_SESSION[$_GET['order'] ?? ''] ?? null; if ($reference === null) { http_response_code(404); exit('Unknown order'); } $payment = mps(API . '/' . rawurlencode($reference)); $paid = $payment['state'] === 'executed' && $payment['amount'] === 1995; echo $paid ? 'Paid' : "Not paid: {$payment['state']}"; } else { http_response_code(404); } ``` ## Production example The rest of this page is a production starting point, one file per language: webhook verification, a durable inbox, retried payment reads, one order with as many payment attempts as the shopper needs, and an atomic order-paid update, with recovery after a restart. **Fulfilment is a log message.** Before going live, record a fulfilment job in the same database commit that marks the order paid, then process that job with retries and an idempotency key the downstream system accepts, and run the reconciliation schedule in [Payment lifecycle](/payment-lifecycle#reconcile-what-you-did-not-hear-about). Each example runs **one worker in one process**, and its worker does not claim inbox rows. Run two instances (two servers behind a load balancer, or two overlapping cron runs of the PHP worker) and both can take the same row. The order is still settled once (see **The order is settled once** below), but both read the payment and record the outcome. Before running more than one worker, have each claim a row with an update only one of them can win, and process the row only when that update changed it: ```sql UPDATE webhook_inbox SET status = 'processing', claimed_until = :now + 60 WHERE delivery_id = :delivery_id AND (status = 'pending' OR (status = 'processing' AND claimed_until < :now)) ``` `claimed_until` is a column the examples do not have: it lets another worker take over a row whose worker stopped mid-way. On PostgreSQL, pick the candidates with `SELECT … FOR UPDATE SKIP LOCKED`; or use your queue, which hands each message to one worker. Run the PHP worker under a lock (`flock -n /tmp/mps-worker.lock php index.php`) so cron runs never overlap. ## What every example does - **`POST /checkout`** stores the order and a payment attempt with a fresh `Idempotency-Key`, and creates the payment with `POST /api/payments/internet/create` (amount in cents, `reference`, `successUrl`, `failureUrl`, `callbackUrl`), sending that key. It stores `paymentReference` and `checkoutUrl` against the attempt **before** redirecting, and sends the shopper to `checkoutUrl` with a `303`. If the create fails, **Try again** sends the same attempt with the same key: MPS returns a payment the failed call did open, rather than make a second one. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). - **Trying again after a `failed` or `abandoned` payment** creates a new payment attempt for the **same order**, with a new idempotency key, and keeps every earlier attempt with its `paymentReference`. A `pending` payment is not replaced: its checkout is reopened. A late ANNA payment on an earlier attempt still belongs to that order. If the order is already paid, the second payment is recorded for review and a refund; the order is never fulfilled twice. See [`failed`](/payment-lifecycle#failed). - **`POST /webhooks/mps`** reads the raw body, checks `X-Mps-Timestamp` is within five minutes, verifies `X-Mps-Signature` (HMAC-SHA256 of `{timestamp}.{raw body}`, lower-case hex, every `v1=` value, constant-time), **stores the webhook in the `webhook_inbox` table**, keyed on `X-Mps-Delivery-Id` so a duplicate webhook is a no-op, and only then answers `2xx`. If it cannot store it, it answers `500` and MPS tries again. It does no other work. See [Process webhooks reliably](/webhooks#processing-them-reliably). - **A worker** completes the business operation, separately from receiving the webhook. Every few seconds it takes the pending inbox rows, finds the attempt and order of each payment (an earlier attempt included), reads the payment and settles it. A temporary failure (a timeout, a `429`, a `5xx`, a payment still `pending`) is retried with backoff, up to 8 times; a permanent one (an unknown payment, a different amount, a payment that does not match its order, a refused read) is kept as `failed` with its reason, for you to look at. Because the inbox is stored, a crash or a restart loses nothing: the next pass picks up where it stopped. In C#, TypeScript and Python it runs inside the server; in PHP it is `php index.php`, run from cron. - **`GET /return`** is both the `successUrl` and the `failureUrl`. It never trusts the landing: it reads `GET /api/payments/internet/{paymentReference}` and settles through the **same function as the worker**, so both paths check the same things before an order is marked paid: `paymentReference` matches the stored attempt (compared as opaque strings), `reference` matches the order, `currency` matches the order's (`EUR` here), `state` is `executed` and `amount` equals the order total in cents. A mismatch never marks the order paid and is recorded for investigation; a partial approval leaves the order unpaid for a person to decide; an unknown state stays pending. The page re-reads a `pending` payment every 2 seconds for about 30 seconds. - **Errors** follow [Errors and rate limits](/errors-and-rate-limits): a `400` logs each field of the problem document, `401` and `403` are configuration problems and are not retried, a `429` is retried after `Retry-After`, and a `5xx` or network error is retried on reads **and on the create**, which is safe because it carries an `Idempotency-Key`. A `409` is decided on its `code`: only `idempotency_key_in_use` (the first call with that key is still running) is retried, after a second; any other code, or none, is final. - **The order is settled once.** The worker and the return page both settle through one statement, `UPDATE orders SET paid_at = …, paid_by = … WHERE id = … AND paid_at IS NULL`, and ship only when it changed a row. A duplicate delivery, a second worker pass or the shopper's return racing the worker cannot ship twice; a second payment that completes for an order already paid is flagged for a refund. **Fulfilment is a placeholder**: where the examples log "ship it", a real shop inserts a fulfilment job in the same commit and processes it with retries and downstream idempotency, so a failed shipment is not lost once the order reads paid. The paid-at update alone does not make the shipment happen. See [Process, then answer](/webhooks#the-simple-handler-process-then-answer) and [Reconcile what you did not hear about](/payment-lifecycle#reconcile-what-you-did-not-hear-about). - **Storage** is SQLite, in `mps-example.db`, so you can run each example as is. It stands in for your database: the same three tables and statements work there. It is a single-instance setup: with more than one worker, claim each row first, as the **Single-instance examples** box at the top shows, or use your queue. Find what needs a person with `SELECT * FROM webhook_inbox WHERE status = 'failed'`. ## Run the production example ### Configure [#configure] | Variable | Required | Description | |---|---|---| | `MPS_API_KEY` | Yes | Your API key, `mps_test_…` while you build. Sent as `Authorization: Bearer`. | | `MPS_WEBHOOK_SECRET` | Yes | The signing secret shown next to the key. | | `PUBLIC_BASE_URL` | Yes | The public `https://` address of this server, for example a tunnel to `localhost:8000`. The examples build the return URL and the `callbackUrl` from it. | | `MPS_WALLET_NUMBER` | No | Partner keys only: the merchant's wallet, sent as `x-wallet-number` on every call. Leave it unset for a test key or a merchant's own key. See [Choosing the merchant](/authentication#choosing-the-merchant). | ```bash export MPS_API_KEY="mps_test_…" # from your secret store, never from source control export MPS_WEBHOOK_SECRET="…" export PUBLIC_BASE_URL="https://your-tunnel.example" # forwards to http://localhost:8000 ``` The webhook only reaches you on a public HTTPS host: put a tunnel (ngrok, Cloudflare Tunnel) in front of port `8000`. Every example listens there. ### Run the code [#the-code] .NET 10, ASP.NET Core minimal API and `HttpClient`, plus SQLite for storage. Run it: `dotnet new web -n MpsExample`, then `dotnet add package Microsoft.Data.Sqlite`, replace `Program.cs` with the file below, then `dotnet run --urls http://localhost:8000`. The orders and the webhook inbox live in `mps-example.db`. ```csharp title="Program.cs" // Program.cs: .NET 10 minimal API; one package, Microsoft.Data.Sqlite. using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; using Microsoft.Data.Sqlite; var apiKey = Required("MPS_API_KEY"); // mps_test_… or mps_live_… var webhookSecret = Required("MPS_WEBHOOK_SECRET"); // shown once, next to the API key var publicBaseUrl = Required("PUBLIC_BASE_URL").TrimEnd('/'); var walletNumber = Environment.GetEnvironmentVariable("MPS_WALLET_NUMBER"); var mps = new HttpClient { BaseAddress = new("https://gateway.mps-emi.com"), Timeout = TimeSpan.FromSeconds(15) }; mps.DefaultRequestHeaders.Authorization = new("Bearer", apiKey); // Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if (!string.IsNullOrEmpty(walletNumber)) mps.DefaultRequestHeaders.Add("x-wallet-number", walletNumber); // SQLite stands in for your database: the same tables and statements work there. const string connectionString = "Data Source=mps-example.db"; Execute(""" CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see MarkPaid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); """); var app = WebApplication.CreateBuilder(args).Build(); var log = app.Logger; app.MapGet("/", () => Html("""
""")); // 1. Create the payment and send the shopper to the MPS checkout. ?retry= tries again for an order that exists: // the order stays, with every attempt it ever had, so a late payment on an earlier attempt still finds it. app.MapPost("/checkout", async (HttpResponse response, string? retry) => { var order = retry is null ? null : OrderById(retry); if (order is { PaidAt: not null }) return Html("

This order is already paid.

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

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

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

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

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

We could not start the payment.

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

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

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

Thank you, your order is paid.

"), Outcome.PaidTwice => Html("

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

"), Outcome.Short => Html("

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

"), Outcome.Mismatch => Html("

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

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

Your payment did not go through.

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

Confirming your payment…

"""), _ => Html("

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

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

This order is already paid.

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

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

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

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

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

We could not start the payment.

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

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

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

Thank you, your order is paid.

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

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

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

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

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

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

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

Your payment did not go through.

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

Confirming your payment…

`) : html(res, '

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

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

This order is already paid.

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

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

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

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

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

We could not start the payment.

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

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

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

Thank you, your order is paid.

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

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

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

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

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

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

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

Your payment did not go through.

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

Confirming your payment…

") return html("

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

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

This order is already paid.

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

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

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

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

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

We could not start the payment.

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

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

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

Thank you, your order is paid.

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

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

'), 'short' => html('

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

'), 'mismatch' => html('

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

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

Your payment did not go through.

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

Confirming your payment…

') : html('

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

'), }; } // 4. The worker: the business operation, separate from receiving the webhook. Each run takes up to 20 // due rows of the inbox. A row left pending (a crash, a restart) is picked up by the next run: at-least-once, // and mark_paid makes that safe. Run it every 5 seconds while testing, from cron every minute in production. // One worker at a time: with several, claim a row first (UPDATE ... SET status = 'processing' ... RETURNING) or use your queue. function confirm_pending_webhooks(): void { $rows = query("SELECT * FROM webhook_inbox WHERE status = 'pending' AND next_attempt_at <= ? ORDER BY received_at LIMIT 20", [time()])->fetchAll(); foreach ($rows as $row) { try { // one bad row never stops the batch try { [$outcome, $error] = process_notification($row['payment_reference']); } catch (Throwable $e) { [$outcome, $error] = ['temporary', $e->getMessage()]; } record_outcome($row, $outcome, $error); } catch (Throwable $e) { error_log("Inbox row {$row['delivery_id']} failed; the next run retries: {$e->getMessage()}"); } } } // Returns [processed|temporary|permanent, error]. Temporary is tried again later; permanent needs a person. function process_notification(string $paymentReference): array { // Any attempt, active or not: a late ANNA payment on an earlier attempt still belongs to its order. $attempt = query('SELECT * FROM payment_attempts WHERE payment_reference = ?', [$paymentReference])->fetch(); $order = $attempt === false ? false : query('SELECT * FROM orders WHERE id = ?', [$attempt['order_id']])->fetch(); if ($order === false) { return ['permanent', 'unknown payment']; } $result = read_payment($paymentReference); if ($result['status'] !== 200) { log_failure('read', $result); // 400, 401, 403, 404: fix the configuration; retrying cannot help. Network, 429 and 5xx pass. return in_array($result['status'], [400, 401, 403, 404], true) ? ['permanent', "MPS answered {$result['status']}"] : ['temporary', "MPS answered {$result['status']}"]; } [$outcome, $reason] = settle($order, $attempt, $result['body']['data']); return match ($outcome) { 'paid', 'not-paid' => ['processed', null], // shipped, or nothing to ship 'pending' => ['temporary', $reason], default => ['permanent', $reason], // short, mismatch, paid-twice: a person decides; never ship }; } // Failed rows stay for investigation: SELECT * FROM webhook_inbox WHERE status = 'failed' function record_outcome(array $row, string $outcome, ?string $error): void { if ($outcome === 'processed') { query("UPDATE webhook_inbox SET status = 'processed', last_error = NULL WHERE delivery_id = ?", [$row['delivery_id']]); return; } error_log("Inbox row {$row['delivery_id']}: $outcome failure, $error"); $attempts = $row['attempts'] + ($outcome === 'temporary' ? 1 : 0); if ($outcome === 'permanent' || $attempts >= 8) { query("UPDATE webhook_inbox SET status = 'failed', attempts = ?, last_error = ? WHERE delivery_id = ?", [$attempts, $error, $row['delivery_id']]); return; } // Back off: 10 s, 20 s, 40 s ... at most an hour. query('UPDATE webhook_inbox SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE delivery_id = ?', [$attempts, time() + min(5 * 2 ** $attempts, 3600), $error, $row['delivery_id']]); } // The one place a payment is matched to its order and settled; the return page and the worker both call it. // The read is the source of truth. Ship once, and only for the full amount. Returns [outcome, reason]. function settle(array $order, array $attempt, array $payment): array { // The key only ever reads its own merchant's payments (another merchant's is a 404), so these checks catch // a mix-up on our side: a payment reference stored against the wrong order, or another currency. foreach (['paymentReference' => $attempt['payment_reference'], 'reference' => $order['id'], 'currency' => 'EUR'] as $field => $expected) { if (($payment[$field] ?? null) !== $expected) { return ['mismatch', "$field is " . json_encode($payment[$field] ?? null) . ", expected $expected"]; } } return match ($payment['state']) { 'executed' => $payment['amount'] === $order['total'] // amount = approved amount ? mark_paid($order, $payment['paymentReference']) : ['short', "approved {$payment['amount']} of {$order['total']} cents"], 'failed', 'abandoned' => ['not-paid', null], default => ['pending', "still {$payment['state']}"], // an unknown state is never paid }; } // One atomic statement: only the call that changes the row ships. This is why a duplicate delivery, a // second worker run, or the return page racing the worker can never ship twice. Fulfilment is a placeholder // here: in a live shop, insert a fulfilment job in the same commit, then process that job with retries // and an idempotency key the downstream system accepts. function mark_paid(array $order, string $paymentReference): array { if (query('UPDATE orders SET paid_at = ?, paid_by = ? WHERE id = ? AND paid_at IS NULL', [gmdate('c'), $paymentReference, $order['id']])->rowCount() === 1) { error_log("Order {$order['id']} paid; ship it"); return ['paid', null]; } // Already paid. By this payment: a repeat, nothing to do. By another one: an earlier attempt completed // late (an ANNA payment, for example). Refund it; never ship twice. $paidBy = query('SELECT paid_by FROM orders WHERE id = ?', [$order['id']])->fetchColumn(); return $paidBy === $paymentReference ? ['paid', null] : ['paid-twice', "order already paid by $paidBy; refund $paymentReference"]; } function active_attempt(string $orderId): ?array { return query('SELECT * FROM payment_attempts WHERE order_id = ? AND active = 1', [$orderId])->fetch() ?: null; } // X-Mps-Signature: v1=, two values during a rotation. function is_valid_signature(string $timestamp, string $signatureHeader, string $body): bool { if (!ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) { return false; // a replay } $expected = hash_hmac('sha256', $timestamp . '.' . $body, env('MPS_WEBHOOK_SECRET')); foreach (explode(',', $signatureHeader) as $value) { $value = trim($value); if (str_starts_with($value, 'v1=') && hash_equals($expected, substr($value, 3))) { return true; } } return false; } function read_payment(string $paymentReference): array { return mps('GET', '/api/payments/internet/' . rawurlencode($paymentReference)); } // One call to MPS. Retries a 429 after Retry-After. Retries a 5xx or network error on a read, and on a // create that carries an Idempotency-Key: the key makes the retry return the payment the first call made. // A create without one is never retried, as it could open a second payment. function mps(string $method, string $path, ?array $payload = null, ?string $idempotencyKey = null): array { $headers = ['Authorization: Bearer ' . env('MPS_API_KEY')]; // mps_test_… or mps_live_… // Partner keys only: name the merchant on every call, the read included. Test and merchant keys: leave unset. if (getenv('MPS_WALLET_NUMBER')) { $headers[] = 'x-wallet-number: ' . getenv('MPS_WALLET_NUMBER'); } if ($payload !== null) { $headers[] = 'Content-Type: application/json'; } if ($idempotencyKey !== null) { $headers[] = 'Idempotency-Key: ' . $idempotencyKey; } $retryable = $method === 'GET' || $idempotencyKey !== null; for ($attempt = 1; ; $attempt++) { $retryAfter = null; $curl = curl_init(MPS . $path); curl_setopt_array($curl, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$retryAfter) { if (preg_match('/^Retry-After:\s*(\d+)/i', $line, $match)) { $retryAfter = (int) $match[1]; } return strlen($line); }, ]); if ($payload !== null) { curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload)); } $text = curl_exec($curl); $status = $text === false ? 0 : curl_getinfo($curl, CURLINFO_RESPONSE_CODE); if ($status === 429 && $attempt < 3 && ($retryAfter ?? 1) <= 10) { sleep($retryAfter ?? 1); continue; } if (($status === 0 || $status >= 500) && $retryable && $attempt < 4) { sleep(2 ** ($attempt - 1)); continue; } $body = $text ? json_decode($text, true) : null; // 409 idempotency_key_in_use: the first call with this key is still running; the retry returns its payment. // Any other code (idempotency_key_expired, one this code does not know, or none) is final: never retried. if ($status === 409 && $idempotencyKey !== null && $attempt < 4 && ($body['code'] ?? null) === 'idempotency_key_in_use') { sleep(1); continue; } return ['status' => $status, 'body' => $body, 'retryAfter' => $retryAfter]; } } function log_failure(string $operation, array $result): void { $status = $result['status']; if ($status === 400 && isset($result['body']['errors'])) { // A problem document: each field with its messages. Fix the request; do not retry it unchanged. foreach ($result['body']['errors'] as $field => $messages) { error_log(sprintf('MPS %s refused %s: %s', $operation, preg_replace('/^Request\./', '', $field), implode('; ', $messages))); } return; } error_log("MPS $operation: " . match ($status) { 401 => '401, the API key is missing, wrong or revoked', 403 => '403, the key lacks the scope, or x-wallet-number is not one of your merchants', 404 => '404, no such payment for this merchant', 429 => "429, rate limited; Retry-After {$result['retryAfter']}s", 0 => 'no response (network error or timeout)', default => (string) $status, }); } // One prepared statement with parameters, never SQL built from strings. function query(string $sql, array $parameters = []): PDOStatement { $statement = db()->prepare($sql); $statement->execute($parameters); return $statement; } // One connection per request (or worker run). The tables are created on first use. function db(): PDO { static $db = null; if ($db === null) { $db = new PDO('sqlite:' . DATABASE, options: [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_TIMEOUT => 5, // the server and the worker write the same file: wait for the lock ]); $db->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS orders ( id TEXT PRIMARY KEY, total INTEGER NOT NULL, -- cents paid_at TEXT, -- set once, atomically. Fulfilment is a placeholder here: see mark_paid paid_by TEXT -- the payment that paid it: a second one is refunded, never shipped ); CREATE TABLE IF NOT EXISTS payment_attempts ( -- one order, as many attempts as the shopper needs idempotency_key TEXT PRIMARY KEY, -- one per create; a retry of the same attempt sends it again order_id TEXT NOT NULL REFERENCES orders(id), payment_reference TEXT UNIQUE, -- opaque: store and compare it as a string checkout_url TEXT, -- to reopen a checkout the shopper left; whoever has it can pay active INTEGER NOT NULL DEFAULT 1, -- 1 for the attempt the shopper can still pay; older ones stay for late webhooks created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS webhook_inbox ( delivery_id TEXT PRIMARY KEY, -- X-Mps-Delivery-Id: the same on every retry, so a repeat is a no-op payment_reference TEXT NOT NULL, received_at TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', -- pending | processed | failed attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER NOT NULL, -- unix seconds last_error TEXT ); SQL); } return $db; } function uuid(): string { $bytes = random_bytes(16); $bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // version 4 $bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // RFC 4122 variant return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); } function html(string $body, int $status = 200): void { http_response_code($status); header('Content-Type: text/html; charset=utf-8'); echo "$body"; } function public_base_url(): string { return rtrim(env('PUBLIC_BASE_URL'), '/'); } function env(string $name): string { $value = getenv($name); if ($value === false || $value === '') { throw new RuntimeException("Set $name"); } return $value; } ```
### Try it [#try-it] 1. Open `PUBLIC_BASE_URL` and press **Pay EUR 19.95**: you land on the MPS checkout. 2. Pay with `4111 1111 1111 1111`, any future expiry date, any security code. The return page reads the payment and shows the order paid. A moment later the webhook arrives and is verified, and the worker finds the order already settled. 3. Try again with `4000 0000 0000 0002` for a declined payment, or `4000 0000 0000 0010` to see the page keep re-reading a payment that stays `pending`. To test the verifier on its own, feed it [the webhook you can test against](/webhooks#a-webhook-you-can-test-against) with the five-minute check switched off: its timestamp is fixed in the past.
## Security checklist - **The API key stays on your backend.** Never in a browser, an app or a POS front end. Read it from the environment or a key vault, never from source control. - **Verify every webhook** before you act on it. The webhook URL is public; the signature is what makes a request trustworthy. - **Hash the raw body.** Verify the bytes exactly as received, and parse the JSON only afterwards. - **Compare in constant time** (`CryptographicOperations.FixedTimeEquals`, `timingSafeEqual`, `hmac.compare_digest`, `hash_equals`), against **every** `v1=` value: there are two while the signing secret is rotated. - **Reject stale timestamps**: more than five minutes from your clock is a replay. - **Never log** the API key, the signing secret or `checkoutUrl`: anyone holding the checkout URL can pay that payment. - **Settle from the read, not the redirect.** Landing on your success URL proves nothing. The read endpoint is the source of truth, and an unknown `state` is never paid. - **Check the amount on `executed`.** On a partial approval it is less than you asked for. Ship only when it matches the order total. - **Be idempotent.** A webhook can arrive more than once: drop a duplicate webhook by its `X-Mps-Delivery-Id`, and settle each order by `paymentReference` once. - **Send an `Idempotency-Key` on every create**, one per checkout attempt, stored with the order before the call. Only then is it safe to retry a create that timed out. - **Store the webhook before you answer it.** After a `2xx` MPS does not send it again, so work started after answering, in a thread or a fire-and-forget task, is lost if the process stops. ## Response What each route of the production example answers: | Route | Answers | |---|---| | `GET /` | A page with a **Pay EUR 19.95** button. | | `POST /checkout` | `303` to `checkoutUrl`. If the create fails, `502` with a **Try again** button that resends the same order with the same key. | | `POST /webhooks/mps` | `401` when the signature or the timestamp fails. `200` once the webhook is stored, or when its event is not `payment.received`. `500` when it cannot store the webhook, so MPS retries. | | `GET /return?order=…` | A page: paid, approved for less than the order total, or not paid (with **Try again**). A `pending` payment is re-read every 2 seconds for about 30 seconds. `404` for an unknown order, `502` when the read fails. | ## Errors The examples log each failure of a call to MPS. What the log line means: | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | MPS refused a field of the request; the log names each field. | Fix the request; do not resend it unchanged. See [Errors and rate limits](/errors-and-rate-limits). | | `401` | — | The API key is missing, wrong or revoked. | Check `MPS_API_KEY`. See [Authentication](/authentication). Not retried. | | `403` | — | The key lacks the scope, or `x-wallet-number` is not one of your merchants. | Check the key's scopes and `MPS_WALLET_NUMBER`. See [Choosing the merchant](/authentication#choosing-the-merchant). Not retried. | | `404` | — | No such payment for this merchant. | Check that the order's `paymentReference` was made with this key. | | `409` | `idempotency_key_in_use` | On the create: the first call with this key is still running. | The examples retry after a second with the same key. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). | | `409` | `idempotency_key_expired`, or any other code | On the create: the payment this key made can no longer be returned. | Not retried. Start a new checkout attempt, with a new key. See [Conflicts](/errors-and-rate-limits#conflicts). | | `429` | — | Rate limited. | The examples retry after `Retry-After`. See [Errors and rate limits](/errors-and-rate-limits). | | `5xx` or no answer | — | MPS or the network failed. | The examples retry reads, and creates that carry an `Idempotency-Key`. | | — | — | No webhook arrives: `PUBLIC_BASE_URL` is not a public HTTPS host, or the key has no signing secret. | Put a tunnel in front of port `8000`, and check the signing secret. See [Receive webhooks](/webhooks#receiving-them). | ## Related - [Payment lifecycle](/payment-lifecycle) - [Receive webhooks](/webhooks) - [Production checklist](/production-checklist): go through it before you switch to a live key. --- # Refund a payment (/refunds) > Refund an online payment in full or in part, as many times as you need, without ever refunding more than was paid. A refund gives the shopper money back for a payment you took. One endpoint serves every payment method, so you never need to know how the shopper paid. You can refund **in full or in parts**, as many times as you need, until the paid amount is used up. Refunds move money out of your merchant's balance, so a live key does not hold `payments:refund` unless MPS granted it to that key. Ask MPS when you request the key. A **test key** always holds it, so you can build against refunds before you go live. Refunds are available for **online payments**, however the shopper paid on the checkout. The refund follows how they paid: a card payment goes back to the card, and a payment made with the ANNA QR code goes back by bank transfer. > **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. - An API key that holds the `payments:refund` scope, for refunding and for reading refunds. A test key (`mps_test_…`) always holds it. - The `paymentReference` of the payment, as the create call returned it A refund normally starts `pending` and first **waits 4 hours**, until its `cancelableUntil` (if MPS cannot schedule it, the `201` instead carries `status` `failed` with `failureReason` `unknown`, and nothing was refunded: see [Response](#response)). Money cannot be called back once it is paid out, so this is the window in which you can [cancel it](#cancel-a-refund). Then MPS sends it. A card refund is decided shortly after. A refund by bank transfer is sent only once the shopper's original transfer appears on MPS's bank statement, and stays `pending` until then; it can no longer be canceled while it waits. A payment made with ANNA is paid back to the bank account it came from, never to any other. ### Request the refund [#refund-a-payment] ```bash # Refund EUR 5.00 of a payment # Prerequisite: export MPS_API_KEY=mps_test_… curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f/refunds" \ -H "Authorization: Bearer $MPS_API_KEY" \ -H "Idempotency-Key: order-1234-refund-1" \ -H "Content-Type: application/json" \ -d '{"amount": 500, "reason": "requested_by_customer"}' ``` The gateway answers `201 Created` with the refund in `data`, normally with `status` `pending`. The `Location` header points at the refund: `/api/payments/{paymentReference}/refunds/{refundId}`. Store `refundId` with your order. Decide on `status`, not on the `201`. In rare cases the `201` already carries `status` `failed` with `failureReason` `unknown`: MPS could not schedule the refund. Nothing is refunded and the amount is free again, so you can refund it again with a new `Idempotency-Key`. Do not show such a refund as on its way. #### Request body [#request-body] The payment is the one the path names: its `paymentReference`, exactly as the create call returned it. | Field | Type | Required | Description | |---|---|---|---| | `amount` | integer | No | Amount to refund, in cents. `500` = EUR 5.00. Greater than zero and at most what is still refundable. **Omit it to refund everything still refundable.** | | `reason` | string | No | One of `duplicate`, `fraudulent`, `requested_by_customer`. | There is no merchant or wallet field: the API key decides whose payment it may refund. The currency is the payment's own. #### Headers [#headers] | Header | Required | Description | |---|---|---| | `Idempotency-Key` | No | Recommended. At most 255 characters: letters, digits and punctuation, no spaces, such as a UUID or `order-1234-refund-1`. See [Retrying safely](#retrying-safely). | ### Get a refund [#get-a-refund] Let MPS tell you the outcome, or read it. When the payment was created with a `callbackUrl`, its refunds send a [webhook](/webhooks#events) once decided: `refund.refunded`, `refund.failed` or `refund.canceled`. To read a refund: ```bash # Read one refund curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f/refunds/0b7d9c41-7f0e-4b8a-9d3c-2a1e5f6b7c8d" \ -H "Authorization: Bearer $MPS_API_KEY" ``` The gateway answers `200` with the same `data` object as the create call (see [Response](#response)). Read a `pending` refund again later. ### Cancel a refund [#cancel-a-refund] Every refund waits 4 hours before it is sent, until the `cancelableUntil` it carries, and you can cancel it until then. A canceled refund reads `canceled`, nothing is paid back, and you can refund its amount again. ```bash # Cancel a refund that was not sent yet curl -sS --fail-with-body -X DELETE "https://gateway.mps-emi.com/api/payments/test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f/refunds/0b7d9c41-7f0e-4b8a-9d3c-2a1e5f6b7c8d" \ -H "Authorization: Bearer $MPS_API_KEY" ``` | Status | Meaning | |---|---| | `204` | The refund is canceled. Canceling it again answers `204` too. | | `409` `refund_not_cancelable` | It can no longer be canceled: `cancelableUntil` has passed and it was sent, or it was already decided. | | `409` `refund_in_progress` | Other refunds of the same payment were being changed at the same moment. Nothing changed; send the cancel again. | | `404` | No such refund of this payment for this merchant. | ## List a payment's refunds ```bash # List the refunds of one payment curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f/refunds" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```json title="200 OK" { "data": [ { "refundId": "0b7d9c41-7f0e-4b8a-9d3c-2a1e5f6b7c8d", "paymentReference": "test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f", "status": "refunded", "amount": 500, "currency": "EUR", "reason": "requested_by_customer", "failureReason": null, "cancelableUntil": null, "createdAt": "2026-10-22T09:14:03Z" } ] } ``` The list is oldest first. A payment with no refunds answers an empty list. ## How much can be refunded You can refund a payment as many times as you like, but never for more than was paid: - **What is left** = the executed amount, less every refund that is `refunded` **or `pending`**. - A `failed` or `canceled` refund does not count: you can refund its amount again. - Asking for more than is left answers `400` naming `amount`, with the amount still refundable in the message. Once nothing is left, every further refund answers `400` naming `amount`. The payment's own read shows both figures. `amountRefunded` counts only refunds that are `refunded`; `amountRemaining` also subtracts the `pending` ones. Right after a refund of EUR 5.00 on a EUR 19.95 payment, while it waits its 4 hours: ```bash # Read the payment curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/internet/test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f" \ -H "Authorization: Bearer $MPS_API_KEY" ``` ```json title="200 OK" { "data": { "paymentReference": "test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f", "state": "executed", "amount": 1995, "currency": "EUR", "amountRefunded": 0, "amountRemaining": 1495, "reference": "order-1234" } } ``` Once the refund is paid out, `amountRefunded` is `500` and `amountRemaining` stays `1495`. Two refunds sent at the same moment cannot both pass when together they exceed the payment. MPS judges the second against the first one's reservation and refuses it. ## Retrying safely Send an `Idempotency-Key` with every refund, unique per refund you intend, for example `order-1234-refund-1`. If the response is lost and you send the same request again with the same key: | You resend… | You get | |---|---| | The same body, after the first finished | The **first** refund again, `201`. Nothing is refunded twice. | | The same body, while the first is **still running** | `409` with `code` `idempotency_key_in_use`. Wait a second and resend it unchanged. | | A **different** body with the same key | `400` naming `Idempotency-Key`. Use a new key for a new refund. | A refund's key belongs to its payment and is kept as long as the refund: it does not expire, so the same key on the same payment always returns that refund. A request refused as invalid (`400`) does not use up its key. Without a key, a resent request is a **new** refund, up to what is left of the payment. If a refund comes back `pending`, or your request timed out, do **not** send a new refund without the same `Idempotency-Key`. The money may already be on its way back. Read the refund (or the payment's `amountRemaining`) before you decide. ## Only your own payments An API key can refund, and read the refunds of, only payments created for **its own merchant**. A payment of another merchant, an unknown reference and a refund id that is not yours all answer the same `404`, never `403`, so nobody can probe references. The checkout URL grants nothing here: holding it lets a shopper pay, never refund. ## Test mode With a **test key**, refunds of test payments (`test-…` references) are simulated: no card is refunded and nothing is booked. A test refund waits and can be canceled exactly like a live one, and reads `refunded` once its `cancelableUntil` has passed. The response and the limits on what can be refunded are exactly as in live mode. A test key cannot refund a live payment, and a live key cannot refund a test payment: either answers `404`. ## What happens to your balance MPS books an approved refund against the merchant that received the payment. The refunded amount is taken back from its balance, together with the fee its contract sets for the payment method, calculated on the refunded amount. The balance may go below zero; the next payout settles it. ## Response The create call (`201`), Get a refund (`200`) and each item of the list carry the same refund object: ```json title="201 Created" { "data": { "refundId": "0b7d9c41-7f0e-4b8a-9d3c-2a1e5f6b7c8d", "paymentReference": "test-d3b07384-d9a0-4c9b-8f3e-2a1b5c6d7e8f", "status": "pending", "amount": 500, "currency": "EUR", "reason": "requested_by_customer", "failureReason": null, "cancelableUntil": "2026-10-22T13:14:03Z", "createdAt": "2026-10-22T09:14:03Z" } } ``` | Field | Type | Required | Description | |---|---|---|---| | `refundId` | string | Yes | The MPS refund id. Store it with your order; it is the key the read endpoint takes. | | `paymentReference` | string | Yes | The payment refunded. | | `status` | string | Yes | `refunded`, `failed`, `canceled` or `pending`. See [Statuses](#statuses). | | `amount` | integer | Yes | Refunded amount, in cents. When you omitted `amount`, this is what was still refundable. | | `currency` | string | Yes | ISO currency code of `amount`. | | `reason` | string | Yes | The reason you gave, or null. | | `failureReason` | string | Yes | Only on `failed`: `declined` or `unknown`. Null otherwise. | | `cancelableUntil` | string | Yes | On a `pending` refund that was not sent yet: until when you can [cancel it](#cancel-a-refund) (UTC). Null once it was sent or decided. | | `createdAt` | string | Yes | When the refund was requested (UTC). | Timestamps are RFC 3339 in UTC and can carry up to seven fractional digits (`2026-10-31T02:20:35.2357206Z`). Parse them with a parser that accepts fractions of a second; do not expect whole seconds. ### Statuses | `status` | Meaning | Final? | |---|---|---| | `refunded` | It was paid back: the shopper gets the money back on their card or bank account. | Yes | | `failed` | It was refused (`declined`) or could not be sent (`unknown`). Nothing was refunded; the amount is free to refund again. | Yes | | `canceled` | You [canceled](#cancel-a-refund) it before it was sent. Nothing was refunded; the amount is free to refund again. | Yes | | `pending` | The outcome is not known yet. The amount stays reserved until it is. A refund by bank transfer stays `pending` until the original transfer appears on MPS's bank statement. | No | Read a `pending` refund again later with [Get a refund](#get-a-refund). Treat any status you do not recognise as `pending`. ## Errors | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | The body names the field: a malformed `paymentReference` in the path, `amount` zero or less or more than is left, nothing left to refund, or an unknown `reason`. | Fix the named field. See [How much can be refunded](#how-much-can-be-refunded). | | `400` | — | An `Idempotency-Key` reused for a different request, or one with spaces or other characters than letters, digits and punctuation. | Use a new key for a new refund, of letters, digits and punctuation only. See [Retrying safely](#retrying-safely). | | `401` | — | No API key, or a wrong or revoked one. | Send a valid key. See [Authentication](/authentication). | | `403` | — | The API key lacks `payments:refund`, or names no single merchant wallet. Checked before the body. | Ask MPS to grant `payments:refund` to the key. A partner key names the merchant with `x-wallet-number`: see [Choosing the merchant](/authentication#choosing-the-merchant). | | `404` | — | No such payment for this merchant, no such refund under it, or a test key used on a live payment (or the reverse). | Check the reference and the key's mode. See [Only your own payments](#only-your-own-payments). | | `409` | `payment_not_refundable` | The payment is not `executed`. | Do not retry. See [Conflicts](/errors-and-rate-limits#conflicts). | | `409` | `idempotency_key_in_use` | The first request with this key is still running. | Retry after a second with the same key and body. See [Retrying safely](#retrying-safely). | | `409` | `refund_in_progress` | Another refund of the same payment is being changed at the same moment. | Retry after a second. See [Conflicts](/errors-and-rate-limits#conflicts). | | `409` | `refund_not_cancelable` | On cancel: the refund was sent or decided. | Do not retry; [read the refund](#get-a-refund). | | `429` | — | Rate limited. | Wait for `Retry-After`, then retry. See [Errors and rate limits](/errors-and-rate-limits). | ## Related - [Follow a payment's timeline](/payment-timeline): every step of a payment's refunds - [Receive refund outcomes as webhooks](/webhooks#events) - [Payment lifecycle](/payment-lifecycle) - [Errors and rate limits](/errors-and-rate-limits) - [Production checklist](/production-checklist) --- # Follow a payment's timeline (/payment-timeline) > Read every step a payment went through, and list your payments with their current state, to explain a result to a shopper or your support team. The timeline shows what happened to each of your payments, in order: you created it, the shopper opened the checkout and paid or did not, MPS sent your webhook, and any refund. Use it to follow a payment and to explain a result. Decide on a payment from [the payment read](/online-payments#read-the-outcome), never from the timeline. The timeline is written after each step, so it can trail real time by a few seconds, and a step is occasionally missing. Never build a decision on the absence of a step. > **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. - An API key that holds the `internet:read` scope: the scope that reads a payment. Every test key and live key holds it. - A payment you created with that key, for one payment's timeline. Your key sees only its own merchant's payments, and only those of its mode: a test key sees test payments, a live key live payments. ### List your payments [#list-payments] ```bash # List your payments, newest first, 25 at a time # Prerequisite: export MPS_API_KEY=mps_test_… curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/timeline?limit=25" \ -H "Authorization: Bearer $MPS_API_KEY" ``` The gateway answers `200 OK` with one page of your payments in `data.items`, each with its current state and no steps. An empty page is an empty `items` array. #### Query parameters [#query-parameters] | Field | Type | Required | Description | |---|---|---|---| | `limit` | integer | No | How many payments a page holds, from `1` to `100`. Defaults to `25`. A larger value is refused, not cut. | | `continuationToken` | string | No | The `continuationToken` the previous page returned, unchanged. Leave it out for the first page. | ### Read the next page [#read-the-next-page] ```bash # Read the page after the one that returned this continuationToken # Prerequisite: export MPS_API_KEY=mps_test_… CONTINUATION_TOKEN=… curl -sS --fail-with-body -G "https://gateway.mps-emi.com/api/payments/timeline" \ -H "Authorization: Bearer $MPS_API_KEY" \ --data-urlencode "limit=25" \ --data-urlencode "continuationToken=$CONTINUATION_TOKEN" ``` Pass `continuationToken` back exactly as you received it: it is opaque, so never build or change one. The last page has no `continuationToken`. Any other value is a `400` that names `continuationToken`. ### Read one payment's timeline [#read-a-payment-timeline] ```bash # Read every step of one payment # Prerequisite: export MPS_API_KEY=mps_test_… PAYMENT_REFERENCE=test-… curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/$PAYMENT_REFERENCE/timeline" \ -H "Authorization: Bearer $MPS_API_KEY" ``` The gateway answers `200 OK` with the payment's current state in `data.payment` and its steps in `data.events`, oldest first. Use the `paymentReference` exactly as create returned it. ## Response [#response] ### A payment [#payment] In each item of the list, and in `data.payment` of one payment's timeline. A field with no value is `null`; the examples show only the fields with a value. | Field | Type | Description | |---|---|---| | `paymentReference` | string | The payment reference create returned. An opaque string: never parse it. | | `reference` | string | Your own order reference, as you sent it on create. | | `status` | string | `pending`, `executed`, `failed` or `abandoned`: the same words the payment read uses. More values may appear. | | `reasonCode` | string | Why the payment, or its last attempt, did not succeed. See [Reason codes](#reason-codes). | | `amount` | integer | The amount in euro cents, as created. | | `currency` | string | The ISO currency code. | | `method` | string | `card`, or `bank_transfer` for a payment the shopper authorised at their bank. Absent until the shopper pays. | | `createdAt` | string | When the payment was created. Absent only while its creation step has not arrived. | | `updatedAt` | string | When anything last happened to the payment. | ```json title="200 OK, list" { "data": { "items": [ { "paymentReference": "test-00000000-0000-4000-8000-000000000002", "reference": "order-1043", "status": "abandoned", "reasonCode": "abandoned", "amount": 1200, "currency": "EUR", "createdAt": "2026-11-20T09:40:11+00:00", "updatedAt": "2026-11-21T09:40:11+00:00" }, { "paymentReference": "test-00000000-0000-4000-8000-000000000001", "reference": "order-1042", "status": "executed", "amount": 2495, "currency": "EUR", "method": "card", "createdAt": "2026-11-20T09:14:02+00:00", "updatedAt": "2026-11-20T09:15:31+00:00" } ], "continuationToken": "W3sidG9rZW4iOiIxIn1d" } } ``` ### A step [#step] In `data.events` of one payment's timeline. A field with no value is `null`; the examples show only the fields with a value. | Field | Type | Description | |---|---|---| | `type` | string | The step. See [Step types](#step-types). | | `occurredAt` | string | When the step happened. Steps can arrive late, so order them by this field. | | `reasonCode` | string | On a step that did not succeed. See [Reason codes](#reason-codes). | | `amount` | integer | The amount in euro cents, where the step carries one. | | `currency` | string | The ISO currency code, where the step carries an amount. | | `method` | string | `card` or `bank_transfer`, where known. | | `cardBrand` | string | The card scheme on a card step, such as `visa`, `mastercard` or `bancontact`. Never a digit of the card. | | `webhookHttpStatus` | integer | On `WebhookAttempted`: the HTTP status your `callbackUrl` answered. | | `webhookDurationMs` | integer | On `WebhookAttempted`: how long your server took to answer, in milliseconds. | | `webhookAttempt` | integer | On `WebhookAttempted`: the delivery attempt, starting at `1`. | | `refundId` | string | On a refund step: the `refundId` the refund request returned. | ```json title="200 OK, one payment" { "data": { "payment": { "paymentReference": "test-00000000-0000-4000-8000-000000000001", "reference": "order-1042", "status": "executed", "amount": 2495, "currency": "EUR", "method": "card", "createdAt": "2026-11-20T09:14:02+00:00", "updatedAt": "2026-11-20T09:15:31+00:00" }, "events": [ { "type": "PaymentCreated", "occurredAt": "2026-11-20T09:14:02+00:00", "amount": 2495, "currency": "EUR" }, { "type": "CheckoutOpened", "occurredAt": "2026-11-20T09:14:05+00:00" }, { "type": "CardSubmitted", "occurredAt": "2026-11-20T09:14:40+00:00", "method": "card", "cardBrand": "visa" }, { "type": "PaymentAuthorised", "occurredAt": "2026-11-20T09:15:22+00:00", "amount": 2495, "currency": "EUR", "method": "card", "cardBrand": "visa" }, { "type": "WebhookAttempted", "occurredAt": "2026-11-20T09:15:31+00:00", "webhookHttpStatus": 200, "webhookDurationMs": 184, "webhookAttempt": 1 } ] } } ``` ### Step types [#step-types] More step types may appear. Ignore a type you do not know. | `type` | When | |---|---| | `PaymentCreated` | You created the payment. | | `CheckoutOpened` | The shopper opened the checkout. Recorded each time they open it. | | `CardSubmitted` | The shopper submitted a card on the checkout. | | `RedirectedToBank` | The shopper was sent to their bank to pay by bank transfer. | | `ScaStarted` | The shopper's bank asked for a 3-D Secure check (SCA). | | `ScaCompleted` | The 3-D Secure check finished. | | `PaymentAttemptFailed` | One attempt did not succeed. The payment is still open. | | `PaymentAuthorised` | The money was collected. | | `PaymentFailed` | The payment did not complete. | | `PaymentAbandoned` | Nothing was paid within the time the payment stays open. | | `WebhookAttempted` | MPS sent a webhook to your `callbackUrl`, with the status, the duration and the attempt number. | | `RefundRequested` | You asked for a [refund](/refunds), with its amount and `refundId`. | | `RefundCanceled` | You [canceled the refund](/refunds#cancel-a-refund) before it was sent. Nothing is paid back. | | `RefundAwaitingFunds` | The refund waits: a payment made by bank transfer is paid back only once the transfer has reached MPS. | | `FundsReceived` | The bank transfer reached MPS. | | `Refunded` | The refund was paid out, with its amount and `refundId`. | | `RefundFailed` | The refund was not paid out. | Not every payment has every step. A card payment has no `RedirectedToBank`, and a payment paid on the first attempt has no `PaymentAttemptFailed`. ### Reason codes [#reason-codes] A payment or a step that did not succeed carries a `reasonCode` from this list. A new code is announced in the [changelog](/changelog). | `reasonCode` | Meaning | |---|---| | `declined_by_issuer` | The card issuer declined the payment. | | `sca_cancelled_by_customer` | The shopper cancelled the 3-D Secure check. | | `sca_failed` | The 3-D Secure check did not succeed. | | `rejected_by_bank` | The shopper's bank rejected the transfer. | | `interrupted` | The shopper left the bank's flow before it finished. | | `abandoned` | Nothing was paid within the time the payment stays open. | | `technical_error` | A system on the way could not process the payment. | | `unknown` | The payment did not succeed for a reason outside this list. | The timeline shows what you need to follow a payment, and nothing of how MPS processed it: no identifiers or codes of the card processor or the bank, no internal trace, and not the body of the webhook. If MPS support needs more, give them the payment reference. ## Errors [#errors] | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | `limit` is outside `1` to `100`, or `continuationToken` is not a value a page returned. The body names the field. | Fix the field the error names. For `continuationToken`, start again from the first page. See [Validation errors](/errors-and-rate-limits#validation-errors). | | `401` | — | No API key, or an unknown one. | Send a valid key as `Authorization: Bearer`. | | `403` | — | The key lacks the `internet:read` scope, or a partner's key sent no `x-wallet-number`. | Ask MPS for the scope, or name the merchant (see [Choosing the merchant](/authentication#choosing-the-merchant)). | | `404` | — | No such payment for this merchant in this mode: unknown, another merchant's, or a test payment read with a live key (and the reverse). | Check the payment reference and the key. The answer never says which of these it is. | | `429` | — | More than 100 requests a minute from this key. | Wait for the `Retry-After` seconds. See [Rate limits](/errors-and-rate-limits#rate-limits). | ## Related [#related] - [Payment lifecycle](/payment-lifecycle): what each `status` means, and which ones are final. - [Webhooks](/webhooks): the webhook a `WebhookAttempted` step records. - [Refund a payment](/refunds): the refunds whose steps appear on the timeline. - [Accept a payment](/online-payments): the payment read that decides whether a payment is paid. --- # Create a payment link with the API (/payment-links-api) > Make a one-time payment link for a fixed amount with your API key, send it to a shopper, and follow whether it is paid. A payment link asks one shopper for one payment of a fixed amount. You make it with the API, send the returned `url` to the shopper, and read the link to see whether it was paid. The shopper pays on the MPS **checkout**, so you never handle a card. The same links are also made on the MPS platform, without code: see [Send a payment link](/payment-links). A **test key** (`mps_test_…`) makes test links: they charge nothing and you can pay them yourself. A **live key** (`mps_live_…`) makes live links, which take real money into your balance. A partner's key makes **test links only**: a live link is made by the merchant itself. > **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. - An API key that holds the `payment-links:create` and `payment-links:read` scopes. A key issued from this release on holds them; for an older key, ask MPS to add them. - For a live link: your merchant's shop name on the MPS platform, which the shopper sees on the checkout. A link without one is refused. A link is **single use** and stays open for the number of days you choose, 10 by default and 90 at most. It stops opening payments when it is **paid**, **canceled** or **expired**. Paid is final. ### Create the link [#create-a-payment-link] ```bash # Make a link for EUR 19.95, open for 10 days # Prerequisite: export MPS_API_KEY=mps_test_… curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/payments/payment-links" \ -H "Authorization: Bearer $MPS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"amount": 1995, "reference": "INV-42", "expiresInDays": 10, "locale": "nl"}' ``` The gateway answers `201 Created` with the link in `data`. The `Location` header points at the link. Store `id` with your invoice, and send the shopper `url`. #### Request body [#request-body] | Field | Type | Required | Description | |---|---|---|---| | `amount` | integer | Yes | Amount in euro cents, from `1` to `5000000`. `1995` = EUR 19.95. | | `reference` | string | Yes | Your reference, shown to the shopper and in your list. Letters A-Z, digits, spaces and `. _ : / # + -`; at most 64 characters. | | `expiresInDays` | integer | No | Days the link stays open, from `1` to `90`. Defaults to `10`. | | `locale` | string | No | `en`, `nl` or `fr`: the language of the link page and the checkout. Without it, the shopper's browser decides. | The merchant, the mode and the shop name come from your key. A body that names a `test` flag or a shop name has them ignored. ### Send the link [#send-the-link] Send the shopper `url`, by e-mail, chat, text message or as a QR code. It opens the checkout with your shop name, the amount and your reference. The shopper can open the link more than once: while a payment is pending on it, the link opens that same checkout, so it cannot be paid twice. ### Read the link [#read-a-payment-link] ```bash # Read one link of your merchant curl -sS --fail-with-body "https://gateway.mps-emi.com/api/payments/payment-links/k3Qz9aVbN2xR7wYc1dFgHw" \ -H "Authorization: Bearer $MPS_API_KEY" ``` To list your links, newest first, call `GET https://gateway.mps-emi.com/api/payments/payment-links` with the same header. Read a link again until its `state` is no longer `open`. ### Cancel the link [#cancel-a-payment-link] ```bash # Stop an open link opening payments curl -sS --fail-with-body -X DELETE "https://gateway.mps-emi.com/api/payments/payment-links/k3Qz9aVbN2xR7wYc1dFgHw" \ -H "Authorization: Bearer $MPS_API_KEY" ``` A canceled link opens no new payment. A payment already on its checkout can still be paid, and then the link reads `paid`: cancelling never turns a paid payment into anything else. Canceling a canceled link answers `204` again. ## Response [#response] A link in `data`: | Field | Type | Description | |---|---|---| | `id` | string | The link's identifier. An opaque string: never parse it. | | `url` | string | The address to send the shopper to. | | `amount` | integer | The amount in euro cents. | | `reference` | string | Your reference, as you sent it. | | `state` | string | `open`, `paid`, `canceled` or `expired`. Paid is final. | | `test` | boolean | `true` for a test link. | | `createdAt` | string | When the link was made. | | `expiresAt` | string | When the link stops opening payments. | | `paidAt` | string or null | When the link was paid. | | `canceledAt` | string or null | When the link was canceled. | | `paymentReference` | string or null | The payment the link was paid by. | | `payments` | array | Every payment the link opened, oldest first, each with its `paymentReference` and `state`. | | `locale` | string or null | The language the link page opens in. | ```json title="201 Created" { "data": { "id": "k3Qz9aVbN2xR7wYc1dFgHw", "url": "https://pay.mps-emi.com/link/k3Qz9aVbN2xR7wYc1dFgHw", "amount": 1995, "reference": "INV-42", "state": "open", "test": true, "createdAt": "2026-11-18T09:14:03Z", "expiresAt": "2026-11-28T09:14:03Z", "paidAt": null, "canceledAt": null, "paymentReference": null, "payments": [], "locale": "nl" } } ``` ## Errors [#errors] | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | A field is out of range, or the reference is missing or has characters not allowed. The body names the field. | Fix the field the error names. | | `401` | — | No API key, or an unknown one. | Send a valid key as `Authorization: Bearer`. | | `403` | — | The key lacks the scope, or a partner's key sent no `x-wallet-number`. | Ask MPS for the scope, or name the merchant (see [Choosing the merchant](/authentication#choosing-the-merchant)). | | `403` | `payment_link_live_partner` | A partner's key asked for a live link. | Make a test link, or have the merchant make the live link itself. | | `404` | — | No such link for this merchant. | The same answer as for a link that does not exist. | | `409` | `payment_link_unnamed` | The merchant has no shop name, which the shopper would see. | Ask MPS to set the shop name, then try again. | | `409` | `payment_link_not_open` | The link is paid or expired, so it cannot be canceled. | Nothing to cancel. Make a new link if the shopper still needs to pay. | | `429` | — | More than 100 requests a minute from this key. | Wait for the `Retry-After` seconds. | ## Related [#related] - [Send a payment link](/payment-links): the same links, made on the MPS platform without code. - [Accept a payment](/online-payments): the payment a link opens, and its states. - [Webhooks](/webhooks): MPS's signed webhook when a payment is received. - [Authentication](/authentication): API keys, scopes and the test and live modes. --- # Create a registration link (/registration-links) > Send a company to MPS's signup with a personal registration link, as a live partner, and follow whether it was used. A registration link sends one company to the MPS signup, with your partner reference on it. You make it with the API for one company and one e-mail address, send the returned `url` to that company's contact, and read the link to see whether they signed up. Only a **live partner's** key can do this. The live key you make for yourself as a live partner holds the `registration-links:manage` scope from the start. A merchant's key, a key you make for one of your merchants, and a test key never hold it. A registration link names a real company and a real e-mail address and sends a real signup, so there is no test mode. A key without the scope, or a partner that is not live, is refused. > **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. - A live key of your own as a live partner, made on the MPS platform under **Online › API keys**. It holds `registration-links:manage` from the start. - The company's country, company number and name, and the e-mail address of the person who signs up. A partner usually has no shop, so its own live key needs no shop name. Such a key takes no payments: an online payment made with it answers `403`, and a payment link answers `409` with code `payment_link_unnamed`. The return address the signup sends the company back to is not proof that the company signed up. It can be reached without finishing the signup, and it can be missed. Read the link's `status` from the API to find out whether the signup was completed. ### Create the link [#create-a-registration-link] ```bash # Make a registration link for one company # Prerequisite: export MPS_API_KEY=mps_live_… curl -sS --fail-with-body -X POST "https://gateway.mps-emi.com/api/partners/registration-links" \ -H "Authorization: Bearer $MPS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"country": "BE", "companyNumber": "0123456749", "companyName": "Bakkerij De Molen BV", "email": "contact@example.com", "language": "nl", "partnerReference": "CRM-1042"}' ``` The gateway answers `201 Created` with the link in `data`. The `Location` header points at the link. Send the company `url`: it is the address the company opens to sign up, and it already carries the link's `code`. Store `id` and `url` with the company's record. ```json title="201 Created" { "data": { "id": "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b", "code": "K7mQ2xP9wRtN4bZc", "status": "open", "country": "BE", "companyNumber": "0123456749", "companyName": "Bakkerij De Molen BV", "email": "contact@example.com", "language": "nl", "partnerReference": "CRM-1042", "createdAt": "2026-11-18T09:14:03Z", "expiresAt": "2026-11-28T09:14:03Z", "revokedAt": null, "usedAt": null, "completedAt": null, "returnUrl": null, "url": "https://main.mps-emi.com/signup?partner=K7mQ2xP9wRtN4bZc" } } ``` #### Request body [#request-body] | Field | Type | Required | Description | |---|---|---|---| | `country` | string | Yes | The company's country, as ISO 3166-1 alpha-2, such as `BE`. | | `companyNumber` | string | Yes | The company's number in its register. | | `companyName` | string | Yes | The company's name, as the signup shows it. | | `email` | string | Yes | The e-mail address of the person who signs up. | | `language` | string | Yes | `en`, `nl` or `fr`: the language of the signup. | | `partnerReference` | string | No | Your reference for the company, kept with the link. | | `expiresInDays` | integer | No | Days the link stays open, from `1` to `90`. Defaults to `30`. | The company is looked up in the register when the register answers, and the link is made either way. A company that already has an open registration link cannot get a second one: revoke the first. ### Read the links [#read-registration-links] ```bash # List your registration links that are still open curl -sS --fail-with-body "https://gateway.mps-emi.com/api/partners/registration-links?status=open" \ -H "Authorization: Bearer $MPS_API_KEY" ``` The list answers the links in `data`, newest first, with `totalCount`, `page` and `pageSize` beside them. Filter with `status`: `open`, `used`, `completed`, `expired` or `revoked`. Ask for another page with `page` (from `1`) and `pageSize` (`25` by default, `100` at most). Read one link with `GET https://gateway.mps-emi.com/api/partners/registration-links/{id}`: it answers the link in `data`. ### Revoke a link [#revoke-a-registration-link] ```bash # Revoke a link nobody has signed up with yet curl -sS --fail-with-body -X DELETE "https://gateway.mps-emi.com/api/partners/registration-links/6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" \ -H "Authorization: Bearer $MPS_API_KEY" ``` Revoking answers `204`. Once someone has signed up with the link, it can no longer be revoked and the answer is `409`. ## Response [#response] A link in `data`: | Field | Type | Description | |---|---|---| | `id` | string | The link's identifier. Opaque: never parse it. | | `url` | string | The address the company opens to sign up, with the link's `code`. Send this to the company. Null when MPS has not configured the signup address, which the gateway refuses on create rather than returning a link without it. | | `code` | string | The code in the `url`. | | `status` | string | `open`, `used`, `completed`, `expired` or `revoked`. | | `country` | string | The company's country. | | `companyNumber` | string | The company's number. | | `companyName` | string | The company's name. | | `email` | string | The e-mail address the link was made for. | | `language` | string | The signup's language. | | `partnerReference` | string or null | Your reference. | | `createdAt` | string | When the link was made. | | `expiresAt` | string | When the link stops working. | | `revokedAt` | string or null | When the link was revoked. | | `usedAt` | string or null | When somebody first used the link. | | `completedAt` | string or null | When the signup was completed. | ## Errors [#errors] | Status | Code | Cause | Resolution | |---|---|---|---| | `400` | — | A field is missing or invalid, or `status` is not one of the values above. The body names the field. | Fix the field the error names. | | `401` | — | No API key, or an unknown one. | Send a valid key as `Authorization: Bearer`. | | `403` | — | The key does not carry `registration-links:manage`, or its partner is not live. | Use the live key you made for yourself as a live partner. A merchant's key and a test key never hold the scope. | | `404` | — | No such link for this partner. | The same answer as for a link that does not exist. | | `409` | — | The link has been used, so it cannot be revoked. | Nothing to revoke. Read the link's `status`. | | `429` | — | More than 100 requests a minute from this key. | Wait for the `Retry-After` seconds. | ## Related [#related] - [Authentication](/authentication): API keys and scopes. - [Create a payment link with the API](/payment-links-api): payments for a shopper, rather than a company's signup. - [Errors and rate limits](/errors-and-rate-limits): the problem format and the retry rules. --- # Production checklist (/production-checklist) > What to check before you switch to a live key, each check linking to the page that explains it. Go through this list before you swap your test key for a live key. Each line links to where it is explained. Nothing here is new. - [ ] **The live key is kept on your backend**, in your key store, and read from there. [Keep the key on your backend](/authentication#keep-the-key-on-your-backend) - [ ] **No key reaches a browser or an app.** Every call to MPS comes from your server. [Test keys and live keys](/authentication#test-and-production-keys) - [ ] **Every create sends an `Idempotency-Key`**, stored with the checkout attempt before the call, and a retry sends the same one. [Retrying safely](/online-payments#retrying-safely-idempotency-key) - [ ] **Webhooks are verified**: signature over the raw body, timestamp within five minutes. Your live key has its own signing secret, and `callbackUrl` is a public `https://` address. [Validating the signature](/webhooks#validating-the-signature) · [The signing secret](/webhooks#the-signing-secret) - [ ] **The outcome comes from the read**, not from the return URL or the webhook body. [Read the outcome](/online-payments#read-the-outcome) - [ ] **`amount` and `currency` are compared with the order** before you ship. A partial approval reports less than you asked for. [`executed`](/payment-lifecycle#executed) - [ ] **An order is fulfilled once**, whatever arrives twice: a repeated webhook, or the return and the webhook together. [Processing them reliably](/webhooks#processing-them-reliably) - [ ] **`401`, `403`, `429` and `5xx` are handled**: the first two are configuration and not retried, the last two are retried with backoff. [Retry policy](/errors-and-rate-limits#retry-policy) - [ ] **A paid, a declined and a pending payment have been tried** with the test cards, through your own checkout. [Test mode](/online-payments#test-mode) - [ ] **Orders you heard nothing about are reconciled** by reading them, until they are decided. [Reconcile what you did not hear about](/payment-lifecycle#reconcile-what-you-did-not-hear-about) - [ ] **A `payment.received` for an order you closed is still handled**: a late ANNA payment can turn a `failed` or `abandoned` payment `executed`. [A late ANNA payment](/payment-lifecycle#a-late-anna-payment) Then create a live key under **Online › API keys** on the MPS platform, in **Live** mode. It can be created once the merchant has signed its contract with MPS; the screen says so while it has not. Test mode and live mode use the same hosts and the same calls: only the key changes. Not building your own integration? [Switch to live payments](/take-live-payments) covers payment links and the shop plugins. ## Related - [Payment lifecycle](/payment-lifecycle): every state and what to do with it - [Webhooks](/webhooks): receive and verify webhooks - [Integration examples](/integration-examples): one runnable server in C#, TypeScript, Python and PHP - [Errors and rate limits](/errors-and-rate-limits): what to retry and what not to --- # API reference (/api-reference) > Every public endpoint with its parameters, request and response schemas and code samples, generated from the gateway's OpenAPI document. These pages are generated from the gateway's own OpenAPI document each time the documentation is published, so they describe exactly the endpoints it serves. The guides explain how to use them together; this section is the contract, one endpoint at a time. > **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. ## Conventions | | | |---|---| | Base URL | `https://gateway.mps-emi.com`. Test keys and live keys use the same host; the key decides. See [The hosts](/overview#the-hosts). | | Authentication | `Authorization: Bearer mps_test_…` on every payment call: your API key (`mps_live_…` / `mps_test_…`). A partner key adds `x-wallet-number`. See [Authentication](/authentication). | | Request bodies | JSON (`Content-Type: application/json`). | | Responses | JSON. A payment endpoint wraps its result in `data`. | | Amounts | Integers in euro cents: `1995` is EUR 19.95. | | Identifiers | `paymentReference` is an opaque string. Store and compare them exactly as returned. | | Idempotency | Send an `Idempotency-Key` on a create, and a retry with the same key and body returns the first payment instead of opening a second one. Without a key every create opens a new payment. See [Retrying safely](/online-payments#retrying-safely-idempotency-key). | | Webhooks | Signed POST requests to the payment's `callbackUrl`: `payment.received`, and `refund.refunded` / `refund.failed` / `refund.canceled`. Documented in the `callbacks` of Create an online payment; see [Webhooks](/webhooks). | | Errors | `400` is a problem document naming the field. Every problem response of the payments API carries `traceId` and `documentationUrl`, a link to the section that resolves it. `401`, `403`, `404` and `429` carry no body, except the `403` for an `x-wallet-number` your key does not cover. See [Errors and rate limits](/errors-and-rate-limits). | | Rate limits | 100 requests a minute per API key, across every endpoint. See [Rate limits](/errors-and-rate-limits#rate-limits). | ## The OpenAPI document Download the document these pages are built from at [`/openapi.json`](/openapi.json). It is OpenAPI 3.0 and loads in Postman, Insomnia, Bruno or any code generator, ready to call `https://gateway.mps-emi.com`. ## Related - [Accept a payment](/online-payments) - [Payment lifecycle](/payment-lifecycle) - [Errors and rate limits](/errors-and-rate-limits) - [Build a request](/api-reference/playground) --- # Get a payment link (/api-reference/payment-links/payment-links-get) > Reads one payment link of the key's merchant. Answers 404 for a link of another merchant, the same answer as for a link that does not exist. Requires the `payment-links:read` scope. `GET https://gateway.mps-emi.com/api/payments/payment-links/{id}` ```json { "tags": [ "Payment links" ], "summary": "Get a payment link", "description": "Reads one payment link of the key's merchant. Answers 404 for a link of another merchant, the same answer as for a link that does not exist.\n\nRequires the `payment-links:read` scope.", "operationId": "payment-links-get", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "id", "in": "path", "description": "The link's id, exactly as create returned it. An opaque string: never parse it.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "k3Qz9aVbN2xR7wYc1dFgHw" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfApiPaymentLinkResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payment-links:read scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "Not Found", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Cancel a payment link (/api-reference/payment-links/payment-links-cancel) > Stops an open payment link opening payments. Canceling a canceled link answers 204 again. Answers 409 with code payment_link_not_open once the link is paid or expired: a payment already on its checkout can still be paid, and a paid link stays paid. Answers 404 for a link of another merchant. Requires the `payment-links:create` scope. `DELETE https://gateway.mps-emi.com/api/payments/payment-links/{id}` ```json { "tags": [ "Payment links" ], "summary": "Cancel a payment link", "description": "Stops an open payment link opening payments. Canceling a canceled link answers 204 again. Answers 409 with code payment_link_not_open once the link is paid or expired: a payment already on its checkout can still be paid, and a paid link stays paid. Answers 404 for a link of another merchant.\n\nRequires the `payment-links:create` scope.", "operationId": "payment-links-cancel", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "id", "in": "path", "description": "The link's id, exactly as create returned it. An opaque string: never parse it.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "k3Qz9aVbN2xR7wYc1dFgHw" } } } ], "responses": { "204": { "description": "No Content", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payment-links:create scope, or a partner key sent no x-wallet-number: no body. A partner's key asking for a live link is answered 403 with the code payment_link_live_partner. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "Not Found", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "409": { "description": "Conflict", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ConflictProblem" } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # List payment links (/api-reference/payment-links/payment-links-list) > Lists the payment links of the key's merchant, newest first. Reads count toward the 100 requests a minute. Requires the `payment-links:read` scope. `GET https://gateway.mps-emi.com/api/payments/payment-links` ```json { "tags": [ "Payment links" ], "summary": "List payment links", "description": "Lists the payment links of the key's merchant, newest first. Reads count toward the 100 requests a minute.\n\nRequires the `payment-links:read` scope.", "operationId": "payment-links-list", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfIReadOnlyListOfApiPaymentLinkResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payment-links:read scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Create a payment link (/api-reference/payment-links/payment-links-create) > Makes a single-use payment link for a fixed amount and returns the address to send the shopper to. The link is test or live as the key is: a test key makes test links, a live key makes live links. A partner's key makes test links only, and a link with no shop name on record is a 409 naming payment_link_unnamed. A link stops opening payments once it is paid, canceled or expired. Requires the `payment-links:create` scope. `POST https://gateway.mps-emi.com/api/payments/payment-links` ```json { "tags": [ "Payment links" ], "summary": "Create a payment link", "description": "Makes a single-use payment link for a fixed amount and returns the address to send the shopper to. The link is test or live as the key is: a test key makes test links, a live key makes live links. A partner's key makes test links only, and a link with no shop name on record is a 409 naming payment_link_unnamed. A link stops opening payments once it is paid, canceled or expired.\n\nRequires the `payment-links:create` scope.", "operationId": "payment-links-create", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateApiPaymentLinkRequest" } } }, "required": true }, "responses": { "201": { "description": "Created", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfApiPaymentLinkResponse" } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payment-links:create scope, or a partner key sent no x-wallet-number: no body. A partner's key asking for a live link is answered 403 with the code payment_link_live_partner. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "409": { "description": "Conflict", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ConflictProblem" } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Create an online payment (/api-reference/online-payments/payments-internet-create) > Opens an online payment and returns the page to send the shopper to. Every call opens a new payment unless it carries an Idempotency-Key (or X-Idempotency-Key): a retry with the same key and the same body returns the payment the first call made, for 24 hours. The same key with a different body is a 400 naming Idempotency-Key; a retry while the first call is still running is a 409. Requires the `internet:create` scope. `POST https://gateway.mps-emi.com/api/payments/internet/create` ```json { "tags": [ "Online payments" ], "summary": "Create an online payment", "description": "Opens an online payment and returns the page to send the shopper to. Every call opens a new payment unless it carries an Idempotency-Key (or X-Idempotency-Key): a retry with the same key and the same body returns the payment the first call made, for 24 hours. The same key with a different body is a 400 naming Idempotency-Key; a retry while the first call is still running is a 409.\n\nRequires the `internet:create` scope.", "operationId": "payments-internet-create", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "Idempotency-Key", "in": "header", "description": "One value per checkout attempt, stored with the order before the call. A retry with the same key and body within 24 hours returns the payment the first call made. Scoped to your merchant and mode.", "schema": { "maxLength": 255, "pattern": "^[!-~]+$", "type": "string" } }, { "name": "X-Idempotency-Key", "in": "header", "description": "The same key under another name, supported alongside Idempotency-Key. Send one of the two; sent together, they must carry the same key.", "schema": { "maxLength": 255, "pattern": "^[!-~]+$", "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateInternetPaymentRequest" } } }, "required": true }, "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfCreateInternetPaymentResponse" } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the internet:create scope, a partner key sent no x-wallet-number, or the merchant has no shop name registered yet (contact MPS): no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "409": { "description": "A conflict, named by code: idempotency_key_in_use (the first call with this Idempotency-Key is still running: retry it unchanged after a second) or idempotency_key_expired (its payment can no longer be returned: create a new one with a new key).", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ConflictProblem" } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "callbacks": { "webhook": { "$request.body#/callbackUrl": { "post": { "summary": "Webhook", "description": "Posted to the callbackUrl, server to server, once the payment has been received and booked (payment.received), and when a refund of it ends: refund.refunded (paid out), refund.failed (not paid out; the amount can be refunded again) or refund.canceled (canceled before it was sent). Verify X-Mps-Signature over the raw body before acting on it. Answer 2xx once the webhook is processed or durably stored: anything else, or no answer within 10 seconds, is retried. MPS never follows a redirect: a 3xx counts as failed too. A failed delivery is retried after 1m, 5m, 30m, 2h, 6h, each counted from the previous attempt: 6 attempts in all, then it is not sent again, so reconcile by reading the payment. Delivery is at least once, so key on X-Mps-Delivery-Id. The read endpoints stay authoritative.", "parameters": [ { "name": "X-Mps-Event", "in": "header", "description": "The event type, so you can route without parsing the body.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "payment.received" } } }, { "name": "X-Mps-Timestamp", "in": "header", "description": "Unix seconds. Part of the signed content; reject one more than five minutes from your clock.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "1791892800" } } }, { "name": "X-Mps-Delivery-Id", "in": "header", "description": "Identifies the webhook delivery: every retry of it carries the same value.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000003" } } }, { "name": "X-Mps-Signature", "in": "header", "description": "v1= followed by the lower-case hex HMAC-SHA256 of {X-Mps-Timestamp}.{raw body} with the signing secret of your API key. During a signing secret rotation it carries two comma-separated values; accept either.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "v1=82b9a79df151e0e9207ef421fe4085e0a0ca95f3047265a0b92701ad5011c326" } } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Webhook" } } }, "required": true }, "responses": { "2XX": { "description": "Processed, or durably stored. Answer within 10 seconds." }, "default": { "description": "Any other answer, or none within 10 seconds, counts as failed and is retried." } }, "security": [ {} ] } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Get an online payment (/api-reference/online-payments/payments-internet-get) > Reports a payment's outcome from stored state. Reads count toward the 100 requests a minute; poll at most every 2 seconds. Answers 404 for a reference not found for the API key's wallet. Requires the `internet:read` scope. `GET https://gateway.mps-emi.com/api/payments/internet/{paymentReference}` ```json { "tags": [ "Online payments" ], "summary": "Get an online payment", "description": "Reports a payment's outcome from stored state. Reads count toward the 100 requests a minute; poll at most every 2 seconds. Answers 404 for a reference not found for the API key's wallet.\n\nRequires the `internet:read` scope.", "operationId": "payments-internet-get", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned. An opaque string of up to 64 characters (a test payment's starts with test-): never parse it or validate it as a GUID.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfInternetPaymentStatusResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the internet:read scope: no body. (A partner key without x-wallet-number is answered 404.) x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "No payment with this reference for the merchant the key acts for: a typo, a reference changed on the way, another merchant's payment, or a partner key that sent no x-wallet-number. No body.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Get a payment's timeline (/api-reference/online-payments/payments-timeline-get) > Returns one payment's current state and every step it went through, oldest first. Answers 404 for a reference not found for the key's wallet, or of the other mode (a test payment read with a live key, and the reverse). Requires the `internet:read` scope. `GET https://gateway.mps-emi.com/api/payments/{paymentReference}/timeline` ```json { "tags": [ "Online payments" ], "summary": "Get a payment's timeline", "description": "Returns one payment's current state and every step it went through, oldest first. Answers 404 for a reference not found for the key's wallet, or of the other mode (a test payment read with a live key, and the reverse).\n\nRequires the `internet:read` scope.", "operationId": "payments-timeline-get", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfPaymentTimelineDetailResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the internet:read scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "Not Found", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # List payment timeline (/api-reference/online-payments/payments-timeline-list) > Lists the merchant's payments, newest first, one page at a time, each with its current state and no steps. Pass the continuationToken from a page, unchanged, to read the next; it is left out on the last page. Any other value is a 400 naming continuationToken. The timeline can trail real time by a few seconds, so it is not the source of truth for a payment's status: read the payment for that. Requires the `internet:read` scope. `GET https://gateway.mps-emi.com/api/payments/timeline` ```json { "tags": [ "Online payments" ], "summary": "List payment timeline", "description": "Lists the merchant's payments, newest first, one page at a time, each with its current state and no steps. Pass the continuationToken from a page, unchanged, to read the next; it is left out on the last page. Any other value is a 400 naming continuationToken. The timeline can trail real time by a few seconds, so it is not the source of truth for a payment's status: read the payment for that.\n\nRequires the `internet:read` scope.", "operationId": "payments-timeline-list", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "limit", "in": "query", "schema": { "type": "integer", "format": "int32" } }, { "name": "continuationToken", "in": "query", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfPaymentTimelinePageResponse" } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the internet:read scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Get a refund (/api-reference/refunds/payments-refunds-get) > Reads one refund of the payment, by the id returned when it was requested. Answers 404 for a refund of another payment, or of another merchant's. Requires the `payments:refund` scope. `GET https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds/{refundId}` ```json { "tags": [ "Refunds" ], "summary": "Get a refund", "description": "Reads one refund of the payment, by the id returned when it was requested. Answers 404 for a refund of another payment, or of another merchant's.\n\nRequires the `payments:refund` scope.", "operationId": "payments-refunds-get", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } }, { "name": "refundId", "in": "path", "description": "The refundId the refund request returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "3f2b8c1e-6d4a-4f7e-9b21-5c8d0e7a4b19" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfRefundResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payments:refund scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "No such refund of this payment for this merchant (a refund of another payment, or of another merchant's, answers the same). No body.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Cancel a refund (/api-reference/refunds/payments-refunds-cancel) > Cancels a refund of the payment that has not been sent yet. Every refund waits until its cancelableUntil (4 hours) before it is sent, and can be canceled until then; it then reads canceled, and its amount can be refunded again. Answers 204 when canceled (also for a refund canceled before), 409 once it can no longer be canceled (after cancelableUntil, or once decided) or while other refunds of the payment are being changed (try again), and 404 for a refund of another payment, or of another merchant's. Requires the `payments:refund` scope. `DELETE https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds/{refundId}` ```json { "tags": [ "Refunds" ], "summary": "Cancel a refund", "description": "Cancels a refund of the payment that has not been sent yet. Every refund waits until its cancelableUntil (4 hours) before it is sent, and can be canceled until then; it then reads canceled, and its amount can be refunded again. Answers 204 when canceled (also for a refund canceled before), 409 once it can no longer be canceled (after cancelableUntil, or once decided) or while other refunds of the payment are being changed (try again), and 404 for a refund of another payment, or of another merchant's.\n\nRequires the `payments:refund` scope.", "operationId": "payments-refunds-cancel", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } }, { "name": "refundId", "in": "path", "description": "The refundId the refund request returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "3f2b8c1e-6d4a-4f7e-9b21-5c8d0e7a4b19" } } } ], "responses": { "204": { "description": "No Content", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payments:refund scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "No such refund of this payment for this merchant (a refund of another payment, or of another merchant's, answers the same). No body.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "409": { "description": "A conflict, named by code: refund_not_cancelable (the refund was sent or decided: do not retry, read it) or refund_in_progress (other refunds of the payment are being changed: retry after a second).", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ConflictProblem" } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # List a payment's refunds (/api-reference/refunds/payments-refunds-list) > Lists the refunds of the payment, oldest first. Answers 404 for a payment belonging to another merchant. Requires the `payments:refund` scope. `GET https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds` ```json { "tags": [ "Refunds" ], "summary": "List a payment's refunds", "description": "Lists the refunds of the payment, oldest first. Answers 404 for a payment belonging to another merchant.\n\nRequires the `payments:refund` scope.", "operationId": "payments-refunds-list", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfIReadOnlyListOfRefundResponse" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payments:refund scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "No such payment for this merchant (another merchant's payment answers the same), or a test key on a live payment or the reverse. No body.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Refund a payment (/api-reference/refunds/payments-refunds-create) > Refunds the payment in full or in part, as many times as needed until the paid amount is used up. Omit the amount to refund everything still refundable. Send an Idempotency-Key header so a retry returns the first refund instead of making a second. Answers 404 rather than 403 for a payment belonging to another merchant, and 409 for a payment not yet executed. A refund is answered pending and waits 4 hours (cancelableUntil) before it is sent; it can be canceled until then. In rare cases the 201 already reads failed, with failureReason unknown: it could not be scheduled, nothing is refunded, and the amount can be refunded again with a new Idempotency-Key. Decide on status. Requires the `payments:refund` scope. `POST https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds` ```json { "tags": [ "Refunds" ], "summary": "Refund a payment", "description": "Refunds the payment in full or in part, as many times as needed until the paid amount is used up. Omit the amount to refund everything still refundable. Send an Idempotency-Key header so a retry returns the first refund instead of making a second. Answers 404 rather than 403 for a payment belonging to another merchant, and 409 for a payment not yet executed. A refund is answered pending and waits 4 hours (cancelableUntil) before it is sent; it can be canceled until then. In rare cases the 201 already reads failed, with failureReason unknown: it could not be scheduled, nothing is refunded, and the amount can be refunded again with a new Idempotency-Key. Decide on status.\n\nRequires the `payments:refund` scope.", "operationId": "payments-refunds-create", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "paymentReference", "in": "path", "description": "The paymentReference create returned, exactly as returned.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "00000000-0000-4000-8000-000000000001" } } }, { "name": "Idempotency-Key", "in": "header", "description": "One value per refund you intend. Kept with the refund, per payment, and never expires: the same key on the same payment always returns that refund. Letters, digits and punctuation, no spaces.", "schema": { "maxLength": 255, "pattern": "^[!-~]+$", "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RefundPaymentRequest" } } }, "required": true }, "responses": { "201": { "description": "Created", "headers": { "Location": { "description": "Where the refund is read: /api/payments/{paymentReference}/refunds/{refundId}.", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ResponsePayloadOfRefundResponse" }, "examples": { "pending": { "summary": "Waiting its 4 hours, cancelable until cancelableUntil", "value": { "data": { "refundId": "00000000-0000-4000-8000-000000000004", "paymentReference": "00000000-0000-4000-8000-000000000001", "status": "pending", "amount": 500, "currency": "EUR", "reason": "requested_by_customer", "failureReason": null, "cancelableUntil": "2026-10-22T13:14:03.0000000+00:00", "createdAt": "2026-10-22T09:14:03.0000000+00:00" } } }, "failed": { "summary": "Could not be scheduled: nothing is refunded, the amount is free again", "value": { "data": { "refundId": "00000000-0000-4000-8000-000000000004", "paymentReference": "00000000-0000-4000-8000-000000000001", "status": "failed", "amount": 500, "currency": "EUR", "reason": "requested_by_customer", "failureReason": "unknown", "cancelableUntil": null, "createdAt": "2026-10-22T09:14:03.0000000+00:00" } } } } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the payments:refund scope, or a partner key sent no x-wallet-number: no body. x-wallet-number names a wallet the key does not cover: the body below, error invalid_request.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "required": [ "error", "error_description" ], "type": "object", "properties": { "error": { "type": "string", "description": "invalid_request." }, "error_description": { "type": "string", "description": "Why the wallet was refused, for a person." } }, "examples": [ { "error": "invalid_request", "error_description": "The requested wallet is not covered by this key's account." } ] } } } }, "404": { "description": "No such payment for this merchant (another merchant's payment answers the same), or a test key on a live payment or the reverse. No body.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "409": { "description": "A conflict, named by code: idempotency_key_in_use (the first request with this Idempotency-Key is still running: retry it unchanged after a second), refund_in_progress (another refund of the payment is being changed: retry after a second) or payment_not_refundable (the payment is not executed: do not retry).", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ConflictProblem" } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "500": { "description": "A problem on our side, as a problem document with the traceId to quote to MPS. Other 5xx answers can carry no body. Retry a read with backoff; retry a create or refund only with the same Idempotency-Key.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ServerProblem" } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # List registration links (/api-reference/registration-links/registration-links-list) > Lists the partner's personal registration links, newest first. Filter with status: open, used, completed, expired or revoked. Reads count toward the 100 requests a minute. Requires the `registration-links:manage` scope. `GET https://gateway.mps-emi.com/api/partners/registration-links` ```json { "tags": [ "Registration links" ], "summary": "List registration links", "description": "Lists the partner's personal registration links, newest first. Filter with status: open, used, completed, expired or revoked. Reads count toward the 100 requests a minute.\n\nRequires the `registration-links:manage` scope.", "operationId": "registration-links-list", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "status", "in": "query", "schema": { "type": "string" } }, { "name": "page", "in": "query", "schema": { "type": "integer", "format": "int32" } }, { "name": "pageSize", "in": "query", "schema": { "type": "integer", "format": "int32" } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RegistrationLinkListData" } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the registration-links:manage scope, or its partner is not live: an active agent with the online channel. No body. Test keys never hold the scope.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Create a registration link (/api-reference/registration-links/registration-links-create) > Makes a personal registration link for one company and one e-mail address: it sends that company to the MPS signup. The link's url is the address the company opens to sign up: send it to the company. The company is looked up in the register when the register answers, and the link is made either way. A return to the return address is not proof that the company signed up: read the link's status. Requires the `registration-links:manage` scope. `POST https://gateway.mps-emi.com/api/partners/registration-links` ```json { "tags": [ "Registration links" ], "summary": "Create a registration link", "description": "Makes a personal registration link for one company and one e-mail address: it sends that company to the MPS signup. The link's url is the address the company opens to sign up: send it to the company. The company is looked up in the register when the register answers, and the link is made either way. A return to the return address is not proof that the company signed up: read the link's status.\n\nRequires the `registration-links:manage` scope.", "operationId": "registration-links-create", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreatePartnerRegistrationLinkRequest" } } }, "required": true }, "responses": { "201": { "description": "Created", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RegistrationLinkData" } } } }, "400": { "description": "Bad Request", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/HttpValidationProblemDetails" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the registration-links:manage scope, or its partner is not live: an active agent with the online channel. No body. Test keys never hold the scope.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Get a registration link (/api-reference/registration-links/registration-links-get) > Reads one personal registration link of the partner. Answers 404 for another partner's link, the same answer as for a link that does not exist. Requires the `registration-links:manage` scope. `GET https://gateway.mps-emi.com/api/partners/registration-links/{id}` ```json { "tags": [ "Registration links" ], "summary": "Get a registration link", "description": "Reads one personal registration link of the partner. Answers 404 for another partner's link, the same answer as for a link that does not exist.\n\nRequires the `registration-links:manage` scope.", "operationId": "registration-links-get", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "id", "in": "path", "description": "The link's id, exactly as create returned it.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" } } } ], "responses": { "200": { "description": "Success.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RegistrationLinkData" } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the registration-links:manage scope, or its partner is not live: an active agent with the online channel. No body. Test keys never hold the scope.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "404": { "description": "Not Found", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Revoke a registration link (/api-reference/registration-links/registration-links-revoke) > Revokes a personal registration link nobody has signed up with yet. Answers 409 once somebody has signed up with it. Answers 404 for another partner's link. Requires the `registration-links:manage` scope. `DELETE https://gateway.mps-emi.com/api/partners/registration-links/{id}` ```json { "tags": [ "Registration links" ], "summary": "Revoke a registration link", "description": "Revokes a personal registration link nobody has signed up with yet. Answers 409 once somebody has signed up with it. Answers 404 for another partner's link.\n\nRequires the `registration-links:manage` scope.", "operationId": "registration-links-revoke", "parameters": [ { "name": "x-wallet-number", "in": "header", "description": "Only with a partner key, on every call: the wallet of the merchant this call acts for, such as BE0000000000. A test key or a merchant key acts for its own wallet and ignores it.", "schema": { "type": "string" } }, { "name": "id", "in": "path", "description": "The link's id, exactly as create returned it.", "required": true, "schema": { "type": "string" }, "examples": { "default": { "value": "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" } } } ], "responses": { "204": { "description": "No Content", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "401": { "description": "No API key, or a wrong, malformed or revoked one: no body.", "headers": { "WWW-Authenticate": { "description": "Bearer error=\"invalid_token\".", "schema": { "type": "string" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "403": { "description": "The key does not carry the registration-links:manage scope, or its partner is not live: an active agent with the online channel. No body. Test keys never hold the scope.", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "404": { "description": "Not Found", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "409": { "description": "Conflict", "headers": { "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } }, "429": { "description": "Over the 100 requests a minute per API key, shared by every endpoint, or more than 10 failed API keys a minute from your address: no body. Wait the number of seconds in Retry-After, then retry.", "headers": { "Retry-After": { "description": "Seconds to wait before retrying.", "schema": { "type": "integer" } }, "traceparent": { "description": "The call's W3C trace: 00-{trace id}-{span id}-{flags}. Sent on every answer, a success or a refusal without a body included. Quote it when you contact MPS about the call; its trace id is the one in a problem's traceId.", "schema": { "type": "string" }, "examples": { "default": { "value": "00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01" } } } } } }, "security": [ { "apiKey": [] } ] } ``` Schemas referenced as `#/components/schemas/…` are defined in the full document at /openapi.json. --- # Errors and rate limits (/errors-and-rate-limits) > Every status code the API answers, its error body, the rate limits and the retry policy, with what to do about each one. Each section below resolves one class of error. The payments API links to it from the error itself, in the `documentationUrl` of every problem response. ## Status codes | Status | Meaning | What to do | |---|---|---| | `200` | Success | — | | `201` | Created: a refund was requested (or replayed for its `Idempotency-Key`) | Read its `status` | | `400` | The request was understood but is invalid | Fix the field named in the body; do not retry unchanged. See [Validation errors](#validation-errors) | | `401` | No API key, or a wrong or revoked one | Check the key; do not retry. See [Authentication errors](#authentication-errors) | | `403` | The API key is valid but may not do this: a missing scope, or a merchant (`x-wallet-number`) your key does not cover | Check the scopes and the wallet; do not retry. See [Authentication errors](#authentication-errors) | | `404` | Not a published endpoint, or, on the payment read and the refund endpoints, no such payment or refund for this merchant | Check the path and the reference. See [Not found](#not-found) | | `409` | A conflict, named by the body's `code` | Retry or stop, as the `code` says. See [Conflicts](#conflicts) | | `429` | Rate limited | Wait `Retry-After` seconds, then retry. See [Rate limits](#rate-limits) | | `5xx` | A problem on the MPS side | Retry reads with backoff; see [Server errors](#server-errors) for creates | ## Problem responses The payments API answers an error with an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem document. Every problem response of the payments API carries two fields beside `status` and `detail`: | Field | Type | Required | Description | |---|---|---|---| | `traceId` | string | Yes | The W3C trace id of the call, such as `00-a27c57cb…-01`. Quote it when you contact MPS about a failed call: it finds that exact call in the MPS logs. | | `documentationUrl` | string | Yes | A link to the section of this page that resolves the error, such as [Validation errors](#validation-errors) for a `400`. | The gateway's own `401`, `403` and `429` answers have no body, and so no `traceId` or `documentationUrl`. The status code is the whole answer. The one exception is the `403` for an `x-wallet-number` your key does not cover: its body is `{ "error": "invalid_request", "error_description": "…" }` (see [Authentication errors](#authentication-errors)). ### The `traceparent` header [#traceparent] **Every answer** carries a `traceparent` header naming the call's W3C trace: a success, a problem, and a `401`, `404` or `429` that has no body. Log it with every call you make; quote it when you contact MPS about a call, failed or not. ```http traceparent: 00-a27c57cb2b3e4f5d8c9a0b1c2d3e4f50-1a2b3c4d5e6f7a8b-01 ``` The second part is the trace id. On a problem response it is the same trace id as in the body's `traceId`; the part after it can differ, as it names the step in MPS that answered. ## Validation errors [#validation-errors] A payment endpoint answers a validation failure with `400` and a problem document whose `errors` object maps each offending field to its messages: ```json title="400 Bad Request" { "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", "title": "One or more validation errors occurred.", "status": 400, "errors": { "amount": ["Amount must be greater than zero (in cents)"] }, "traceId": "00-a27c57cb…-01", "documentationUrl": "https://docs.mps-emi.com/errors-and-rate-limits#validation-errors" } ``` Each key is the field as you sent it in the JSON body (`amount`, `successUrl`), or the header (`Idempotency-Key`). A body that cannot be read at all is refused the same way, naming the field when there is one: a decimal or a string where a whole number of cents belongs, or malformed JSON. Show the messages to a developer, not to a shopper: they are written in English for integrators. Fix the named field and send the request again. Do not retry it unchanged. ## Authentication errors [#authentication-errors] | Status | Code | Cause | Resolution | |---|---|---|---| | `401` | — | No API key, or a wrong or revoked one. No body. | Check the key; do not retry. See [API key errors](/authentication#api-key-errors). | | `403` | — | The API key is valid but lacks the endpoint's scope. No body. | Use a key that holds the scope. See [Scopes](/authentication#scopes). | | `403` | `invalid_request` | The `x-wallet-number` is not one of your merchants. The body is `{ "error": "invalid_request", "error_description": "…" }`. | Send a wallet your key covers. See [Choose the merchant](/authentication#choosing-the-merchant). | | `403` | — | Create a payment with a partner key and no `x-wallet-number`. No body. | Send `x-wallet-number` on every call. See [Choose the merchant](/authentication#choosing-the-merchant). | | `403` | — | Create a payment: the merchant has no shop name registered yet. No body. | Contact MPS. | ## Not found [#not-found] A `404` carries no body. It means one of two things: - The path is not a published endpoint. Check the path against the [API reference](/api-reference). - On the payment read and the refund endpoints: no such payment or refund for the merchant the key acts for. The reference has a typo, changed on the way (trimmed, re-cased, parsed as a UUID), or belongs to a different merchant than the one the payment was created for. With a partner key, read it with the same `x-wallet-number`. Do not retry a `404` unchanged. ## Conflicts [#conflicts] A `409` is a problem document with a stable `code` beside its `detail`. Decide on the `code`: it never changes, while `detail` is English text for a person and can be reworded at any time. ```json title="409 Conflict" { "status": 409, "detail": "A payment with this Idempotency-Key is still being created; retry shortly", "code": "idempotency_key_in_use", "traceId": "00-a27c57cb…-01", "documentationUrl": "https://docs.mps-emi.com/errors-and-rate-limits#conflicts" } ``` | `code` | Where | Meaning | Retry? | |---|---|---|---| | `idempotency_key_in_use` | Create a payment, refund a payment | The first request with this `Idempotency-Key` is still running | Yes, after a second, with the same key and body | | `refund_in_progress` | Refund a payment, cancel a refund | Another refund of the same payment is being changed at this moment | Yes, after a second | | `idempotency_key_expired` | Create a payment | The key is still kept, but the payment it made can no longer be returned (rare). After 24 hours a key is not kept at all and opens a new payment instead: see [Retrying safely](/online-payments#retrying-safely-idempotency-key) | No: create a new payment with a new key | | `payment_not_refundable` | Refund a payment | The payment is not `executed` | No | | `refund_not_cancelable` | Cancel a refund | The refund was sent or decided | No: read it | | `payment_link_not_open` | Cancel a payment link | The link is paid or expired, so there is nothing left to cancel | No: read the link | | `payment_link_unnamed` | Create a payment link | The merchant has no shop name, which the shopper would see | No: ask MPS to set it | New codes may be added. Treat a `409` with a code you do not know as one not to retry. ## Rate limits | | Limit | |---|---| | Requests per API key | 100 per minute, across every endpoint | The limit counts **per API key**: creates, reads and refunds share it. A test key and a live key each have their own; a partner key has one for all the merchants it acts for. The minute is a fixed window, not a rolling one: all 100 calls may come at once, and the count starts again when the window ends. Over the limit the answer is `429 Too Many Requests` at once, with a `Retry-After` header giving the seconds to wait. Nothing is queued. A `429` also comes from too many failed keys from one address. See [API key errors](/authentication#api-key-errors). **Reuse connections.** Send your calls over kept-alive connections (HTTP/1.1 keep-alive or one HTTP/2 connection) from an HTTP client that pools them, as every common HTTP client does by default. Opening many new connections at the same moment from one address can be refused at the network edge, before the request reaches the API, as a reset connection rather than a `429`. A pooled client does not run into it. Retry a reset like a network error. **Budget for polling.** Reading four payments every 2 seconds is already 120 reads a minute. Poll only while a shopper is on your return page, at most every 2 seconds and for about 30 seconds, then let the webhook settle the order. Reconcile older orders on a schedule, spread out, with backoff. See [Reconcile what you did not hear about](/payment-lifecycle#reconcile-what-you-did-not-hear-about). If your volume needs more, ask MPS. ## Server errors [#server-errors] A `5xx` is a problem on the MPS side. A `500` from the payments API is a problem document with a `traceId` and a `documentationUrl`; other `5xx` answers can carry no body. - **Reads** are safe to retry with backoff. - **A create with an `Idempotency-Key`** is safe to retry with the same key and the same body: you get the payment the first call made, or a new one if it made none. - **A create without a key** is not safe to retry: the retry may open a second payment. The [Retry policy](#retry-policy) lists every operation. Quote the `traceId` when you contact MPS. ## By endpoint ### `POST /api/payments/internet/create` > **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. | Status | Body | Common causes | |---|---|---| | `200` | `{ "data": { "paymentReference", "checkoutUrl" } }` | — | | `400` | Problem document with `errors` per field (see [Validation errors](#validation-errors)) | `amount` of zero or missing; `successUrl` / `failureUrl` missing or not `https://`; a `callbackUrl` that is not an absolute HTTPS URL on a public host; an `Idempotency-Key` reused for a different request, or `Idempotency-Key` and `X-Idempotency-Key` naming different keys | | `401` | none | No API key, or a wrong or revoked one | | `403` | none, or `{ "error", "error_description" }` | The key lacks `internet:create`; a partner key sent no `x-wallet-number`, or one it does not cover (with a body); or the merchant has no shop name registered yet (contact MPS) | | `409` | Problem document with a `code` | `idempotency_key_in_use`: a create with the same `Idempotency-Key` is still running; retry shortly. `idempotency_key_expired`: create a new payment with a new key | | `429` | none, `Retry-After` header | The key's 100 requests a minute, shared by every endpoint ([Rate limits](#rate-limits)) | | `5xx` | See [Server errors](#server-errors) | On the MPS side: do not retry blindly, see [Retry policy](#retry-policy) | ### `GET /api/payments/internet/{paymentReference}` | Status | Body | Common causes | |---|---|---| | `200` | `{ "data": { "paymentReference", "state", "amount", "currency", "amountRefunded", "amountRemaining", "reference" } }` | — | | `401` | none | No API key, or a wrong or revoked one | | `403` | none | The key lacks `internet:read` | | `404` | none | No such payment for the merchant the key acts for, or a partner key sent no `x-wallet-number` (see [Not found](#not-found)) | | `429` | none, `Retry-After` header | The key's 100 requests a minute, shared by every endpoint ([Rate limits](#rate-limits)); poll every 2 seconds at most | ### `POST /api/payments/{paymentReference}/refunds` | Status | Body | Common causes | |---|---|---| | `201` | `{ "data": { "refundId", "status", … } }`, `Location` header | — | | `400` | Problem document with `errors` per field (see [Validation errors](#validation-errors)) | a malformed `paymentReference`; `amount` zero or less, or more than is left; nothing left to refund; an unknown `reason`; an `Idempotency-Key` reused for a different request, or with spaces or other characters than letters, digits and punctuation | | `401` | none | No API key, or a wrong or revoked one | | `403` | none, or `{ "error", "error_description" }` | The key lacks `payments:refund`; a partner key sent no `x-wallet-number`, or one it does not cover (with a body) | | `404` | none | No such payment for this merchant, or a test key on a live payment (or the reverse) | | `409` | Problem document with a `code` | `idempotency_key_in_use` or `refund_in_progress`: retry shortly. `payment_not_refundable`: the payment is not `executed` | | `429` | none, `Retry-After` header | The key's 100 requests a minute, shared by every endpoint ([Rate limits](#rate-limits)) | ### `GET /api/payments/{paymentReference}/refunds/{refundId}` and `GET /api/payments/{paymentReference}/refunds` | Status | Body | Common causes | |---|---|---| | `200` | `{ "data": { "refundId", "status", … } }`, or `{ "data": [ … ] }` for the list | — | | `401` | none | No API key, or a wrong or revoked one | | `403` | none, or `{ "error", "error_description" }` | The key lacks `payments:refund`; a partner key sent no `x-wallet-number`, or one it does not cover (with a body) | | `404` | none | No such payment for this merchant, or no such refund under it | | `429` | none, `Retry-After` header | The key's 100 requests a minute, shared by every endpoint ([Rate limits](#rate-limits)) | ### `DELETE /api/payments/{paymentReference}/refunds/{refundId}` | Status | Body | Common causes | |---|---|---| | `204` | none | Canceled, or canceled before | | `401` | none | No API key, or a wrong or revoked one | | `403` | none, or `{ "error", "error_description" }` | The key lacks `payments:refund`; a partner key sent no `x-wallet-number`, or one it does not cover (with a body) | | `404` | none | No such refund of this payment for this merchant | | `409` | Problem document with a `code` | `refund_not_cancelable`: it was sent or decided; read it. `refund_in_progress`: retry shortly | | `429` | none, `Retry-After` header | The key's 100 requests a minute, shared by every endpoint ([Rate limits](#rate-limits)) | ## Retry policy | Operation | Retry on | Do not retry on | |---|---|---| | **Create a payment** (with an `Idempotency-Key`) | `5xx`, a network error or a timeout: same key, same body. `409` `idempotency_key_in_use`: after a second. `429`: after `Retry-After`. | `400`, `401`, `403`, `409` `idempotency_key_expired` | | **Create a payment** (without a key) | `429` only | `5xx` or a timeout: the retry may open a second payment. Create a fresh one and abandon the first | | **Read a payment** | `5xx`, a network error, `429` (after `Retry-After`): with backoff (1 s, 2 s, 4 s…, capped) | `400`, `401`, `403`, `404` | | **Refund a payment** | `5xx`, a network error or a timeout: same key, same body. `409` `idempotency_key_in_use` or `refund_in_progress`: after a second. `429`. | `400`, `401`, `403`, `404`, `409` `payment_not_refundable` | | **Cancel a refund** | `5xx`, a network error, `409` `refund_in_progress`, `429`. A repeated cancel is safe: a canceled refund answers `204` again. | `404`, `409` `refund_not_cancelable` | Back off with jitter (a random part of the wait), and give up after a handful of attempts: a request that keeps failing is something to look at, not to repeat. ## Related - [Payment lifecycle](/payment-lifecycle) - [Accept a payment](/online-payments) - [Authentication](/authentication) - [Refunds](/refunds) --- # Overview (/overview) > What the MPS payment gateway is, the host you talk to, and the shape of every integration. The MPS payment gateway is the public API for taking payments through MPS. Your backend sends its **API key** as the bearer on every call. You do not exchange it for anything first. It offers one kind of payment, the **online payment**: you send the shopper to the MPS checkout, the shopper pays with ANNA (by bank) or by card, and comes back to your shop. See [Accept a payment](/online-payments). ## The hosts | Host | What it is | Who calls it | |---|---|---| | `https://gateway.mps-emi.com` | The API: `/api/payments/…` for the payment endpoints, called with your API key | Your backend | | `https://pay.mps-emi.com` | The checkout, the `checkoutUrl` of an online payment | The shopper's browser, never your code | Redirect the shopper to `checkoutUrl` exactly as returned. Never build it yourself. **There is one environment, and no separate test host.** You test on these same hosts with a **test key**: an API key that starts with `mps_test_`. A test key's payments use the same endpoints, checkout, states and webhooks as live ones. They accept only the [test cards](/online-payments#test-mode) and never charge or pay out anything. Moving to live mode means swapping the key, not the host. You create API keys on the MPS platform under **Online › API keys**, test and live keys alike. They only work on `https://gateway.mps-emi.com`. Sent anywhere else, the call fails with `401`. ## Every integration has the same shape > **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. ### Your backend holds an API key It sends the key as `Authorization: Bearer mps_…` on every call. The key stays on your backend: a browser or an app never calls MPS itself. See [Authentication](/authentication). ### Create a payment and redirect `POST /api/payments/internet/create` with the amount, your return URLs and an `Idempotency-Key`, one per checkout attempt, so a retry returns the same payment instead of opening a second. You get back a `paymentReference`, which you store with the order, and a `checkoutUrl` to redirect the shopper to. ### Confirm the outcome MPS posts a signed `payment.received` [webhook](/webhooks) to your `callbackUrl` once the payment is received. When the shopper comes back, read the payment by its `paymentReference` on your backend. > **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. ## Endpoints at a glance | Endpoint | Method | Scope | |---|---|---| | `https://gateway.mps-emi.com/api/payments/internet/create` | POST | `internet:create` | | `https://gateway.mps-emi.com/api/payments/internet/{paymentReference}` | GET | `internet:read` | | `https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds` | POST | `payments:refund` | | `https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds` | GET | `payments:refund` | | `https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds/{refundId}` | GET | `payments:refund` | | `https://gateway.mps-emi.com/api/payments/{paymentReference}/refunds/{refundId}` | DELETE | `payments:refund` | | `https://gateway.mps-emi.com/api/payments/payment-links` | POST | `payment-links:create` | | `https://gateway.mps-emi.com/api/payments/payment-links` | GET | `payment-links:read` | | `https://gateway.mps-emi.com/api/payments/payment-links/{id}` | GET | `payment-links:read` | | `https://gateway.mps-emi.com/api/payments/payment-links/{id}` | DELETE | `payment-links:create` | | `https://gateway.mps-emi.com/api/partners/registration-links` | POST | `registration-links:manage` | | `https://gateway.mps-emi.com/api/partners/registration-links` | GET | `registration-links:manage` | | `https://gateway.mps-emi.com/api/partners/registration-links/{id}` | GET | `registration-links:manage` | | `https://gateway.mps-emi.com/api/partners/registration-links/{id}` | DELETE | `registration-links:manage` | Nothing else is part of the public API. Every parameter, schema and status of these endpoints is in the [API reference](/api-reference), and as an OpenAPI document at [`/openapi.json`](/openapi.json). This whole site is available as plain text for language models. See [Build with AI](/build-with-ai), or hand your assistant [`/llms.txt`](/llms.txt) directly. ## Related - [Take your first online payment](/quickstart): create a payment, send the shopper to the checkout, read it back - [Accept a payment](/online-payments): create, redirect, return, read, and test mode - [Authentication](/authentication): API keys, choosing the merchant and scopes - [Payment lifecycle](/payment-lifecycle): every state and what to do with it --- # Changelog (/changelog) > Changes to what the API, the webhooks and test mode do, newest first, with every change an existing integration has to act on marked Breaking. Changes to what the API, the webhooks and test mode do, newest first. A change an existing integration has to act on is marked **Breaking**, with what to change; everything else needs nothing from you. Plugin releases are on each plugin's own page. ## What counts as non-breaking New endpoints, optional fields, response fields, states and events can appear at any time, and identifiers, field order and error messages can change shape. An integration that ignores what it does not recognise keeps working through all of them.
The full list, and how to write for it | Non-breaking change | How to write for it | |---|---| | New endpoints, and new optional request fields | Nothing you send today is affected. | | New fields in a response or a webhook body | Ignore the fields you do not know, rather than rejecting the body. | | New values for an existing field, such as a new `state` or a new `eventType` | Treat an unknown state as `pending`, and an unknown event as something to ignore. | | Fields in a different order, in a response or a webhook body | Verify a webhook signature over the raw bytes, never a re-serialised object. | | Identifiers in a different shape | `paymentReference`, `sessionId` and every other identifier are opaque strings: store them exactly as returned, in a column that allows up to 64 characters, and never parse them. | | New error messages, or reworded ones | Act on the status code and the field the error names, not on the message text. | | New `409` codes | Decide on the `code` a conflict carries; treat one you do not know as one not to retry. See [Conflicts](/errors-and-rate-limits#conflicts). | | Rate limits raised | Nothing to do. | Anything else is breaking: removing or renaming a field or an endpoint, making an optional field required, changing a field's type or meaning, or lowering a limit. There is one version of the API and no version header to pin. Its compatibility guarantee is this list: a breaking change is announced here, marked **Breaking**, with what to change, before it takes effect.
## 2026-11-20 - **Added** the payment timeline on the API: `GET /api/payments/timeline` lists your payments, newest first, with each payment's current state, and `GET /api/payments/{paymentReference}/timeline` returns every step one payment went through. Scope `internet:read`, which every test key and live key holds. See [Follow a payment's timeline](/payment-timeline). ## 2026-11-18 - **Added** payment links on the API: `POST /api/payments/payment-links` makes one, `GET` lists and reads them, `DELETE` cancels one. Scopes `payment-links:create` and `payment-links:read`, held by test keys and by live keys from this release on. A partner's key makes test links only. See [Create a payment link with the API](/payment-links-api). - **Added** personal registration links for a live partner on the API: `POST`, `GET` (with `status`), `GET {id}` and `DELETE {id}` under `/api/partners/registration-links`. Scope `registration-links:manage`, held by the live key a live partner makes for itself; never by a merchant's key or a test key. See [Create a registration link](/registration-links). - **Added** `url` on every registration link: the address the company opens to sign up. Send it to the company. See [Create a registration link](/registration-links). - **Added** the `409` codes `payment_link_not_open` and `payment_link_unnamed`, listed in [Conflicts](/errors-and-rate-limits#conflicts). ## 2026-11-17 - **Added** `locale` on [Create a payment](/online-payments#request-body): `en`, `nl` or `fr` opens the checkout in that language, whatever the shopper's browser asks for. Optional; without it nothing changes. - **Added** **Shopper's language** on a payment link: the link and its checkout open in the language you choose. See [Send a payment link](/payment-links). ## 2026-11-05 - **Added** ANNA in test mode: a test payment's checkout now shows the ANNA QR code. It opens ANNA's test screen, where the shopper chooses a bank and how the bank answers: paid, rejected by the bank, cancelled at the bank, or pending. No bank is contacted and no money moves; a paid one sends `payment.received` as in live mode. See [Test mode](/online-payments#test-mode). ## 2026-11-04 - **Added** payment links: ask for one payment of a fixed amount from **Online › Payment links** on the MPS platform, share the link or its QR code, and see when it is paid. No API call needed. See [Send a payment link](/payment-links). ## 2026-11-02 - **Breaking** a refund's `Idempotency-Key` must be letters, digits and punctuation without spaces, as a payment create's already was; any other key answers `400` naming `Idempotency-Key`. What to change: only an integration that put spaces or non-ASCII characters in a refund key. A UUID or `order-1234-refund-1` is unaffected, and so are the shop plugins' keys. See [Retrying safely](/refunds#retrying-safely). ## 2026-11-01 - **Changed** test and live keys are created on one screen, **Online › API keys**, with a Test | Live switch. You can hold several test keys at once, each with a name and its own webhook signing secret, and a key works until you revoke it. Keys you already have keep working. See [Authentication](/authentication#test-and-production-keys). - **Changed** a test payment lands on your own wallet, marked test, so you see it and its history on the platform. Nothing is charged, booked or paid out. Take a new test key to get this. - **Changed** a live key can be created once the merchant it is for has signed its contract with MPS. No API change. ## 2026-10-31 - **Breaking** a refund lives under the payment it refunds: create, list, read and cancel moved from `/api/payments/refunds` to `/api/payments/{paymentReference}/refunds` (and `…/refunds/{refundId}`). The refund body carries only `amount` and `reason`, and the list takes no query parameter. The former paths are gone. See [Refund a payment](/refunds). - **Changed** a partner key names its merchant with `x-wallet-number`. See [Authentication](/authentication). - **Added** a `traceparent` header on every answer of the API, also on a `401`, `404` or `429` without a body, and `documentationUrl` on every problem response, linking to the section of [Errors and rate limits](/errors-and-rate-limits) that resolves it. Quote `traceparent` when you contact MPS about a call. ## 2026-10-30 - **Breaking** `amount` is at most `5000000` (EUR 50,000) and must be a JSON number: a string such as `"1995"` is refused with `400`. Breaking only if you sent amounts as strings. - **Added** an `Idempotency-Key` header on create an online payment. A retry with the same key and body returns the first payment instead of opening a second one. See [Retry safely](/online-payments#retrying-safely-idempotency-key). - **Added** a stable `code` on every `409`, saying whether to retry. See [Conflicts](/errors-and-rate-limits#conflicts). - **Added** webhooks `refund.refunded`, `refund.failed` and `refund.canceled`, posted to the payment's `callbackUrl`, signed and retried like `payment.received`. See [Webhooks](/webhooks#events). - **Changed** every refund waits 4 hours before it is sent and can be canceled until then; a canceled refund reads `canceled`, and its amount can be refunded again. See [Refund a payment](/refunds). - **Changed** a `400` names the field as you sent it (`amount`, not `Request.Amount`), also for a body that cannot be read. Over the rate limit the answer is `429` with `Retry-After` at once. ## 2026-10-29 The API went live with: - **Added** [online payments](/online-payments): create a payment, send the shopper to the MPS checkout, and read its `state` and `amount`. A payment not paid within 24 hours is `abandoned`; see [Payment lifecycle](/payment-lifecycle). - **Added** signed `payment.received` [webhooks](/webhooks) to your `callbackUrl`. - **Added** [refunds](/refunds) of all or part of a payment, with `amountRefunded` and `amountRemaining` on the payment. A live key refunds once refunds were granted to it; every test key can. - **Added** [API keys](/authentication): one key, `mps_live_…` or `mps_test_…`, sent in the `Authorization` header with the `Bearer` scheme on every call. Keys do not expire. A partner key names the merchant per call. - **Added** [test mode](/online-payments#test-mode) with test keys and test cards; a test payment's `paymentReference` starts with `test-`. - **Added** the [API reference](/api-reference), and the OpenAPI document at [`/openapi.json`](/openapi.json). ## Related [Payment lifecycle](/payment-lifecycle), [Errors and rate limits](/errors-and-rate-limits) and the [API reference](/api-reference).