Code example (all payment methods)
To facilitate and optimize your integration process, check below a complete example of how to include the Mercado Pago Wallet as a means of payment with Payment Brick.
Create your preference
Server-Side
<?php
// SDK do Mercado Pago
require __DIR__ . '/vendor/autoload.php';
// Add credentials
MercadoPago\SDK::setAccessToken('PROD_ACCESS_TOKEN');
// Create a preference object
$preference = new MercadoPago\Preference();
// Create an item in the preference
$item = new MercadoPago\Item();
$item->title = 'Meu produto';
$item->quantity = 1;
$item->unit_price = 75.56;
$preference->items = array($item);
// the $preference->purpose = 'wallet_purchase'; only allow logged in payments
// to allow guest payments you can omit this property
$preference->purpose = 'wallet_purchase';
$preference->save();
?>
// SDK do Mercado Pago
const mercadopago = require ('mercadopago');
// Add credentials
mercadopago.configure({
access_token: 'PROD_ACCESS_TOKEN'
});
// Create a preference object
let preference = {
// the "purpose": "wallet_purchase" only allows logged payments
// to allow guest payments you can omit this property
"purpose": "wallet_purchase",
"items": [
{
"id": "item-ID-1234",
"title": "Meu produto",
"quantity": 1,
"unit_price": 75.76
}
]
};
mercadopago.preferences.create(preference)
.then(function (response) {
// This value is the preferenceId that will be sent to the Brick at startup
const preferenceId = response.body.id;
}).catch(function (error) {
console.log(error);
});
// Mercado Pago SDK
import com.mercadopago.MercadoPagoConfig;
// Add credentials
MercadoPagoConfig.setAccessToken("PROD_ACCESS_TOKEN");
// Create a preference object
PreferenceClient client = new PreferenceClient();
// Create an item in the preference
List<PreferenceItemRequest> items = new ArrayList<>();
PreferenceItemRequest item =
PreferenceItemRequest.builder()
.title("My producto")
.quantity(1)
.unitPrice(new BigDecimal("100"))
.build();
items.add(item);
PreferenceRequest request = PreferenceRequest.builder()
// the .purpose('wallet_purchase') only allows logged payments
// to allow guest payments you can omit this line
.purpose('wallet_purchase')
.items(items).build();
client.create(request);
# Mercado Pago SDK
require 'mercadopago'
# Add credentials
sdk = Mercadopago::SDK.new('PROD_ACCESS_TOKEN')
# Create a preference object
preference_data = {
# the purpose: 'wallet_purchase', allows only logged payments
# to allow guest payments you can omit this property
purpose: 'wallet_purchase',
items: [
{
title: 'Meu produto',
unit_price: 75.56,
quantity: 1
}
]
}
preference_response = sdk.preference.create(preference_data)
preference = preference_response[:response]
# This value is the preferenceId you will use in the HTML on Brick startup
@preference_id = preference['id']
// Mercado Pago SDK
using MercadoPago.Config;
// Add credentials
MercadoPagoConfig.AccessToken = "PROD_ACCESS_TOKEN";
// Create the preference request object
var request = new PreferenceRequest
{
// the Purpose = 'wallet_purchase', allows only logged payments.
// to allow guest payments you can omit this property
Purpose = 'wallet_purchase',
Items = new List<PreferenceItemRequest>
{
new PreferenceItemRequest
{
Title = "Meu produto",
Quantity = 1,
CurrencyId = "BRL",
UnitPrice = 75.56m,
},
},
};
// Create the preference using the client
var client = new PreferenceClient();
Preference preference = await client.CreateAsync(request);
# Mercado Pago SDK
import mercadopago
# Add credentials
sdk = mercadopago.SDK("PROD_ACCESS_TOKEN")
# Create an item in the preference
preference_data = {
# the "purpose": "wallet_purchase", allows only logged in payments
# to allow guest payments, you can omit this property
"purpose": "wallet_purchase",
"items": [
{
"title": "My item",
"quantity": 1,
"unit_price": 75.76
}
]
}
preference_response = sdk.preference().create(preference_data)
preference = preference_response["response"]
curl -X POST \
'https://api.mercadopago.com/checkout/preferences' \
-H 'Content-Type: application/json' \
-H 'cache-control: no-cache' \
-H 'Authorization: Bearer **PROD_ACCESS_TOKEN**' \
-d '{
"purpose": "wallet_purchase",
"items": [
{
"title": "My product",
"quantity": 1,
"unit_price": 75.76
}
]
}'
Configure the integration
Client-Side
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bricks</title>
</head>
<body>
<div id="paymentBrick_container"></div>
<script src="https://sdk.mercadopago.com/js/v2"></script>
<script>
const mp = new MercadoPago('YOUR_PUBLIC_KEY');
const bricksBuilder = mp.bricks();
const renderPaymentBrick = async (bricksBuilder) => {
const settings = {
initialization: {
/*
"amount" is the total amount to be paid
by all means of payment with the exception of the Mercado Pago Wallet,
which has its processing value determined in the backend through the "preferenceId"
*/
amount: 100, // amount of processing to be performed
preferenceId: '<PREFERENCE_ID>', // preferenceId generated in the backend
},
customization: {
paymentMethods: {
creditCard: 'all',
debitCard: 'all',
ticket: 'all',
mercadoPago: 'all',
},
},
callbacks: {
onReady: () => {
/*
Callback called when Brick is ready
Here you can hide loadings from your site, for example.
*/
},
onSubmit: ({ selectedPaymentMethod, formData }) => {
// callback called when clicking on the data submission button
return new Promise((resolve, reject) => {
let url = undefined;
if (selectedPaymentMethod === 'credit_card' || selectedPaymentMethod === 'debit_card') {
url = 'process_payment_card';
} else if (selectedPaymentMethod === 'ticket') {
url = 'process_payment_ticket';
}
if (url) {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData)
})
.then((response) => {
// receive payment result
resolve();
})
.catch((error) => {
// handle error response when trying to create payment
reject();
})
} else if (
selectedPaymentMethod === 'wallet_purchase' ||
selectedPaymentMethod === 'onboarding_credits'
) {
/*
wallet_purchase (Mercado Pago Wallet) e
onboarding_credits (Installments without card)
does not need to be sent from the backend
*/
resolve();
} else {
reject();
}
});
},
onError: (error) => {
// callback called for all Brick error cases
console.error(error);
},
},
};
window.paymentBrickController = await bricksBuilder.create(
'payment',
'paymentBrick_container',
settings
);
};
renderPaymentBrick(bricksBuilder);
</script>
</body>
</html>
Payment submission to Mercado Pago
Server-Side
preferenceId
sent at the initialization of the Brick is responsible for redirecting the buyer to the Mercado Pago website, where the payment will be made directly on our website. To redirect the buyer back to your site, you can configure the back_urls
as described
in this article.
For the endpoint
/process_payment_card
:<?php require_once 'vendor/autoload.php'; MercadoPago\SDK::setAccessToken("YOUR_ACCESS_TOKEN"); $payment = new MercadoPago\Payment(); $payment->transaction_amount = (float)$_POST['transactionAmount']; $payment->token = $_POST['token']; $payment->description = $_POST['description']; $payment->installments = (int)$_POST['installments']; $payment->payment_method_id = $_POST['paymentMethodId']; $payment->issuer_id = (int)$_POST['issuer']; $payer = new MercadoPago\Payer(); $payer->email = $_POST['cardholderEmail']; $payer->identification = array( "type" => $_POST['identificationType'], "number" => $_POST['identificationNumber'] ); $payer->first_name = $_POST['cardholderName']; $payment->payer = $payer; $payment->save(); $response = array( 'status' => $payment->status, 'status_detail' => $payment->status_detail, 'id' => $payment->id ); echo json_encode($response); ?>
You can find payment status in status value.
var mercadopago = require('mercadopago'); mercadopago.configurations.setAccessToken("YOUR_ACCESS_TOKEN"); var payment_data = { amount: req.body.amount, ... } mercadopago.payment.save(payment_data) .then(function(response) { const { status, status_detail, id } = response.body; res.status(response.status).json({ status, status_detail, id }); }) .catch(function(error) { console.error(error); });
You can find payment status in status value.
PaymentClient client = new PaymentClient(); PaymentCreateRequest paymentCreateRequest = PaymentCreateRequest.builder() .transactionAmount(request.getTransactionAmount()) .token(request.getToken()) .description(request.getDescription()) .installments(request.getInstallments()) .paymentMethodId(request.getPaymentMethodId()) .payer( PaymentPayerRequest.builder() .email(request.getPayer().getEmail()) .firstName(request.getPayer().getFirstName()) .identification( IdentificationRequest.builder() .type(request.getPayer().getIdentification().getType()) .number(request.getPayer().getIdentification().getNumber()) .build()) .build()) .build(); client.create(paymentCreateRequest);
You can find payment status in status value.
require 'mercadopago' sdk = Mercadopago::SDK.new('YOUR_ACCESS_TOKEN') payment_data = { transaction_amount: params[:transactionAmount].to_f, token: params[:token], description: params[:description], installments: params[:installments].to_i, payment_method_id: params[:paymentMethodId], payer: { email: params[:cardholderEmail], identification: { type: params[:identificationType], number: params[:identificationNumber] }, first_name: params[:cardholderName] } } payment_response = sdk.payment.create(payment_data) payment = payment_response[:response] puts payment
You can find payment status in status value.
using System; using MercadoPago.Client.Common; using MercadoPago.Client.Payment; using MercadoPago.Config; using MercadoPago.Resource.Payment; MercadoPagoConfig.AccessToken = "YOUR_ACCESS_TOKEN"; var paymentRequest = new PaymentCreateRequest { TransactionAmount = decimal.Parse(Request["transactionAmount"]), Token = Request["token"], Description = Request["description"], Installments = int.Parse(Request["installments"]), PaymentMethodId = Request["paymentMethodId"], Payer = new PaymentPayerRequest { Email = Request["cardholderEmail"], Identification = new IdentificationRequest { Type = Request["identificationType"], Number = Request["identificationNumber"], }, FirstName = Request["cardholderName"] }, }; var client = new PaymentClient(); Payment payment = await client.CreateAsync(paymentRequest); Console.WriteLine(payment.Status);
You can find payment status in status value.
import mercadopago sdk = mercadopago.SDK("ACCESS_TOKEN") payment_data = { "transaction_amount": float(request.POST.get("transaction_amount")), "token": request.POST.get("token"), "description": request.POST.get("description"), "installments": int(request.POST.get("installments")), "payment_method_id": request.POST.get("payment_method_id"), "payer": { "email": request.POST.get("cardholderEmail"), "identification": { "type": request.POST.get("identificationType"), "number": request.POST.get("identificationNumber") } "first_name": request.POST.get("cardholderName") } } payment_response = sdk.payment().create(payment_data) payment = payment_response["response"] print(payment)
You can find payment status in status value.
curl -X POST \ -H 'accept: application/json' \ -H 'content-type: application/json' \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \ 'https://api.mercadopago.com/v1/payments' \ -d '{ "transaction_amount": 100, "token": "ff8080814c11e237014c1ff593b57b4d", "description": "Blue shirt", "installments": 1, "payment_method_id": "visa", "issuer_id": 310, "payer": { "email": "test@test.com" } }'
For the endpoint
/process_payment_ticket
:<?php require_once 'vendor/autoload.php'; MercadoPago\SDK::setAccessToken("ENV_ACCESS_TOKEN"); $payment = new MercadoPago\Payment(); $payment->transaction_amount = 100; $payment->description = "Product title"; $payment->payment_method_id = "rapipago"; $payment->payer = array( "email" => "test@test.com", ); $payment->save(); ?>
var mercadopago = require('mercadopago'); mercadopago.configurations.setAccessToken(config.access_token); var payment_data = { transaction_amount: 100, description: 'Product title', payment_method_id: 'rapipago', payer: { email: 'test@test.com', } }; mercadopago.payment.create(payment_data).then(function (data) { }).catch(function (error) { });
PaymentClient client = new PaymentClient(); PaymentCreateRequest paymentCreateRequest = PaymentCreateRequest.builder() .transactionAmount(new BigDecimal("100")) .description("Product title") .paymentMethodId("rapipago") .dateOfExpiration(OffsetDateTime.of(2023, 1, 10, 10, 10, 10, 0, ZoneOffset.UTC)) .payer( PaymentPayerRequest.builder() .email("test@test.com") .build()) .build(); client.create(paymentCreateRequest);
require 'mercadopago' sdk = Mercadopago::SDK.new('ENV_ACCESS_TOKEN') payment_request = { transaction_amount: 100, description: 'Product title', payment_method_id: 'rapipago', payer: { email: 'test@test.com', } } payment_response = sdk.payment.create(payment_request) payment = payment_response[:response]
using MercadoPago.Config; using MercadoPago.Client.Common; using MercadoPago.Client.Payment; using MercadoPago.Resource.Payment; MercadoPagoConfig.AccessToken = "ENV_ACCESS_TOKEN"; var request = new PaymentCreateRequest { TransactionAmount = 105, Description = "Product title", PaymentMethodId = "rapipago", Payer = new PaymentPayerRequest { Email = "test@test.com", }, }; var client = new PaymentClient(); Payment payment = await client.CreateAsync(request);
import mercadopago sdk = mercadopago.SDK("ENV_ACCESS_TOKEN") payment_data = { "transaction_amount": 100, "description": "Product title", "payment_method_id": "rapipago", "payer": { "email": "test@test.com", } } payment_response = sdk.payment().create(payment_data) payment = payment_response["response"]
curl -X POST \ -H 'accept: application/json' \ -H 'content-type: application/json' \ -H 'Authorization: Bearer ENV_ACCESS_TOKEN' \ 'https://api.mercadopago.com/v1/payments' \ -d '{ "transaction_amount": 100, "description": "Product title", "payment_method_id": "rapipago", "payer": { "email": "test@test.com", } }'
You can find payment status in status value.