Mercado Pago Python SDK

2.3.0 · active · verified Thu Apr 16

The Mercado Pago SDK for Python provides developers with a simple set of bindings to integrate with the Mercado Pago API and process payments. It is actively maintained with frequent minor releases, currently at version 2.3.0, and simplifies server-side operations like creating and managing payment preferences, processing transactions, and handling refunds or chargebacks.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Mercado Pago SDK with your access token and create a basic payment preference. Replace 'YOUR_ACCESS_TOKEN' with your actual production access token or set it as an environment variable `MERCADO_PAGO_ACCESS_TOKEN` for security. The example creates a checkout preference for a single item and prints the resulting payment links.

import os
import mercadopago
from mercadopago.config import RequestOptions

ACCESS_TOKEN = os.environ.get('MERCADO_PAGO_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN')

if not ACCESS_TOKEN or ACCESS_TOKEN == 'YOUR_ACCESS_TOKEN':
    print("Error: MERCADO_PAGO_ACCESS_TOKEN environment variable is not set or is default.")
    print("Please set it with your actual Mercado Pago Access Token.")
else:
    try:
        sdk = mercadopago.SDK(ACCESS_TOKEN)

        # Example: Create a payment preference
        preference_data = {
            "items": [
                {
                    "title": "My Product",
                    "quantity": 1,
                    "currency_id": "BRL",
                    "unit_price": 75.56
                }
            ],
            "payer": {
                "email": "test_user_123456@testuser.com"
            },
            "back_urls": {
                "success": "https://www.your-site.com/success",
                "failure": "https://www.your-site.com/failure",
                "pending": "https://www.your-site.com/pending"
            },
            "auto_return": "approved"
        }

        # Optional: Per-request configuration for custom headers or different credentials
        # request_options = RequestOptions()
        # request_options.custom_headers = { 'X-Idempotency-Key': 'some_unique_value' }
        # result = sdk.preference().create(preference_data, request_options)

        result = sdk.preference().create(preference_data)

        if result["status"] == 201:
            preference = result["response"]
            print("Preference created successfully:")
            print(f"ID: {preference['id']}")
            print(f"Init Point: {preference['init_point']}")
            print(f"Sandbox Init Point: {preference['sandbox_init_point']}")
        else:
            print(f"Error creating preference: {result['status']} - {result['response']}")

    except Exception as e:
        print(f"An unexpected error occurred: {e}")

view raw JSON →