Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/assets/badges/ci.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions .github/assets/badges/license.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions .github/assets/badges/package.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions .github/assets/badges/runtime.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions .github/assets/mercado-pago.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
103 changes: 103 additions & 0 deletions .github/workflows/documentation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
name: Documentation quality

on:
pull_request:
paths:
- '**/*.md'
- 'llms.txt'
- '.github/assets/**'
- '.github/workflows/documentation.yml'
push:
paths:
- '**/*.md'
- 'llms.txt'
- '.github/assets/**'
- '.github/workflows/documentation.yml'

permissions:
contents: read

jobs:
local-links:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4
- name: Validate local documentation links
shell: bash
run: |
set -euo pipefail
failed=0

while IFS= read -r file; do
case "$file" in
README.md|SECURITY.md|llms.txt|docs/*.md|guides/*.md|docs/guides/*.md|examples/README.md|src/examples/README.md|src/main/java/com/mercadopago/example/README.md)
;;
*)
continue
;;
esac

while IFS= read -r raw; do
target="${raw#](}"
target="${target%%#*}"

case "$target" in
""|http://*|https://*|mailto:*|\#*)
continue
;;
esac

if [[ ! -e "$(dirname "$file")/$target" ]]; then
echo "::error file=$file::Broken local link: $target"
failed=1
fi
done < <(grep -oE '\]\([^)[:space:]]+' "$file" || true)
done < <(git ls-files '*.md' 'llms.txt')

exit "$failed"

- name: Require repository-local documentation images
shell: bash
run: |
set -euo pipefail
failed=0

while IFS= read -r file; do
case "$file" in
README.md|SECURITY.md|llms.txt|docs/*.md|guides/*.md|docs/guides/*.md|examples/README.md|src/examples/README.md|src/main/java/com/mercadopago/example/README.md)
;;
*)
continue
;;
esac

if grep -nE "(<img[^>]+src=['\"]https?://|!\[[^]]*\]\(https?://)" "$file"; then
echo "::error file=$file::Documentation images must be stored in this repository"
failed=1
fi
done < <(git ls-files '*.md' 'llms.txt')

exit "$failed"

- name: Allow only Mercado Pago and repository links
shell: bash
run: |
set -euo pipefail
failed=0

while IFS= read -r file; do
case "$file" in
docs/apidocs/*|docs/sdk/*) continue ;;
README.md|SECURITY.md|llms.txt|docs/*.md|guides/*.md|docs/guides/*.md|examples/README.md|src/examples/README.md|src/main/java/com/mercadopago/example/README.md) ;;
*) continue ;;
esac

while IFS= read -r url; do
case "$url" in
https://github.com/mercadopago/*|https://mercadopago.github.io/*|https://mercadopago.com|https://mercadopago.com/*|https://*.mercadopago.com|https://*.mercadopago.com/*|https://mercadopago.com.ar|https://mercadopago.com.ar/*|https://*.mercadopago.com.ar|https://*.mercadopago.com.ar/*|https://mercadopago.com.br|https://mercadopago.com.br/*|https://*.mercadopago.com.br|https://*.mercadopago.com.br/*) ;;
*) echo "::error file=$file::External link is not approved: $url"; failed=1 ;;
esac
done < <(grep -oE 'https?://[^)"[:space:]<>]+' "$file" || true)
done < <(git ls-files '*.md' 'llms.txt')

exit "$failed"
53 changes: 32 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
# Mercado Pago SDK for Python

[![PyPI](https://img.shields.io/pypi/v/mercadopago.svg)](https://pypi.python.org/pypi/mercadopago)
[![PyPI Downloads](https://img.shields.io/pypi/dm/mercadopago.svg)](https://pypi.python.org/pypi/mercadopago)
[![APM](https://img.shields.io/apm/l/vim-mode)](https://github.com/mercadopago/sdk-python)

This library provides developers with a simple set of bindings to help you integrate Mercado Pago API to a website and start receiving payments.
<div align="center">
<img src=".github/assets/mercado-pago.svg" alt="Mercado Pago" width="120" />
<h1>Mercado Pago SDK for Python</h1>
<p><strong>The official Mercado Pago SDK for Python applications.</strong></p>
<p>Integrate Mercado Pago APIs into your Python application and start receiving payments.</p>
<p>
<a href="https://github.com/mercadopago/sdk-python/actions/workflows/ci.yml"><img src=".github/assets/badges/ci.svg" alt="CI workflow" /></a>
<a href="#installation"><img src=".github/assets/badges/package.svg" alt="Python package" /></a>
<img src=".github/assets/badges/runtime.svg" alt="Python 3.10 or later" />
<a href="LICENSE"><img src=".github/assets/badges/license.svg" alt="MIT license" /></a>
</p>
<p>
<a href="#installation">Installation</a> ·
<a href="#getting-started">Getting started</a> ·
<a href="#documentation">Documentation</a> ·
<a href="#contributing">Contributing</a>
</p>
</div>

---

## 💡 Requirements

Python 3.9 or higher.
Python 3.10 or higher.

## 📲 Installation
## 📲 Installation

Run ```pip3 install mercadopago```

Expand Down Expand Up @@ -68,17 +81,18 @@ fields are omitted from the JSON body automatically, matching the `dict` route.

```python
import mercadopago
from mercadopago.resources.order_create import OrderCreateRequest, OrderPayerRequest
from mercadopago.resources.order_item import OrderItemRequest
from mercadopago.resources.order_create import OrderCreateRequest
from mercadopago.resources.payer import PayerRequest
from mercadopago.resources.item import ItemRequest

sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN")

order = OrderCreateRequest(
type="online",
total_amount="100.00",
external_reference="ext_ref_1234",
payer=OrderPayerRequest(email="test_user_123456@testuser.com"),
items=[OrderItemRequest(title="A book", unit_price="100.00", quantity=1)],
payer=PayerRequest(email="test_user_123456@testuser.com"),
items=[ItemRequest(title="A book", unit_price="100.00", quantity=1)],
)

result = sdk.order().create(order)
Expand Down Expand Up @@ -132,15 +146,12 @@ result = sdk.payment().create(payment_data, request_options)
payment = result["response"]
```

## 📚 Documentation

Visit our Dev Site for further information regarding:
- [APIs](https://www.mercadopago.com/developers/en/reference)
- [Checkout Pro](https://www.mercadopago.com/developers/en/guides/online-payments/checkout-pro/introduction)
- [Checkout API](https://www.mercadopago.com/developers/en/guides/online-payments/checkout-api/introduction)
- [Web Tokenize Checkout](https://www.mercadopago.com/developers/en/guides/online-payments/web-tokenize-checkout/introduction)
## 📚 Documentation

Check our official code reference to explore all available functionalities.
- [SDK guides](docs/README.md): configuration, errors, retries, pagination, and webhooks.
- [Examples](examples/README.md): runnable integration flows supported by this SDK.
- [API resources](docs/api-resources.md): SDK clients and their common operations.
- [API reference](https://www.mercadopago.com/developers/en/reference): request fields and response schemas.

## 🤝 Contributing

Expand Down
14 changes: 14 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Security policy

## Report a vulnerability

Open an [issue in this repository](https://github.com/mercadopago/sdk-python/issues/new/choose) with the affected SDK version, impact, and a minimal reproduction.

Do not include credentials, tokens, signatures, personal data, complete API responses, or exploit details in a public issue. If the report requires sensitive information, provide only a non-sensitive summary and ask the maintainers for a private disclosure channel.

## Credential safety

- Keep access tokens and OAuth client secrets in a secret manager or environment variable.
- Use server-side code for private credentials.
- Validate webhook signatures before processing signed notifications.
- Rotate any credential that was committed or logged.
23 changes: 23 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Mercado Pago Python SDK documentation

Use the root README to install the SDK and send a first request. This index provides the shortest path from a runnable Orders example to a production-ready integration.

## Start with Orders

Orders is the recommended learning path because it demonstrates the complete payment lifecycle. Begin with [create_order](../mercadopago/examples/order/create_order.py), inspect the result with [get_order](../mercadopago/examples/order/get_order.py), and continue with [process_order](../mercadopago/examples/order/process_order.py), [capture_order](../mercadopago/examples/order/capture_order.py), [cancel_order](../mercadopago/examples/order/cancel_order.py), or [refund_total](../mercadopago/examples/order/refund_total.py).

Before production traffic, configure [retries and idempotency](retries-and-idempotency.md), [typed errors](error-handling.md), and the [production checklist](production-checklist.md). The [Orders-first example catalog](../examples/README.md#orders-first) also covers Checkout Pro, transactions, PSE, stored credentials, and automatic payments.

## Operational guides

| Question | Guide |
|---|---|
| How should credentials and request options be configured? | [Configuration](configuration.md) |
| How should failures be classified? | [Error handling](error-handling.md) |
| When is a repeated write safe? | [Retries and idempotency](retries-and-idempotency.md) |
| How should search results be iterated? | [Pagination](pagination.md) |
| How should signed notifications be processed? | [Webhook validation](webhooks.md) |
| Which resources are exposed? | [API resources](api-resources.md) |
| What should be checked before launch or during an incident? | [Production checklist](production-checklist.md) · [Troubleshooting](troubleshooting.md) |

Endpoint fields and response schemas belong to the [Mercado Pago API reference](https://www.mercadopago.com/developers/en/reference).
14 changes: 14 additions & 0 deletions docs/api-resources.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Supported API resources

The `SDK` object exposes resource clients through methods such as `sdk.order()` and `sdk.payment()`.

| API area | SDK resource | Common operations |
|---|---|---|
| Orders | `sdk.order()` | create, get, search, capture, process, cancel, refund |
| Payments | `sdk.payment()` | create, get, search, update, capture, cancel |
| Preferences | `sdk.preference()` | create, get, search, update |
| Customers | `sdk.customer()` | create, get, search, update, cards |
| Subscriptions | `sdk.preapproval()` | create, get, search, update |
| OAuth | `sdk.oauth()` | authorization URL, create token, refresh token |

Additional resources cover cards, chargebacks, refunds, invoices, merchant orders, payment methods, identification types, users, and advanced payments. Confirm endpoint fields in the [API reference](https://www.mercadopago.com/developers/en/reference).
32 changes: 32 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Configure the Python SDK

Create one `SDK` instance with an access token stored outside source control:

```python
import os
import mercadopago

sdk = mercadopago.SDK(os.environ["MP_ACCESS_TOKEN"])
```

All API methods accept an optional `RequestOptions` instance for a single call:

```python
from mercadopago.config import RequestOptions

options = RequestOptions(
access_token=os.environ["MP_ACCESS_TOKEN"],
connection_timeout=30.0,
max_retries=3,
custom_headers={"x-idempotency-key": "order-2026-0001"},
)
result = sdk.order().get("ORDER_ID", options)
```

`RequestOptions` also supports `corporation_id`, `integrator_id`, `platform_id`, retry delays, jitter, custom retry status codes, and an `on_retry` callback. Prefer per-request overrides when different credentials or policies share one process.

Create and reuse the `SDK` instance for the lifetime of the application instead of rebuilding it inside every handler. Treat `connection_timeout` as a per-attempt limit: retry delays can make the complete operation longer, so keep the combined worst case below the request or job deadline.

If multiple seller credentials share a process, pass the correct token in request-scoped options and keep tenant selection outside user-controlled headers. Corporation, integrator, and platform identifiers are partner metadata; set them only when they were assigned to the integration.

Never log an access token or commit it to the repository.
28 changes: 28 additions & 0 deletions docs/error-handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Handle errors in the Python SDK

The SDK raises subclasses of `MercadoPagoError` for API failures. Catch the most specific error you can recover from, then keep a final base-class handler.

```python
from mercadopago.errors import MPRateLimitError, MPValidationError, MercadoPagoError

try:
result = sdk.order().create(order_data, request_options)
except MPRateLimitError as error:
print("Retry after:", error.retry_after)
except MPValidationError as error:
print("Invalid request:", error.causes)
except MercadoPagoError as error:
print(error.status_code, error.error, error.request_id)
```

| Status | Exception | Typical action |
|---|---|---|
| 400 | `MPBadRequestError` | Fix syntax or required fields. |
| 401 | `MPAuthenticationError` | Replace the access token. |
| 409 | `MPIdempotencyError` | Check the idempotency key and previous result. |
| 422 | `MPValidationError` | Fix business-rule violations. |
| 423 | `MPResourceLockedError` | Retry later with the same idempotency key. |
| 429 | `MPRateLimitError` | Honor `retry_after`. |
| 5xx | `MPServerError` | Retry with a bounded policy. |

`MPConnectionError` represents failures where no HTTP response was received. See [retries and idempotency](retries-and-idempotency.md) before retrying a write.
14 changes: 14 additions & 0 deletions docs/pagination.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Paginate search results

Search methods accept filters such as `limit` and `offset`. Resources including payments, customers, preferences, and subscriptions also expose `search_auto_paging_iter`.

```python
for payment in sdk.payment().search_auto_paging_iter({"sort": "date_created"}, limit=100):
print(payment["id"])
```

The iterator requests additional pages lazily. Stop the loop when you have enough results, and handle `MercadoPagoError` around the iteration because a later page can fail independently.

Use `search()` directly when you need paging metadata or explicit control over `limit` and `offset`.

For long-running jobs, make item processing idempotent and persist a business checkpoint. Automatic pagination removes offset boilerplate, but it is not a transactional snapshot: records can change while pages are being read, and a restarted scan can encounter an item again.
32 changes: 32 additions & 0 deletions docs/production-checklist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Production checklist

Use this checklist after the first successful sandbox request and before sending production traffic.

## Credentials and isolation

- Load access tokens and webhook secrets from a secret manager or environment variables.
- Confirm that production and test credentials cannot be selected by untrusted input.
- Set corporation, integrator, or platform identifiers only when assigned to the integration.

## Reliable writes

- Generate and persist one idempotency key per logical write operation.
- Reuse that key only for retries of the same payload.
- Reconcile an unknown outcome after a timeout or `MPConnectionError` before writing again.
- Keep SDK, framework, and queue retries within one bounded end-to-end deadline.

## Webhooks

- Validate signatures before trusting signed notifications.
- Keep server clocks synchronized and choose an explicit timestamp tolerance.
- Deduplicate deliveries, acknowledge promptly, and process asynchronously.
- Fetch the current API resource and make state transitions idempotent.

## Observability and support

- Record operation name, latency, attempt count, status, SDK error type, request ID, and an application correlation ID.
- Alert on sustained authentication, validation, rate-limit, and server-error changes separately.
- Exclude credentials, card data, full request bodies, webhook secrets, and complete signatures from logs.
- Pin a tested SDK version and review release notes before upgrading.

Keep a minimal sanitized reproduction and the installed SDK/Python versions available for repository issues.
22 changes: 22 additions & 0 deletions docs/retries-and-idempotency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Retries and idempotency

`RequestOptions` defaults to three retries. The policy can be changed per request with `max_retries`, `initial_delay`, `max_delay`, `jitter`, and `retry_on`.

```python
from mercadopago.config import RequestOptions

options = RequestOptions(
access_token=os.environ["MP_ACCESS_TOKEN"],
max_retries=3,
initial_delay=250,
max_delay=5_000,
jitter=True,
custom_headers={"x-idempotency-key": "checkout-0001"},
)
```

Use one stable idempotency key for every logical write operation. Reuse it when retrying the same operation; generate a new key for a new operation. The SDK generates a key when none is supplied, but an application-owned key is safer when a retry can happen across processes.

Persist the key beside the internal order or command before sending the request. After a timeout or `MPConnectionError`, reconcile by resource ID or external reference before repeating the write: the API may have completed it even though the response never arrived. Request option validation accepts keys from 1 to 64 characters.

Retry transport failures, `423`, `429`, and transient `5xx` responses. Do not blindly retry validation or authentication failures. Honor `Retry-After` when present.
Loading
Loading