Skip to content

Instantly share code, notes, and snippets.

@upadrian
Last active September 30, 2021 16:33
Show Gist options
  • Select an option

  • Save upadrian/dad5ffd12ba48b989a656e8df9eeaa5c to your computer and use it in GitHub Desktop.

Select an option

Save upadrian/dad5ffd12ba48b989a656e8df9eeaa5c to your computer and use it in GitHub Desktop.
Mercado Pago Wrapper for Checkout Pro
<script type="text/javascript" src="https://sdk.mercadopago.com/js/v2"></script>
<div class="cho-container"></div>
<script>
const PreferenceId = '', //get this from MpMakePreference.php
PublicKey = '',
RenderContainer = '.cho-container',
RenderLabel = 'Pay with MP',
Locale = 'es-AR',
mp = new MercadoPago(PublicKey, {locale: Locale});
mp.checkout({
preference: {
id: PreferenceId
},
render : {
container: RenderContainer,
label : RenderLabel
}
});
</script>
<?php
$MpWrapper = new MpWrapper();
/*
* Transaction number that is assigned to this payment
* There can be several transactions for the same order.
* Example, a payment order # 1, may have transaction # 1 (unpaid), and # 2 (paid).
* There can only be one paid transaction for each payment request.
* Transaction are used for log and debug purporses.
*/
$IDtransaction = 1;
/*
* Array with the items to sell.
* Each item must have ProductName, Quantity, UnitPrice, CurrencyIso3 (UYU, USD), UrlProductImage (empty if it does not have one)
*/
$items = [];
foreach ($items as $item) {
$MpWrapper->addItem($item);
}
/*
* Preloaded data of the user who buys.
* It must have Name, Surname, Email, Phone and DocumentNumber
*/
$User = [];
$MpWrapper->generatePayer($User);
/*
* Apply shipping cost
*/
$Shippingcost = 0;
if ($Shippingcost) {
$MpWrapper->addShippingCost($Shippingcost);
}
/*
* Save items added
*/
$MpWrapper->saveItems();
/*
* Apply Discount
*/
$discount = 0;
if($discount){
$MpWrapper->setDiscount($discount);
}
/*
* Save preference
*/
if(!$MpWrapper->PreferenceSave()){
Tthrow new Exception($MpWrapper->getPreferenceError());
}
/*
* Echo PreferenceId to use in JS
*/
echo json_encode(["PreferenceId" => $MpWrapper->getPreferenceId()]);
<?php
/**
* MercadoPago php SDK install:
* composer require "mercadopago/dx-php"
*
* Mercadopago Checkout Pro documentation:
* https://www.mercadopago.com.uy/developers/es/guides/online-payments/checkout-pro/introduction
*
*/
/**
* Class MpWrapper
*/
class MpWrapper {
const ClientId = '';
const ClientSecret = '';
const PublicKey = '';
const AccessToken = '';
const back_url_success = '';
const back_url_failure = '';
const back_url_pending = '';
const Statement_Descriptor = '';
private $preference;
private array $items = [];
public function __construct() {
MercadoPago\SDK::setAccessToken(self::AccessToken);
$this->makePreference();
}
public function makePreference(): MpWrapper {
$this->preference = new MercadoPago\Preference();
$this->preference->back_urls = [
'success' => self::back_url_success,
'failure' => self::back_url_failure,
'pending' => self::back_url_pending
];
$this->preference->auto_return = 'all';
$this->preference->statement_descriptor = self::Statement_Descriptor;
return $this;
}
public function addItem(array $ItemRow) {
$item = new MercadoPago\Item();
$item->title = $ItemRow['ProductName'];
$item->quantity = $ItemRow['ProductQuantity'];
$item->unit_price = $ItemRow['UnitPrice'];
$item->currency_id = $ItemRow['CurrencyIso3'];
$item->picture_url = $ItemRow['UrlProductImage'];
$this->items[] = $item;
}
public function addShippingCost(
float $Amount,
string $title = 'Shipping Cost',
string $CurrencyId = 'UYU'
): MpWrapper {
$item = new MercadoPago\Item();
$item->title = $title;
$item->quantity = 1;
$item->unit_price = $Amount;
$item->currency_id = $CurrencyId;
$this->items[] = $item;
return $this;
}
public function setDiscount(float $amount): MpWrapper {
$this->preference->coupon_amount = $amount;
return $this;
}
public function saveItems(): MpWrapper {
$this->preference->items = $this->items;
return $this;
}
public function generatePayer(array $User): MpWrapper {
$payer = new MercadoPago\Payer();
$payer->type = 'customer';
$payer->id = $User['id'];
$payer->name = $User['Name'];
$payer->surname = $User['Surname'];
$payer->email = $User['Email'];
$payer->date_created = date(DATE_ATOM);
$payer->phone = [
'area_code' => '',
'number' => $User['Phone']
];
$payer->identification = [
'type' => 'DNI',
'number' => $User['DocumentNumber']
];
$this->preference->payer = $payer;
return $this;
}
/**
* @throws Exception
*/
public function PreferenceSave(): bool {
return $this->preference->save();
}
public function getPreferenceId():string {
return $this->preference->id;
}
public function getPreferenceError(): \MercadoPago\RecuperableError{
return $this->preference->Error();
}
}
  1. Generate Cart
  2. Show button and call MpMakePreference.php using ajax
  3. MakePreference.php returns PreferenceId
  4. Instance MercadoPago JS, showing pay button
  5. MercadoPago returns to success, failure or pending url (see MpWrapper.php)
  6. Catch payment using webhook configured in MercadoPago Application (IPN Notifications).

IPN Notifications

https://www.mercadopago.com.uy/developers/es/guides/notifications/ipn

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