diff --git a/.github/assets/badges/ci.svg b/.github/assets/badges/ci.svg new file mode 100644 index 0000000..9d28ca6 --- /dev/null +++ b/.github/assets/badges/ci.svg @@ -0,0 +1 @@ +CI: GitHub ActionsCI · Actions diff --git a/.github/assets/badges/license.svg b/.github/assets/badges/license.svg new file mode 100644 index 0000000..8d5f2db --- /dev/null +++ b/.github/assets/badges/license.svg @@ -0,0 +1 @@ +License: MITlicense · MIT diff --git a/.github/assets/badges/package.svg b/.github/assets/badges/package.svg new file mode 100644 index 0000000..43f41d9 --- /dev/null +++ b/.github/assets/badges/package.svg @@ -0,0 +1 @@ +Package: PyPIpackage · PyPI diff --git a/.github/assets/badges/runtime.svg b/.github/assets/badges/runtime.svg new file mode 100644 index 0000000..49b1b9e --- /dev/null +++ b/.github/assets/badges/runtime.svg @@ -0,0 +1 @@ +Python 3.10 or laterPython · 3.10+ diff --git a/.github/assets/mercado-pago.svg b/.github/assets/mercado-pago.svg new file mode 100644 index 0000000..02d073d --- /dev/null +++ b/.github/assets/mercado-pago.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml new file mode 100644 index 0000000..94f8f71 --- /dev/null +++ b/.github/workflows/documentation.yml @@ -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 "(]+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" diff --git a/README.md b/README.md index 18389dc..fb8c79f 100644 --- a/README.md +++ b/README.md @@ -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. +
+ Mercado Pago +

Mercado Pago SDK for Python

+

The official Mercado Pago SDK for Python applications.

+

Integrate Mercado Pago APIs into your Python application and start receiving payments.

+

+ CI workflow + Python package + Python 3.10 or later + MIT license +

+

+ Installation · + Getting started · + Documentation · + Contributing +

+
+ +--- ## 💡 Requirements -Python 3.9 or higher. +Python 3.10 or higher. -## 📲 Installation +## 📲 Installation Run ```pip3 install mercadopago``` @@ -68,8 +81,9 @@ 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") @@ -77,8 +91,8 @@ 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) @@ -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 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5162318 --- /dev/null +++ b/SECURITY.md @@ -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. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..ccbed0e --- /dev/null +++ b/docs/README.md @@ -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). diff --git a/docs/api-resources.md b/docs/api-resources.md new file mode 100644 index 0000000..076e7fc --- /dev/null +++ b/docs/api-resources.md @@ -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). diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..cfc736b --- /dev/null +++ b/docs/configuration.md @@ -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. diff --git a/docs/error-handling.md b/docs/error-handling.md new file mode 100644 index 0000000..3f36057 --- /dev/null +++ b/docs/error-handling.md @@ -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. diff --git a/docs/pagination.md b/docs/pagination.md new file mode 100644 index 0000000..b227134 --- /dev/null +++ b/docs/pagination.md @@ -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. diff --git a/docs/production-checklist.md b/docs/production-checklist.md new file mode 100644 index 0000000..3e56e97 --- /dev/null +++ b/docs/production-checklist.md @@ -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. diff --git a/docs/retries-and-idempotency.md b/docs/retries-and-idempotency.md new file mode 100644 index 0000000..94fd5fa --- /dev/null +++ b/docs/retries-and-idempotency.md @@ -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. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..6772de5 --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,29 @@ +# Troubleshooting + +## `401 Unauthorized` + +Confirm that `MP_ACCESS_TOKEN` belongs to the intended account and environment. Do not send a public key as an access token. + +## `409` or a reused idempotency key + +Use the same key only when retrying the same logical operation. Use a new key for a new order or payment. + +## `422 Unprocessable Entity` + +Inspect `MPValidationError.causes`. Verify required fields, amounts, currency, payer data, and the selected payment method. + +## Requests time out + +Set `connection_timeout` explicitly and keep retries bounded. A larger timeout does not fix invalid credentials or payloads. + +## Webhook validation fails + +Pass `x-signature`, `x-request-id`, and `data.id` exactly as received. Check the application webhook secret and server clock. + +## An SDK symbol cannot be imported + +Check the installed package version with `python -m pip show mercadopago` and compare it with the repository changelog. + +## Escalating an issue + +Include the SDK and Python versions, operation, HTTP status, request ID, sanitized exception type/message, and a minimal reproduction. Open a repository issue without credentials, card data, webhook secrets, or exploit details. diff --git a/docs/webhooks.md b/docs/webhooks.md new file mode 100644 index 0000000..dd18ffd --- /dev/null +++ b/docs/webhooks.md @@ -0,0 +1,23 @@ +# Validate webhook signatures + +Use `WebhookSignatureValidator` before trusting a signed notification: + +```python +from mercadopago.webhook import WebhookSignatureValidator + +WebhookSignatureValidator.validate( + x_signature=request.headers.get("x-signature"), + x_request_id=request.headers.get("x-request-id"), + data_id=request.args.get("data.id"), + secret=os.environ["MP_WEBHOOK_SECRET"], + tolerance_seconds=300, +) +``` + +The validator uses a constant-time comparison and raises `InvalidWebhookSignatureError` when validation fails. Pass header and query values exactly as received. + +Respond with HTTP `200` or `201` promptly and process business work asynchronously. QR Code notifications are not signed and must not be passed to this validator. + +After validation, deduplicate by notification or resource identifier, enqueue the identifier, and fetch the current resource from Mercado Pago in the worker. Apply changes idempotently because notifications may repeat or arrive out of order. The notification is a change signal; the API lookup is the current resource state. + +Never log the secret or the complete signature. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..5ede68a --- /dev/null +++ b/examples/README.md @@ -0,0 +1,35 @@ +# Python examples + +These programs demonstrate integration flows implemented by the Python SDK. Start with Orders, then choose another API only when the payment product requires it. + +## Orders first + +Orders is the most complete learning path in this repository: it covers creation, retrieval, processing, capture, cancellation, refunds, and transaction management. + +| Stage | Goal | Example | +|---|---|---| +| 1. Create | Submit a basic order | [`create_order.py`](../mercadopago/examples/order/create_order.py) | +| 2. Inspect | Retrieve the server-side result | [`get_order.py`](../mercadopago/examples/order/get_order.py) | +| 3. Advance | Process or capture an order | [`process_order.py`](../mercadopago/examples/order/process_order.py) · [`capture_order.py`](../mercadopago/examples/order/capture_order.py) | +| 4. Reverse | Cancel, partially refund, or fully refund | [`cancel_order.py`](../mercadopago/examples/order/cancel_order.py) · [`refund_partial.py`](../mercadopago/examples/order/refund_partial.py) · [`refund_total.py`](../mercadopago/examples/order/refund_total.py) | +| 5. Manage transactions | Create, update, or delete a transaction | [`create_transaction.py`](../mercadopago/examples/order/create_transaction.py) · [`update_transaction.py`](../mercadopago/examples/order/update_transaction.py) · [`delete_transaction.py`](../mercadopago/examples/order/delete_transaction.py) | +| 6. Add a payment flow | Use Checkout Pro or PSE | [`create_order_checkout_pro.py`](../mercadopago/examples/order/create_order_checkout_pro.py) · [`create_order_pse.py`](../mercadopago/examples/order/create_order_pse.py) | +| 7. Use stored credentials | Create credential-on-file or automatic payments | [`create_order_credential_on_file.py`](order/create_order_credential_on_file.py) · [`create_order_automatic_payment.py`](order/create_order_automatic_payment.py) | + +Before production use, persist the idempotency key and handle typed exceptions. See [retries and idempotency](../docs/retries-and-idempotency.md), [error handling](../docs/error-handling.md), and the [production checklist](../docs/production-checklist.md). + +## Other supported examples + +| Goal | API | Examples | +|---|---|---| +| Create a hosted checkout | Preferences API | [`mercadopago/examples/preference/`](../mercadopago/examples/preference/) | +| Connect a seller account | OAuth API | [`mercadopago/examples/oauth/`](../mercadopago/examples/oauth/) | + +## Before running an example + +1. Install this checkout with `python -m pip install -e .`. +2. Replace placeholders with test credentials and test data. +3. Set a stable `x-idempotency-key` for each logical write. +4. Confirm fields in the [API reference](https://www.mercadopago.com/developers/en/reference). + +Never commit credentials or use production card data in examples. diff --git a/llms.txt b/llms.txt new file mode 100644 index 0000000..1eb075a --- /dev/null +++ b/llms.txt @@ -0,0 +1,36 @@ +# Mercado Pago SDK for Python + +Official server-side Python SDK for Mercado Pago APIs. + +## Start here +- [README](README.md) +- [Documentation index](docs/README.md) +- [API resources](docs/api-resources.md) +- [Examples](examples/README.md) + +## Recommended integration path +- [Orders-first examples](examples/README.md#orders-first) +- [Retries and idempotency](docs/retries-and-idempotency.md) +- [Error handling](docs/error-handling.md) +- [Production checklist](docs/production-checklist.md) + +## Operational guides +- [Configuration](docs/configuration.md) +- [Error handling](docs/error-handling.md) +- [Retries and idempotency](docs/retries-and-idempotency.md) +- [Pagination](docs/pagination.md) +- [Webhook validation](docs/webhooks.md) +- [Troubleshooting](docs/troubleshooting.md) +- [Production checklist](docs/production-checklist.md) + +## Supported examples +- [Example catalog](examples/README.md) +- [Orders](mercadopago/examples/order/) +- [Checkout Pro preferences](mercadopago/examples/preference/) +- [OAuth](mercadopago/examples/oauth/) +- [Automatic payments](examples/order/) + +## Canonical sources +- [Installation](README.md#installation) +- [Mercado Pago API reference](https://www.mercadopago.com/developers/en/reference) +- [Source repository](https://github.com/mercadopago/sdk-python)