Checkout Pro allows you to redirect users to a Mercado Pago hosted checkout page. The workflow involves:
- Authentication: Set the access token via
MercadoPagoConfig. - Preference Creation: Define a request array containing
items, payer, payment_methods, and back_urls (success, failure, etc.). - Preference Client: Use
PreferenceClient to send the request to the API. - Redirect: Use the
init_point property from the returned Preference object to redirect the user to the checkout URL.
You can also retrieve an existing preference using $client->get("PREFERENCE_ID").
use MercadoPago\MercadoPagoConfig;
use MercadoPago\Client\Preference\PreferenceClient;
use MercadoPago\Exceptions\MPApiException;
// 1. Authenticate
MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
// 2. Prepare items and payer
$items = [
[
"id" => "1234567890",
"title" => "Product 1",
"description" => "Description",
"currency_id" => "BRL",
"quantity" => 1,
"unit_price" => 9.90
]
];
$payer = [
"name" => "John",
"surname" => "Doe",
"email" => "john.doe@example.com",
];
// 3. Create the preference request
$request = [
"items" => $items,
"payer" => $payer,
"back_urls" => [
'success' => 'https://your-site.com/success',
'failure' => 'https://your-site.com/failed'
],
"external_reference" => "1234567890",
"auto_return" => 'approved',
];
// 4. Execute via PreferenceClient
$client = new PreferenceClient();
try {
$preference = $client->create($request);
// Use $preference->init_point to redirect the user
echo "Redirect to: " . $preference->init_point;
} catch (MPApiException $error) {
// Handle error
}