Developers
API Reference
Support
Sign in

    Home

    Getting started

    Online Payments

    Checkout Pro

    Checkout API

    Payment Link

    Subscriptions

    Marketplace

    Mobile Checkout

    Web Tokenize Checkout

    In person payments

    QR Code

    Mercado Pago Point

    Plugins and platforms

    WooCommerce

    Prestashop

    Magento 2

    Shopify

    Tiendanube

    VTEX

    SDKs

    Notifications

    Webhooks

    IPN

    Account Management

    Requirements for production environment

    Get payments

    Reports

    Cashback and Cancellations

    Chargeback Management

    Improves approval

    Resources

    Localization

    Changelog

    Status

IN THIS PAGE

Suggest edit
Help us improve the documentation
Did you see wrong information and would you like us to explain something else or improve our manuals? Please leave your suggestions on GitHub.

Receive Payments

Prerequisites
  • This guide presumes that you have already followed the steps in the introduction section of the documentation for installing the SDK.
  • This guide will help you integrate MercadoPago’s visual payment component in your application. This component addresses the selection of the payment method, the collection of data from the payment method of the user and the communication of the payment result.

    The integration consists of two steps:

    • Integration in your server: in this step, you will get the payment information.
    • Integration in your application: in this step, you will configure the visual component.

    scheme

    1. Create the payment preference from your server on MercadoPago’s servers.
    2. Start the checkout in your application, using the preference id.
    3. The Checkout will make the payment on MercadoPago’s servers.
    4. Sign up to receive notifications to find out about new payments and status updates.

    Set up your server

    In order to start the payment flow, you need to get information about the product or service to be paid. This entity is the payment preference and contains:

    1. Description and amount.
    2. Your buyer’s information (email, name, address, etc.).
    3. Payment methods accepted.
    4. Reference ID of your system.
    • php
    • java
    • node
    • ruby
              
    <?php  
      require ('mercadopago.php');
      MercadoPago\SDK::configure(['ACCESS_TOKEN' => 'ENV_ACCESS_TOKEN']);
    ?>
    
            
              
    import com.mercadopago.*;
    MercadoPago.SDK.configure("ENV_ACCESS_TOKEN");
    
            
              
    var mercadopago = require('mercadopago');
    mercadopago.configure({
        access_token: 'ENV_ACCESS_TOKEN'
    });
    
            
              
    require 'mercadopago'
    MercadoPago::SDK.configure(ACCESS_TOKEN: ENV_ACCESS_TOKEN)
    
            

    Then, you must add the attributes of your payment preference:

    • php
    • java
    • javascript
    • ruby
              
    <?php
      $preference = new MercadoPago\Preference();
    
      $item = new MercadoPago\Item();
      $item->title = "Blue shirt";
      $item->quantity = 10;
      $item->currency_id = "MXN";
      $item->unit_price = 150;
    
      $payer = new MercadoPago\Payer();
      $payer->email = "test_user_19653727@testuser.com";
    
      $preference->items = array($item);
      $preference->payer = $payer;
      $preference->save();
    ?>
    
            
              
    Preference preference = new Preference();
    
    Item item = new Item();
    item.setId("1234")
        .setTitle("Blue shirt")
        .setQuantity(10)
        .setCategoryId("MXN")
        .setUnitPrice((float) 150);
    
    Payer payer = new Payer();
    payer.setEmail("john@yourdomain.com");
    
    preference.setPayer(payer);
    preference.appendItem(item);
    preference.save();
    
    
            
              
    var preference = {}
    
    var item = {
      title: 'Blue shirt',
      quantity: 1,
      currency_id: 'MXN',
      unit_price: 150
    }
    
    var payer = {
      email: "demo@mail.com"
    }
    
    preference.items = [item]
    preference.payer = payer
    
    mercadopago.preferences.create(preference).then(function (data) {
       // Do Stuff...
     }).catch(function (error) {
       // Do Stuff...
     });
    
            
              
    preference = MercadoPago::Preference.new()
    
    item = MercadoPago::Item.new()
    item.title="Blue shirt"
    item.quantity= 10
    item.currency_id = 'MXN'
    item.unit_price = 150
    
    payer = MercadoPago::Payer.new()
    payer.email="john@yourdomain.com"
    
    preference.items = [item]
    preference.payer = payer
    
    preference.save
    
            

    Content of the preference

    The more information you send us, the faster is the payment approval and the better is the experience for your users.

    Payer

    You must submit your buyer’s email.

    json

    {
       ...,
      "payer": {
        "name": "Carlota",
        "surname": "Castellanos",
        "email": "john@yourdomain.com",
        "date_created": "2015-06-02T12:58:41.425-04:00",
        "phone": {
          "area_code": "11",
          "number": "619 911 306"
        },
        "identification": {
          "type": "DNI",
          "number": "123456789"
        },
        "address": {
          "street_name": "Insurgentes Sur",
          "street_number": 7304,
          "zip_code": "52"
        }
      },
      ...
    }

    Integrate MercadoPago’s payment flow in your application

    1. Connect your application to your server

    In the SDK, we offer you a class called CustomServer to make the connection to your server easier. The createPreference method makes a POST and sends a map that you can configure to receive extra info (preferenceMap) as the message body. Send us your base URL (https://your-base-url.com) and the URI (/your-create-preference-uri) where you receive the data to create the preference.

    The CustomServer will be responsible for converting your service response (which must have the same structure as that of MercadoPago) into a CheckoutPreference object, whose ID is the entry point to our checkout.

    Create the preference on your server from your application with the following code:

    • android
    • swift
              
    public void submit(View view) {
    // Create a map with payment’s details.
    Map<String, Object> preferenceMap = new HashMap<>();
    preferenceMap.put("item_id", "1");
    preferenceMap.put("amount", new BigDecimal(10));
    preferenceMap.put("currency_id", "MXN");
    preferenceMap.put("payer_email", "john@yourdomain.com");
    
    final Activity activity = this;
    LayoutUtil.showProgressLayout(activity);
    CustomServer.createCheckoutPreference(activity, "https://your-base-url.com", "/your-create-preference-uri", preferenceMap, new Callback<CheckoutPreference>() {
    @Override
    public void success(CheckoutPreference checkoutPreference) {
    startMercadoPagoCheckout(checkoutPreference);
    LayoutUtil.showRegularLayout(activity);
    }
    
    @Override
    public void failure(ApiException apiException) {
    // Ups, something went wrong
    }
    });
    }
    
            
              
            let preferenceBody : [String : Any] = ["item_id" : "id", "quantity" : 10]
    
            CustomServer.createCheckoutPreference(url: "https://your-base-url.com/", uri: "your-create-preference-uri", bodyInfo: preferenceBody as NSDictionary, success: { (checkoutPrefernece) in
                startMercadoPagoCheckout(checkoutPreference)
            }) { (error) in
                // Handle error
            }
    
            

    2. Create a pay button

    As an example, we propose that you initiate the MercadoPago’s flow from a button.

    • android
    • swift
    1. Create an Activity to insert the button (** MainActivity**, for example). 2. Add a text field to show the payment result. 3. Paste the following sample code in res/layout/activity_main.xml.
              
    
    <FrameLayout xmlns:android='http://schemas.android.com/apk/res/android'
    xmlns:tools='http://schemas.android.com/tools'
    android:layout_width='match_parent'
    android:layout_height='match_parent'
    android:paddingLeft='@dimen/activity_horizontal_margin'
    android:paddingRight='@dimen/activity_horizontal_margin'
    android:paddingTop='@dimen/activity_vertical_margin'
    android:paddingBottom='@dimen/activity_vertical_margin'
    android:orientation='vertical'
    tools:context='.MainActivity'>
    <include layout="@layout/mpsdk_view_progress_bar"/>
    <LinearLayout
    android:id="@+id/mpsdkRegularLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <Button
    android:layout_width='match_parent'
    android:layout_height='50dp'
    android:layout_marginTop='25dp'
    android:gravity='center'
    android:text='Pagar $10'
    android:onClick='submit'/>
    
    <TextView
    android:layout_width='match_parent'
    android:layout_height='wrap_content'
    android:id='@+id/mp_results'
    android:paddingTop='50dp'/>
    </LinearLayout>
    </FrameLayout>
    
            
    1. Create a ViewController to insert the button (MainViewController, for example). 2. Insert a button on the corresponding .xib. 3. Add a text field to show the payment result. 4. Paste the following example code on your class MainViewController.swift. 5. In the next step, you will be working on the event associated with the button click (startCheckout).
              
    
    import UIKit
    import MercadoPagoSDK
    
    class MainViewController: UIViewController {
    @IBOutlet weak var payButton: UIButton!
    @IBOutlet weak var paymentResult: UITextField!
    
    override func viewDidLoad() {
    super.viewDidLoad()
    
    self.payButton.addTarget(self,
    action: #selector(MainViewController.startCheckout),
    for: .touchUpInside)
    }
    }
    
            

    3. Start the Checkout

    After creating the payment preference and defining an event from which to start the payment flow, you can start our Checkout with the following code:

    • android
    • swift
              
    private void startMercadoPagoCheckout(CheckoutPreference checkoutPreference) {
      new MercadoPagoCheckout.Builder()
        .setActivity(activity)
        .setPublicKey("ENV_PUBLIC_KEY").setCheckoutPreference(checkoutPreference)
        .startForPayment();
    }
    
            

    The flow of our checkout is based on NavigationController. If your application is also based on NavigationControllers you can start the Checkout flow using the NavigationController of your application, or you can create one, start the Checkout on it, and then present it.

              
    
    public func startMercadoPagoCheckout(_ checkoutPreference CheckoutPreference) {
    
    let checkout = MercadoPagoCheckout(publicKey: "ENV_PUBLIC_KEY", accessToken: nil, checkoutPreference: checkoutPreference,
    navigationController: self.navigationController!)
    
    checkout.start()
    }
    
            

    4. Get the response

    The SDK will always return a payment result.

    In the event of a hard error, or if the user left the flow, it will return an object representing the error so you can understand what happened.

    These are the most important payment attributes:

    • id: Payment identifier.
    • status: Payment status.
    • payment_method_id: Identifier of the payment method selected by your user.
    • payment_type_id: Payment type selected.
    • card: Object that identifies your user’s card.
    • issuer_id: : Identifier of the card bank selected by your user.
    • installments: Number of installments selected.

    The posible payment status are:

    payment-status

    You can get the response with the following code:

    • android
    • swift
              
    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == MercadoPagoCheckout.CHECKOUT_REQUEST_CODE) {
                if (resultCode == MercadoPagoCheckout.PAYMENT_RESULT_CODE) {
                    Payment payment = JsonUtil.getInstance().fromJson(data.getStringExtra("payment"), Payment.class);
                    ((TextView) findViewById(R.id.mp_results)).setText("Resultado del pago: " + payment.getStatus());
                    //Done!
                } else if (resultCode == RESULT_CANCELED) {
                    if (data != null && data.getStringExtra("mercadoPagoError") != null) {
                        MercadoPagoError mercadoPagoError = JsonUtil.getInstance().fromJson(data.getStringExtra("mercadoPagoError"), MercadoPagoError.class);
                        ((TextView) findViewById(R.id.mp_results)).setText("Error: " +  mercadoPagoError.getMessage());
                        //Resolve error in checkout
                    } else {
                        //Resolve canceled checkout
                    }
                }
            }
        }
    
            
              
    MercadoPagoCheckout.setPaymentCallback { (payment) in
    self.payment = payment
    }
    
    checkout.setCallbackCancel {
       // Resolved cancel checkout
       self.navigationController?.popToRootViewController(animated: true)
    }
    
            

    Color settings

    You can change the colors of the graphical interface of the payment flow, as well as make the font darker, by using the DecorationPreference class. You can do this using the following code:

    • android
    • swift
              
    private void startMercadoPagoCheckout(CheckoutPreference checkoutPreference) {
      DecorationPreference decorationPreference = new DecorationPreference.Builder()
        .setBaseColor(ContextCompat.getColor(context, R.color.your_color))
        .enableDarkFont() //Optional
        .build();
    
      new MercadoPagoCheckout.Builder()
        .setActivity(activity)
        .setDecorationPreference(decorationPreference)
        .setPublicKey("ENV_PUBLIC_KEY")
        .setCheckoutPreference(checkoutPreference)
        .startForPayment();
    }
    
            
              
    public func startMercadoPagoCheckout(_ checkoutPreference CheckoutPreference) {
        let decorationPreference: DecorationPreference = DecorationPreference()
        decorationPreference.setBaseColor(color: UIColor.purple)
        decorationPreference.enableDarkFont()
        MercadoPagoCheckout.setDecorationPreference(decorationPreference)
    
        let checkout = MercadoPagoCheckout(publicKey: "ENV_PUBLIC_KEY", accessToken: nil, checkoutPreference: checkoutPreference,
        navigationController: self.navigationController!)
    
        checkout.start()
    }
    
            

    The SDK allows you to set the color in the hexadecimal format, i.e. setBaseColor("#060d72");.

    Enable payment notifications

    Notifications are automatically sent to inform you of any new payments and status updates.

    This will allow you to manage your inventories and keep your system in sync.

    To learn more about it, go to Notifications.

    Test the integration

    You can test the integration before going into production, in order to check the operation and make all the adjustments you need.

    For that, you must use test users and cards.

    For more information, go to the Test section.

    Next steps

    • To adapt the payment flow to your needs, go to the Customization section.
    • For information on how to test, go to the testing integration section.
    Was this information helpful?

    Copyright © 2021 MercadoLibre S. de R.L. de C.V.

    Terms and conditionsHow we take care of your privacy
    Partners Mercado Pago

    Al navegar en este sitio aceptas las cookies que utilizamos para mejorar tu experiencia. Más información.