Skip to content

Instantly share code, notes, and snippets.

@pablorsk
Last active December 18, 2017 12:19
Show Gist options
  • Save pablorsk/7ef2cfd315ec231e1fe3a33cf4bbceee to your computer and use it in GitHub Desktop.
Save pablorsk/7ef2cfd315ec231e1fe3a33cf4bbceee to your computer and use it in GitHub Desktop.
MercadoPago with PHP --> SIMPLE!
<?php
$mp = new MP('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$preference_data = [
"items" => [
[
"title" => "Your product name ",
"id" => "yourProductId",
"external_reference" => "yourProductId", // used on webhook
"quantity" => 1,
"currency_id" => "ARS",
"unit_price" => 9.99
]
],"payer" => [
"email" => $client_email // this is optional
]
];
$preference_array = $mp->create_preference($preference_data);
$pref_id = $preference['response']['id'];
<?php
// se configura aquí: https://www.mercadopago.com/mla/herramientas/notificaciones
$ref = $arr = false;
try {
// tell PHP to log errors to receive_token_mercadopago.log in this directory
ini_set('log_errors', true);
ini_set('error_log', __DIR__ . '/receive_token_mercadopago-errors.log');
$operation_id = $_GET['id'];
$mp = new MP('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$arr_tmp = $mp->get_payment($operation_id);
$arr = $arr_tmp['response']['collection'];
// some fixes for MercadoPago 2017
if (strpos($arr['external_reference'], '%') !== false) {
$refstr = urldecode($arr['external_reference']);
} else {
$refstr = $arr['external_reference'];
}
if ($arr['status'] == 'approved')
{
// pago recibido del producto $arr['reason']
// revisar el monto pagado y la moneda para evitar hacks
}
} catch (Exception $e) {
$ret = mail('[email protected]', 'ERROR ping mercadopago: ' . $e->getMessage(),
$_SERVER['REQUEST_URI'] . "\n\n"
. 'refstr: ' . ($refstr ?? '(not setted)') . "\n\n"
. 'ref: ' . print_r($ref, true) . "\n\n"
. 'GET: ' . print_r($_GET, true) . "\n\n"
. 'POST: ' . print_r($_POST, true) . "\n\n"
. 'DATA: ' . print_r($arr, true));
if (!$ret && $e->getCode() != 500)
$header->setHttpCode(404);
error_log($e->getMessage());
}
exit;

Send your users to https://www.mercadopago.com/mla/checkout/pay?pref_id=$pref_id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment