Mercado Pago Python SDK
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
-
TypeError: __init__() missing 1 required positional argument: 'access_token'
cause Attempting to initialize the `mercadopago.SDK` class without providing the `access_token` argument.fixProvide your Mercado Pago access token when initializing the SDK: `sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN")`. -
{'message': 'Invalid access_token', 'error': 'bad_request', 'status': 400}cause The provided `ACCESS_TOKEN` is incorrect, expired, or malformed, leading to an authentication failure with the Mercado Pago API.fixObtain a valid `ACCESS_TOKEN` from your Mercado Pago developer credentials panel (either production or test credentials) and ensure it is correctly passed to the SDK. Double-check for typos or leading/trailing spaces. -
KeyError: 'response' or KeyError: 'status' when trying to access result['response'] or result['status']
cause The API call resulted in an unexpected response format, possibly due to a network error, a very specific API error not encapsulated as expected, or the SDK itself failing to structure the response.fixAlways check if `result` is not `None` and contains expected keys before accessing them. Add more robust error handling around API calls. For example, `if 'response' in result and 'status' in result:`.
Warnings
- breaking Authentication mechanism changed from `CLIENT_ID`/`CLIENT_SECRET` to `ACCESS_TOKEN` in SDK version 2.x. Older code using `mercadopago.MP("CLIENT_ID", "CLIENT_SECRET")` will fail with the current SDK.
- gotcha When working with front-end components like Mercado Pago Checkout Bricks, the container ID provided to the Brick's creation function must exactly match an already rendered DOM element's ID. Mismatches or attempting to render before the DOM element is ready will result in a 'Container Not Found' error.
- gotcha The Customer Search API (`/v1/customers/search`) might return empty results even if a customer exists in the Mercado Pago dashboard. This can happen if the customer was created through a different flow (e.g., subscriptions) and is not linked to the 'customer' entity directly searchable by email.
Install
-
pip install mercadopago
Imports
- SDK
import mercadopago.MP mp = mercadopago.MP("CLIENT_ID", "CLIENT_SECRET")import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") - RequestOptions
from mercadopago.config import RequestOptions
Quickstart
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}")