Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
Send buyers to Mercado Pago's hosted Checkout Pro using a payment preference, handle back_urls safely, validate x-signature webhooks, and confirm payments by fetching them from the Payments API before fulfilling.
- Provider
- Mercado Pago
- Level
- Intermediate
- Stacks
- Node.js (Express), Python (FastAPI), PHP
- Code maturity
- Sandbox-ready
- Last verified
- 25 Nov 2026
Introduction
Checkout Pro is Mercado Pago's hosted checkout. Your server creates a payment preference (what is being bought, how much, where to send the buyer afterwards, where to notify you), and the buyer is redirected to Mercado Pago to pay with the methods available in their country.
This guide builds the whole loop in test mode: create a preference, redirect, receive a signed webhook, fetch the payment from the API, and fulfil the order exactly once.
Tip: Mercado Pago runs separate sites per country (mercadopago.com.br, .com.ar, .com.mx …). The API host is the same (api.mercadopago.com), but available payment methods, currencies and test cards depend on the country of the seller account.
What Checkout Pro does
- Your backend calls the Preferences API (
POST /checkout/preferences) withitems,back_urls,notification_urland anexternal_reference(your order id). - The response contains an
idand aninit_pointURL (plussandbox_init_point). You redirect the buyer there, or render the Wallet Brick with the preference id. - The buyer pays on Mercado Pago. They are sent back to one of your
back_urls(success / failure / pending). - Mercado Pago sends a webhook (topic
payment) to yournotification_url. You validate thex-signatureheader, then fetchGET /v1/payments/{id}and fulfil whenstatusisapproved.
Countries
Mercado Pago operates in Latin America (for example Brazil, Argentina, Mexico, Chile, Colombia, Peru and Uruguay). Each seller account belongs to one country and charges in that country's currency (for example BRL, ARS, MXN).
Check the country selector on the developer site for the current list — this guide does not claim a definitive country list.
Payment methods
Checkout Pro shows the methods enabled for the seller's country: cards (credit/debit, with installments where available), the Mercado Pago wallet/account balance, and local methods such as Pix or boleto in Brazil and cash vouchers in some countries.
You can exclude methods or cap installments with the preference's payment_methods object. Some methods are asynchronous (boleto, cash vouchers): the payment starts as pending and becomes approved later — another reason to rely on webhooks.
When to use it
- You sell to buyers in a Mercado Pago country and want local methods (Pix, boleto, installments) without building a card form.
- You want the lowest PCI scope: card data never touches your servers.
- You want buyers to be able to pay with an existing Mercado Pago account.
When not to use it
- You need a fully embedded, custom-styled card form — look at Checkout Bricks / Checkout API instead.
- Your merchant entity is outside Mercado Pago's countries.
- You need multi-country acquiring from one account — a global gateway or a cross-border aggregator may fit better.
Example scenarios
- Brazilian e-commerce store offering Pix, boleto and card installments on one hosted page.
- Course platform in Mexico selling one-off course purchases with redirect checkout.
- Event tickets in Argentina where async methods must not release tickets until the webhook confirms
approved.
Registration
- Create a Mercado Pago account in your country and open Your integrations in the developer panel.
- Create an application and choose Checkout Pro as the product.
- Note the test credentials (Access Token, Public Key) and later the production credentials, which require the account to be activated.
Sandbox and test accounts
Mercado Pago tests with test credentials and test users. In Your integrations you can create test accounts (a seller and a buyer). Log in to Checkout Pro as the test buyer and pay with the published test cards (see Testing).
Do not pay with your real account against a test preference — the docs require the buyer to be a test user.
Warning: The docs do not state on the test-purchases page whether a separate test seller account is mandatory. Following the developer-panel flow (test seller + test buyer) avoids the common "buyer and seller are the same" error.
Credentials
- Access Token — secret, server only. Sent as
Authorization: Bearer <token>. - Public Key — safe for the browser; only needed for Bricks / client SDK.
- Webhook secret signature — revealed under Webhooks > Configure notifications in Your integrations. It does not expire; you can renew it with the Reset button.
Security: Never ship the Access Token to a browser or mobile app. Anyone with it can create refunds and read payments on your account.
Environment configuration
Keep every secret in environment variables. A .env.example committed to the repo documents the names with placeholders only:
# Mercado Pago — use TEST credentials until you go live
MP_ACCESS_TOKEN=replace-with-test-access-token
MP_WEBHOOK_SECRET=replace-with-webhook-secret-signature
APP_BASE_URL=https://your-public-tunnel.example.comAuthentication
Every server call uses the Access Token as a bearer token: Authorization: Bearer $MP_ACCESS_TOKEN. The official SDKs set it for you once (new MercadoPagoConfig({ accessToken }) in Node, MercadoPagoConfig::setAccessToken() in PHP, mercadopago.SDK(token) in Python).
For POST requests send an X-Idempotency-Key header (Node: requestOptions.idempotencyKey; PHP: RequestOptions::setCustomHeaders(["X-Idempotency-Key: …"])) so that retries do not create duplicates.
Backend: create a preference
Prices come from your database, never from the request body. Store the preference id against the order.
import express from 'express';
import { randomUUID } from 'node:crypto';
import { MercadoPagoConfig, Preference } from 'mercadopago';
const app = express();
const mp = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN });
const BASE = process.env.APP_BASE_URL;
app.post('/checkout/:orderId', express.json(), async (req, res) => {
const order = await db.orders.findById(req.params.orderId); // your data layer
if (!order || order.status !== 'unpaid') return res.status(404).end();
const pref = await new Preference(mp).create({
body: {
items: order.lines.map((l) => ({
id: l.sku, title: l.name, quantity: l.qty,
unit_price: l.unitPrice, currency_id: order.currency, // e.g. 'BRL' — major units
})),
external_reference: order.id,
back_urls: {
success: `${BASE}/orders/${order.id}/return`,
failure: `${BASE}/orders/${order.id}/return`,
pending: `${BASE}/orders/${order.id}/return`,
},
auto_return: 'approved',
notification_url: `${BASE}/webhooks/mercadopago`,
},
requestOptions: { idempotencyKey: `pref-${order.id}-${order.version}` },
});
await db.orders.update(order.id, { mpPreferenceId: pref.id });
// Use pref.sandbox_init_point while testing if your account's docs ask for it
res.json({ redirectUrl: pref.init_point, preferenceId: pref.id });
});
app.listen(3000);import os, mercadopago
from fastapi import FastAPI, HTTPException
app = FastAPI()
sdk = mercadopago.SDK(os.environ['MP_ACCESS_TOKEN'])
BASE = os.environ['APP_BASE_URL']
@app.post('/checkout/{order_id}')
def create_preference(order_id: str):
order = orders.get(order_id) # your data layer
if not order or order['status'] != 'unpaid':
raise HTTPException(404)
return_url = f'{BASE}/orders/{order_id}/return'
result = sdk.preference().create({
'items': [{'id': l['sku'], 'title': l['name'], 'quantity': l['qty'],
'unit_price': l['unit_price'], 'currency_id': order['currency']}
for l in order['lines']],
'external_reference': order_id,
'back_urls': {'success': return_url, 'failure': return_url, 'pending': return_url},
'auto_return': 'approved',
'notification_url': f'{BASE}/webhooks/mercadopago',
})
if result['status'] not in (200, 201):
raise HTTPException(502, 'preference creation failed')
pref = result['response']
orders.update(order_id, mp_preference_id=pref['id'])
return {'redirectUrl': pref['init_point'], 'preferenceId': pref['id']}<?php
require __DIR__ . '/vendor/autoload.php';
use MercadoPago\MercadoPagoConfig;
use MercadoPago\Client\Preference\PreferenceClient;
use MercadoPago\Client\Common\RequestOptions;
use MercadoPago\Exceptions\MPApiException;
MercadoPagoConfig::setAccessToken(getenv('MP_ACCESS_TOKEN'));
$base = getenv('APP_BASE_URL');
$order = find_unpaid_order($_POST['order_id'] ?? ''); // your data layer
if (!$order) { http_response_code(404); exit; }
$return = "$base/orders/{$order['id']}/return";
$options = new RequestOptions();
$options->setCustomHeaders(["X-Idempotency-Key: pref-{$order['id']}"]);
try {
$pref = (new PreferenceClient())->create([
'items' => array_map(fn ($l) => [
'id' => $l['sku'], 'title' => $l['name'], 'quantity' => $l['qty'],
'unit_price' => $l['unit_price'], 'currency_id' => $order['currency'],
], $order['lines']),
'external_reference' => $order['id'],
'back_urls' => ['success' => $return, 'failure' => $return, 'pending' => $return],
'auto_return' => 'approved',
'notification_url' => "$base/webhooks/mercadopago.php",
], $options);
} catch (MPApiException $e) {
http_response_code(502);
exit;
}
save_preference_id($order['id'], $pref->id);
header('Location: ' . $pref->init_point, true, 303);Warning: Unlike Stripe/Adyen, Mercado Pago unit_price is in major units (e.g. 49.90 BRL), not cents. Round with your currency's decimals and compare as decimals when reconciling.
Tip: The Python snippet uses mercadopago.SDK(...).preference().create(...) (present in sdk-python's sdk.py on 2026-11-25). Its result is a dict with status and response; the snippet is marked simplified because it was not executed against test mode.
Frontend
The simplest frontend is a button that POSTs to your /checkout/:orderId route and then sets window.location.href = redirectUrl. Alternatively, render the Wallet Brick from the @mercadopago/sdk-react / sdk-js package with your Public Key and the preference id.
The frontend never sends prices and never decides that an order is paid.
Initiating the payment
- Buyer clicks Pay; your server loads the order, creates the preference with
external_reference = order.idand an idempotency key. - Redirect the buyer to
init_point. - Mark the order
awaiting_paymentwith the preference id. Creating a new preference for every click is fine, but keep the latest id for support.
Confirmation and back URLs
When the buyer returns, the back URL carries query parameters such as payment_id, status, external_reference and preference_id. Treat them as hints only — anyone can type them into the address bar.
On the return page, fetch the payment by id from the API (server side) and show its real status, or simply show "we're confirming your payment" and poll your own order status, which the webhook updates.
Security: Never mark an order paid because the buyer landed on the success URL. Only a server-side fetch of GET /v1/payments/{id} (triggered by the webhook or the return page) is trustworthy.
Webhooks: validate x-signature, then fetch
Configure the webhook URL and the Payments topic in Your integrations (or per preference with notification_url). Each notification carries:
x-signatureheader:ts=<unix seconds>,v1=<hex HMAC>x-request-idheader- the resource id as the
data.idquery parameter (also in the JSON body)
The signed manifest is id:<data.id>;request-id:<x-request-id>;ts:<ts>; — a pair is left out when its value is missing — and v1 is the hex HMAC-SHA256 of that manifest keyed with your webhook secret. The official SDKs now ship a WebhookSignatureValidator that does this for you.
After validating: return 200/201 quickly, then fetch the payment and apply it idempotently. Mercado Pago waits 22 seconds for your answer and otherwise retries every 15 minutes, with longer intervals after the third attempt.
import express from 'express';
import { MercadoPagoConfig, Payment, WebhookSignatureValidator, InvalidWebhookSignatureError } from 'mercadopago';
const router = express.Router();
const mp = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN });
router.post('/webhooks/mercadopago', express.json(), async (req, res) => {
try {
WebhookSignatureValidator.validate({
xSignature: req.headers['x-signature'],
xRequestId: req.headers['x-request-id'],
dataId: req.query['data.id'],
secret: process.env.MP_WEBHOOK_SECRET,
toleranceSeconds: 300,
});
} catch (err) {
if (err instanceof InvalidWebhookSignatureError) return res.status(401).end();
throw err;
}
res.sendStatus(200); // acknowledge fast; process after
if (req.body?.type !== 'payment') return;
try {
const payment = await new Payment(mp).get({ id: req.query['data.id'] });
await applyPayment(payment);
} catch (e) {
console.error('mp webhook processing failed', e.message); // re-queue in production
}
});
async function applyPayment(p) {
const order = await db.orders.findById(p.external_reference);
if (!order) return;
const amountOk = Number(p.transaction_amount) === Number(order.total)
&& p.currency_id === order.currency;
if (p.status === 'approved' && amountOk) {
// Conditional update: only one concurrent delivery wins
const won = await db.orders.updateWhere(
{ id: order.id, status: { $ne: 'paid' } },
{ status: 'paid', mpPaymentId: String(p.id) },
);
if (won) await fulfil(order.id);
} else if (['rejected', 'cancelled'].includes(p.status)) {
await db.orders.updateWhere({ id: order.id, status: 'awaiting_payment' }, { status: 'failed' });
}
}
export default router;import hmac, hashlib, os, time
from fastapi import APIRouter, Request, BackgroundTasks, Response
router = APIRouter()
SECRET = os.environ['MP_WEBHOOK_SECRET'].encode()
def valid_signature(x_signature: str, x_request_id: str | None, data_id: str | None) -> bool:
parts = dict(p.split('=', 1) for p in (x_signature or '').split(',') if '=' in p)
ts, v1 = parts.get('ts', '').strip(), parts.get('v1', '').strip()
if not ts or not v1 or abs(time.time() - int(ts)) > 300:
return False
manifest = ''
if data_id:
manifest += f'id:{data_id};'
if x_request_id:
manifest += f'request-id:{x_request_id};'
manifest += f'ts:{ts};'
expected = hmac.new(SECRET, manifest.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)
@router.post('/webhooks/mercadopago')
async def mp_webhook(request: Request, tasks: BackgroundTasks):
data_id = request.query_params.get('data.id')
if not valid_signature(request.headers.get('x-signature'),
request.headers.get('x-request-id'), data_id):
return Response(status_code=401)
body = await request.json()
if body.get('type') == 'payment' and data_id:
tasks.add_task(apply_payment, data_id) # fetch + idempotent update, see status-check
return Response(status_code=200)<?php
require __DIR__ . '/../vendor/autoload.php';
use MercadoPago\MercadoPagoConfig;
use MercadoPago\Client\Payment\PaymentClient;
use MercadoPago\Webhook\WebhookSignatureValidator;
use MercadoPago\Exceptions\InvalidWebhookSignatureException;
MercadoPagoConfig::setAccessToken(getenv('MP_ACCESS_TOKEN'));
// PHP turns the 'data.id' query key into 'data_id'
$dataId = $_GET['data_id'] ?? null;
try {
WebhookSignatureValidator::validate(
$_SERVER['HTTP_X_SIGNATURE'] ?? '',
$_SERVER['HTTP_X_REQUEST_ID'] ?? '',
$dataId,
getenv('MP_WEBHOOK_SECRET')
);
} catch (InvalidWebhookSignatureException $e) {
http_response_code(401);
exit;
}
$event = json_decode(file_get_contents('php://input'), true);
http_response_code(200);
if (($event['type'] ?? '') !== 'payment' || !$dataId) exit;
$payment = (new PaymentClient())->get((int) $dataId);
$order = find_order($payment->external_reference);
if ($order && $payment->status === 'approved'
&& (float) $payment->transaction_amount === (float) $order['total']
&& $payment->currency_id === $order['currency']) {
// e.g. UPDATE orders SET status='paid' WHERE id=? AND status<>'paid'
if (mark_paid_once($order['id'], (string) $payment->id)) fulfil($order['id']);
}Warning: QR Code notifications are not signed and cannot be validated with the secret signature. Treat them only as a signal to fetch the payment from the API.
Tip: The SDK docs recommend: validate signature and timestamp tolerance → deduplicate → enqueue and acknowledge → fetch the current resource in a worker → apply idempotently, because deliveries can repeat or arrive out of order.
Status check and reconciliation
GET /v1/payments/{id} is the source of truth. Useful status values include approved, pending, in_process, rejected, cancelled, refunded and charged_back.
If a webhook never arrives, search by your order id: GET /v1/payments/search?external_reference=<order id> (Node: new Payment(mp).search({ options: { external_reference } })). Run this from a scheduled job for orders stuck in awaiting_payment.
import { MercadoPagoConfig, Payment } from 'mercadopago';
const mp = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN });
export async function reconcile(orderId) {
const { results = [] } = await new Payment(mp).search({
options: { external_reference: orderId, sort: 'date_created', criteria: 'desc' },
});
const approved = results.find((p) => p.status === 'approved');
if (approved) await applyPayment(approved); // same idempotent function as the webhook
return approved?.status ?? results[0]?.status ?? 'none';
}Refunds
Refund with POST /v1/payments/{id}/refunds. Omit the amount for a full refund; pass amount (major units) for a partial one. Always send an idempotency key.
- Node:
new PaymentRefund(mp).create({ payment_id, body: { amount }, requestOptions: { idempotencyKey } }) - PHP:
(new PaymentRefundClient())->refund($paymentId, $amount, $options)or->refundTotal($paymentId, $options)
import { MercadoPagoConfig, PaymentRefund } from 'mercadopago';
const mp = new MercadoPagoConfig({ accessToken: process.env.MP_ACCESS_TOKEN });
// Staff-only route; amount in major units, omitted = full refund
export async function refundOrder(order, amount) {
return new PaymentRefund(mp).create({
payment_id: order.mpPaymentId,
body: amount ? { amount } : undefined,
requestOptions: { idempotencyKey: `refund-${order.id}-${amount ?? 'full'}` },
});
}Errors
- SDK calls throw on non-2xx responses (Node rejects the promise; PHP throws
MPApiExceptionwith the API response attached). Logstatus,messageandcause— never the Access Token. 401usually means a wrong or production/test-mixed Access Token.400with a field error usually means a missingitems[].unit_price/quantity, or an invalidback_urlswhenauto_returnis set.- A payment
status_detail(e.g. insufficient funds) explains rejections; show the buyer a friendly message and let them retry with a new preference or method.
Going to production
- Switch to production credentials (Access Token, Public Key) and a new webhook secret for production.
- Use HTTPS public URLs for
back_urlsandnotification_url. - Run the reconciliation job for unpaid orders and alert on webhook failures in Your integrations.
- Review statement descriptor, installment settings and excluded methods per country.
Security checklist
- Validate
x-signaturewith a constant-time comparison and a timestamp tolerance; reject on failure (401). - After validation, still fetch the payment — never trust the notification body or the back-URL query string.
- Compare
transaction_amount,currency_idandexternal_referencewith your order before fulfilling. - Make fulfilment idempotent (conditional update or unique constraint on payment id).
- Secrets only in env vars / a secret manager; rotate the webhook secret with the Reset button if exposed.
Testing
Log in to Checkout Pro as your test buyer and use the published test cards. For Brazil the test-purchases page lists (all expiring 11/30):
- Mastercard credit
5480 8328 0103 3311, CVV123 - Visa credit
4235 6477 2802 5682, CVV123 - American Express
3753 651535 56885, CVV1234 - Elo debit
5067 7667 8388 8311, CVV123
The cardholder name selects the outcome: APRO approved, OTHE declined (general error), CONT pending, CALL needs validation, FUND insufficient funds, SECU invalid security code, EXPI expiry problem, FORM form error.
Expose your local server with a tunnel so notification_url is reachable, and use the webhook simulator in Your integrations to replay notifications.
Warning: Test card numbers differ per country site. The numbers above are from the Brazilian (mercadopago.com.br) page checked 2026-11-25 — use your own country's test-purchases page.
Common mistakes
- Marking the order paid on the
successback URL instead of after fetching the payment. - Building the manifest from the body's
data.idwith a different value than the querydata.id, or forgetting the trailing;— the HMAC will never match. - Reading
$_GET['data.id']in PHP: PHP converts dots in query keys to underscores, so it is$_GET['data_id']. - Sending prices in cents (
unit_price: 4990) — Mercado Pago expects major units. - Testing with your real account as buyer against test credentials.
- Doing slow work before responding, so Mercado Pago times out (22 s) and retries.
Troubleshooting
- Signature always invalid — check you copied the secret for the same application and environment, that
tsis used exactly as sent, and thatx-request-idis included when present. - No webhooks arriving —
notification_urlmust be public HTTPS (nolocalhost); confirm the Payments topic is enabled and check the delivery log in Your integrations. auto_returnerror —back_urls.successmust be set whenauto_returnis used.- Payment stays
pending— async methods (boleto, vouchers) can take days; keep the order open and rely on the later webhook.
Further reading
Official documentation
Official documentation
Sources
- Mercado Pago — Create payment preference
- Mercado Pago — Webhooks (x-signature, retries, SDK validators)
- Mercado Pago — Checkout Pro test purchases (test cards, holder-name codes)
- sdk-nodejs — webhook validator source (manifest format)
- sdk-nodejs — webhook docs
- sdk-php — README (MercadoPagoConfig, PreferenceClient, RequestOptions)
- sdk-python — webhook validator
More payment guides
- Mercado Pago provider profile
- Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- MTN MoMo Collections: Request to Pay with the MoMo Open API
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayHero Kenya: M-Pesa STK Push via the PayHero API
- PayPal Checkout with Orders v2, verified webhooks and refunds