Receive Payments
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.
- Create the payment preference from your server on MercadoPago’s servers.
- Start the checkout in your application, using the preference id.
- The Checkout will make the payment on MercadoPago’s servers.
- 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:
- Description and amount.
- Your buyer’s information (email, name, address, etc.).
- Payment methods accepted.
- Reference ID of your system.
<?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)
using MercadoPago;
MercadoPago.SDK.SetAccessToken = "ENV_ACCESS_TOKEN";
Then, you must add the attributes of your payment preference:
<?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
Preference preference = new Preference();
preference.Items.Add(
new Item()
{
Id = "1234",
Title = "Blue shirt",
Quantity = 10,
CurrencyId = "MXN",
UnitPrice = (float)150
}
preference.Payer = new Payer()
{
Email = "john@yourdomain.com"
};
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"
},
"address": {
"street_name": "Insurgentes Sur",
"street_number": 7304,
"zip_code": "52"
}
},
...
}
Integrate MercadoPago’s payment flow in your application
1. Create a pay button
As an example, we propose that you initiate the MercadoPago’s flow from a button.
- 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='startMercadoPagoCheckout'/>
<TextView
android:layout_width='match_parent'
android:layout_height='wrap_content'
android:id='@+id/mp_results'
android:paddingTop='50dp'/>
</LinearLayout>
</FrameLayout>
- 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 (startMercadoPagoCheckout).
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.startMercadoPagoCheckout),
for: .touchUpInside)
}
}
2. 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:
To start the checkout you need to call startPayment passing as arguments the Android context and a RequestCode which is the number that will identify the checkout response in the method onActivityResult.
private static final int REQUEST_CODE = 1;
private void startMercadoPagoCheckout(final String checkoutPreferenceId) {
new MercadoPagoCheckout.Builder("ENV_PUBLIC_KEY", checkoutPreferenceId).build()
.startPayment(MainActivity.this, REQUEST_CODE);
}
@IBAction func startMercadoPagoCheckout(_ sender: Any) {
MercadoPagoCheckout.init(builder: MercadoPagoCheckoutBuilder.init(publicKey: "ENV_PUBLIC_KEY", preferenceId: checkoutPreferenceId))
.start(navigationController: self.navigationController!)
}
3. 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:
You can get the response with the following code:
Use the RequestCode that you sent on startPayment to obtain the checkout result on onActivityResult.
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == MercadoPagoCheckout.PAYMENT_RESULT_CODE) {
final Payment payment = (Payment) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_PAYMENT_RESULT);
((TextView) findViewById(R.id.mp_results)).setText("Resultado del pago: " + payment.getStatus());
//Done!
} else if (resultCode == RESULT_CANCELED) {
if (data != null && data.getExtras() != null
&& data.getExtras().containsKey(MercadoPagoCheckout.EXTRA_ERROR)) {
final MercadoPagoError mercadoPagoError =
(MercadoPagoError) data.getSerializableExtra(MercadoPagoCheckout.EXTRA_ERROR);
((TextView) findViewById(R.id.mp_results)).setText("Error: " + mercadoPagoError.getMessage());
//Resolve error in checkout
} else {
//Resolve canceled checkout
}
}
}
}
Implement PXLifeCycleProtocol protocol to be able to obtain the checkout result, and pass it as an argument on the checkout initialization. The methods that must be implemented are finishCheckout and cancelCheckout as it is shown in the next example. When you implement this protocol you are responsible for finishing the checkout flow, in this example we execute popToRootViewController to close the checkout.
@IBAction func startMercadoPagoCheckout(_ sender: Any) {
MercadoPagoCheckout.init(builder: MercadoPagoCheckoutBuilder.init(publicKey: "ENV_PUBLIC_KEY", preferenceId: checkoutPreferenceId))
.start(navigationController: self.navigationController!, lifeCycleProtocol: self)
}
func finishCheckout() -> ((_ payment: PXResult?) -> Void)? {
return ({ (_ payment: PXResult?) in
print(payment)
self.navigationController?.popToRootViewController(animated: false)
})
}
func cancelCheckout() -> (() -> Void)? {
return {
self.navigationController?.popToRootViewController(animated: true)
}
}
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.
Prevent payment rejection
A payment can be rejected because the issuer for the selected method detected a problem or because of non-compliance with security requirements.
Avoid rejected payments with our recommendations and improve the approval process.
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.