Home
Documentation
Resources
Partners
Community

Partners

Discover our program for agencies or developers that offer integration services and sellers who want to hire them.

Community

Get the latest news, ask others for help and share your knowledge.

Default rendering - Payment - Mercado Pago Developers

Intelligent search powered by OpenAI 

Default rendering

Before rendering the Payment Brick, first execute the initialization steps shared among all Bricks. From there, see below the necessary information to configure and render the Payment Brick.

Note
To consult the types and specifications of the parameters and responses of the Brick functions, refer to the technical documentation .

Configure the Brick

Create Brick's startup configuration.

          
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 Account and Installment without a credit card, which have their processing value determined in the backend through the "preferenceId"
     */
     amount: 100,
     preferenceId: "<PREFERENCE_ID>",
   },
   customization: {
     paymentMethods: {
       atm: "all",
       ticket: "all",
       creditCard: "all",
       debitCard: "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 the submit data button
       return new Promise((resolve, reject) => {
         fetch("/process_payment", {
           method: "POST",
           headers: {
             "Content-Type": "application/json",
           },
           body: JSON.stringify(formData),
         })
           .then((response) => response.json())
           .then((response) => {
             // receive payment result
             resolve();
           })
           .catch((error) => {
             // handle error response when trying to create payment
             reject();
           });
       });
     },
     onError: (error) => {
       // callback called for all Brick error cases
       console.error(error);
     },
   },
 };
 window.paymentBrickController = await bricksBuilder.create(
   "payment",
   "paymentBrick_container",
   settings
 );
};
renderPaymentBrick(bricksBuilder);

        
          
const initialization = {
 amount: 100,
 preferenceId: "<PREFERENCE_ID>",
};
const customization = {
 paymentMethods: {
   atm: "all",
   ticket: "all",
   creditCard: "all",
   debitCard: "all",
   mercadoPago: "all",
 },
};
const onSubmit = async (
 { selectedPaymentMethod, formData }
) => {
 // callback called when clicking the submit data button
 return new Promise((resolve, reject) => {
   fetch("/process_payment", {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify(formData),
   })
     .then((response) => response.json())
     .then((response) => {
       // receive payment result
       resolve();
     })
     .catch((error) => {
       // handle error response when trying to create payment
       reject();
     });
 });
};
const onError = async (error) => {
 // callback called for all Brick error cases
 console.log(error);
};
const onReady = async () => {
 /*
   Callback called when Brick is ready.
   Here you can hide loadings from your site, for example.
 */
};

        
Attention
Whenever the user leaves the screen where some Brick is displayed, it is necessary to destroy the current instance with the command window.paymentBrickController.unmount(). When entering again, a new instance must be generated.

To use a payment method (paymentMethods) of the "mercadoPago" type, a preference must be sent during Brick initialization, replacing the value <PREFERENCE_ID> by the ID of the preference created. Instructions for creating the preference are in the Enable payment with Mercado Pago section.

Render the Brick

Once the configurations are created, enter the code below to render the Brick.

Important
The id paymentBrick_container of the html div below should correspond to the value used in the method create() of the last step.
          
<div id="paymentBrick_container"></div>

        
          
import { Payment } from '@mercadopago/sdk-react';

<Payment
   initialization={initialization}
   customization={customization}
   onSubmit={onSubmit}
   onReady={onReady}
   onError={onError}
/>

        

The result of rendering the Brick should look like the image below.

payment-Brick-layout-mlm

Enable payment with Mercado Pago

To use a payment method (paymentMethods) of the "mercadoPago" type, a preference must be sent during Brick initialization, replacing the value <PREFERENCE_ID> by the ID of the preference created.

To create a preference in your backend, add the Mercado Pago SDK and the necessary credentials to your project to enable the preference usage:

          
<?php
// Mercado Pago SDK
require __DIR__ .  '/vendor/autoload.php';
// Add Your credentials
MercadoPago\SDK::setAccessToken('PROD_ACCESS_TOKEN');
?>

        
          
// Mercado Pago SDK
const mercadopago = require ('mercadopago');
// Add Your credentials
mercadopago.configure({
  access_token: 'PROD_ACCESS_TOKEN'
});

        
          
// Mercado Pago SDK
import com.mercadopago.MercadoPagoConfig;
// Add Your credentials
MercadoPagoConfig.setAccessToken("PROD_ACCESS_TOKEN");

        
          
# Mercado Pago SDK
require 'mercadopago'
# Add Your credentials
sdk = Mercadopago::SDK.new('PROD_ACCESS_TOKEN')

        
          
// Mercado Pago SDK
 using MercadoPago.Config;
 // Add Your credentials
MercadoPagoConfig.AccessToken = "PROD_ACCESS_TOKEN";

        
          
# Mercado Pago SDK
import mercadopago
# Add Your credentials
sdk = mercadopago.SDK("PROD_ACCESS_TOKEN")

        

Then set the preference according to your product or service.

The code examples below set the purpose of preference to wallet_purchase, but it is also possible to set it to onboarding_credits. Understand the difference between the two:

  • wallet_purchase: the user must log in when redirected to his Mercado Pago account.

  • onboarding_credits: after logging in, the user will see the pre-selected credit payment option in his Mercado Pago account.

            
    <?php
    $client = new PreferenceClient();
    $preference = $client->create([
      "items"=> array(
        array(
          "title" => "My product",
          "quantity" => 1,
          "unit_price" => 25
        )
      )
    ]);
    ?>
    
          
            
    // Create a preference object
    let preference = {
      // o "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);
      });
    
          
            
    // Create a preference object
    PreferenceClient client = new PreferenceClient();
    
    // Create an item in the preference
    List<PreferenceItemRequest> items = new ArrayList<>();
    PreferenceItemRequest item =
       PreferenceItemRequest.builder()
           .title("Meu produto")
           .quantity(1)
           .unitPrice(new BigDecimal("100"))
           .build();
    items.add(item);
    
    PreferenceRequest request = PreferenceRequest.builder()
      // o .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);
    
          
            
    # 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']
    
          
            
    // 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);
    
          
            
    # 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
          }
      ]
    }'
    
          
Important
For more details on how to configure it, access the Preferences section.

Consider that when a user chooses to make a payment using the Mercado Pago Wallet, he will be redirected to the Mercado Pago page to complete the payment. Therefore, it is necessary to configure the back_urls if you want to return to your site at the end of the payment. For more information, visit the Redirect buyer to your website section.