# 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 (
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