pax_global_header00006660000000000000000000000064152441215520014513gustar00rootroot0000000000000052 comment=b345a69f646103c84cebcbe37b9dd0e9777cc696 mercadopago-sdk-python-b345a69/000077500000000000000000000000001524412155200164315ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/.github/000077500000000000000000000000001524412155200177715ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/.github/ISSUE_TEMPLATE/000077500000000000000000000000001524412155200221545ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/.github/ISSUE_TEMPLATE/bug_report.yml000066400000000000000000000115251524412155200250530ustar00rootroot00000000000000name: πŸ› Bug Report description: Report a bug or unexpected behavior in the SDK title: "[BUG]: " labels: ["bug"] assignees: ["luismeli10","orojaspardo","barajas-d"] body: - type: markdown attributes: value: | ## πŸ› Thanks for reporting this issue! Please make sure you tested with the latest version of the relevant packages and/or checked existing issues to avoid duplicates. If the bug persists, open the issue with a clear and concise description including screenshots, if applicable. We appreciate your feedback! **Before reporting a bug:** - πŸ” **Search [existing issues](./issues?q=is%3Aissue) to avoid duplicates** - πŸ“š **Verify you are using the [latest version](../../releases)** - πŸ’‘ **Try to reproduce the problem in sandbox environment** - ⚠️ **IMPORTANT: Your bug will be resolved faster if you can share a self-contained example that doesn't rely on internal or private dependencies.** > **πŸ”’ SECURITY WARNING:** Issues without reproduction steps or code examples may be immediately closed as not actionable. Always remember to **REMOVE ALL PII AND PERSONAL INFORMATION** from your examples. **Bugs opened with real data will be immediately reported and closed.** - type: input id: sdk-version attributes: label: πŸ“¦ SDK Version description: "Example: 2.1.0" placeholder: "x.y.z" validations: required: true - type: textarea id: environment-details attributes: label: πŸ–₯️ Environment Details description: | System and dependencies information placeholder: | - Operating System: [e.g. Ubuntu 20.04, Windows 11, macOS 13] - Language Version: [e.g. Python 3.9.0, Node.js 18.0.0] - Framework: [e.g. Django 4.0, Express 4.18] - Package Manager: [e.g. pip 21.0, npm 8.0] - Other relevant dependencies: ... validations: required: true - type: dropdown id: country attributes: label: 🌎 Country description: Country where the issue occurs options: - Argentina (MLA) - Brazil (MLB) - Chile (MLC) - Colombia (MCO) - Mexico (MLM) - Peru (MPE) - Uruguay (MLU) - Other validations: required: true - type: textarea id: description attributes: label: πŸ“ Bug Description description: A clear and concise description of what the bug is placeholder: The SDK fails when I try to... validations: required: true - type: textarea id: expected attributes: label: βœ… Expected Behavior description: A clear description of the behavior you expected from the SDK placeholder: I expected the SDK to... validations: required: true - type: textarea id: actual attributes: label: ❌ Actual Behavior description: A description of what the SDK actually does instead placeholder: Instead, the SDK... validations: required: true - type: textarea id: reproduce attributes: label: πŸ”„ Steps To Reproduce description: Detailed steps to reproduce the problem placeholder: | 1. Configure the SDK with... 2. Execute the method... 3. Send the following parameters... 4. Observe the error... validations: required: true - type: textarea id: code-sample attributes: label: πŸ’» Code Example description: | Minimal code that reproduces the problem. **REMOVE ALL CREDENTIALS AND SENSITIVE DATA.** You can provide: - A CodeSandbox (https://codepen.io/pen/) - A link to a GitHub repository - A minimal code example that reproduces the problem - A screenshot of the application if you think it is relevant **Remember to REMOVE ALL SENSITIVE DATA FIRST.** render: python placeholder: | import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # ⚠️ DO NOT USE REAL TOKENS # Your code here that reproduces the bug... validations: required: true - type: textarea id: error-logs attributes: label: πŸ“‹ Logs and Error Messages description: Copy complete logs, stack traces, or error messages render: shell placeholder: | Error: ... Stack trace: ... - type: checkboxes id: checklist attributes: label: βœ… Checklist options: - label: I have verified that I am using the latest SDK version required: true - label: I have searched existing issues and this bug has not been reported required: true - label: I have included a minimal code example to reproduce the problem required: true - label: I have removed all sensitive information (tokens, credentials, real data) required: truemercadopago-sdk-python-b345a69/.github/ISSUE_TEMPLATE/config.yml000066400000000000000000000006061524412155200241460ustar00rootroot00000000000000blank_issues_enabled: false contact_links: - name: Support Center Mercado Pago - ES url: https://www.mercadopago.com/developers/es/support/center about: Problems with payments, account, or general inquiries - name: Support Center Mercado Pago - PT url: https://www.mercadopago.com/developers/pt/support/center about: Problems with payments, account, or general inquiriesmercadopago-sdk-python-b345a69/.github/ISSUE_TEMPLATE/feature_request.yml000066400000000000000000000052321524412155200261040ustar00rootroot00000000000000name: ✨ Feature Request description: Propose a new feature for the Mercado Pago SDK title: "[FEATURE]: " labels: ["enhancement"] assignees: ["luismeli10","orojaspardo","barajas-d"] body: - type: markdown attributes: value: | ## πŸ’‘ Thanks for contributing with ideas! Your feedback is valuable to improve the SDK. Before submitting: - πŸ” **Search [existing issues](./issues?q=is%3Aissue) to avoid duplicates**. - πŸ“š **Check the [documentation](https://www.mercadopago.com/developers/es/docs) to confirm this isn't already supported**. - type: dropdown id: feature-type attributes: label: βš™οΈ Feature Type description: What type of improvement are you proposing? options: - New feature - Enhancement of existing feature - Support for new Mercado Pago product - Better error handling - Documentation improvement - Performance optimization - Other validations: required: true - type: textarea id: problem attributes: label: 🎯 Problem to solve description: Describe the problem or need this feature would solve. placeholder: | As a developer of [application type]... I need [feature]... To be able to [goal]... validations: required: true - type: textarea id: solution attributes: label: πŸ’‘ Proposed Solution description: Describe how you would like this new feature to work. placeholder: | I would like the SDK to support... The implementation could be... Usage example: ``` // example code ``` validations: required: true - type: textarea id: alternatives attributes: label: πŸ”„ Alternatives Considered description: | Have you tried any workarounds? Are there similar features in other SDKs or libraries? placeholder: | - Alternative 1: ... - Alternative 2: ... - In the [language] SDK they do... - type: checkboxes id: checklist attributes: label: βœ… Checklist options: - label: I have searched existing issues and this feature has not been requested before required: true - label: I have clearly described the problem I am trying to solve required: true - label: I have proposed a concrete solution or API design required: true - label: This feature would benefit other users, not just my specific use case required: true - label: I have not included any sensitive information (tokens, credentials, real data) required: truemercadopago-sdk-python-b345a69/.github/ISSUE_TEMPLATE/question.yml000066400000000000000000000055761524412155200245630ustar00rootroot00000000000000name: πŸ’¬ Question description: Ask a question about the Mercado Pago SDK title: "[QUESTION]: " labels: ["question"] assignees: ["luismeli10","orojaspardo","barajas-d"] body: - type: markdown attributes: value: | ## πŸ‘‹ Thanks for using the Mercado Pago SDK! Before asking your question, please: - πŸ” **Search [existing issues](./issues?q=is%3Aissue) to see if it was already answered** - πŸ“š **Check the [official documentation](https://www.mercadopago.com/developers/es/docs)** - πŸ’‘ **Review the repository examples** - type: input id: sdk-version attributes: label: πŸ“¦ SDK Version description: "Example: 2.1.0" placeholder: "x.y.z" validations: required: true - type: dropdown id: country attributes: label: 🌎 Country description: In which country are you operating? options: - Argentina (MLA) - Brazil (MLB) - Chile (MLC) - Colombia (MCO) - Mexico (MLM) - Peru (MPE) - Uruguay (MLU) - Other validations: required: true - type: textarea id: context attributes: label: πŸ–₯️ Environment Details description: | Provide details about your environment to help us understand your setup: - Platform (Web, Mobile, Backend) - Framework used - Relevant error messages - Documentation consulted placeholder: | - Platform: [e.g. Backend, Web, Mobile] - Language Version: [e.g. Python 3.9.0, Node.js 18.0.0] - Framework: [e.g. Django 4.0, Express 4.18] - Other relevant dependencies: ... - type: textarea id: question attributes: label: ❓ Your Question description: Ask your question as clearly and specifically as possible. The more detail you provide, the faster we can help. placeholder: | What are you trying to do? What have you tried so far? What is the result you are getting vs. what you expected? Is there an error message involved? validations: required: true - type: textarea id: code-sample attributes: label: πŸ’» Code Example (optional) description: If applicable, share a code snippet that illustrates your question. **Remember to remove all sensitive data (tokens, credentials, etc)** render: python placeholder: | import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # ⚠️ DO NOT USE REAL TOKENS # Your code here... - type: checkboxes id: checklist attributes: label: βœ… Checklist options: - label: I have searched existing issues required: true - label: I have checked the official documentation required: true - label: I have removed sensitive information (tokens, credentials, etc) required: truemercadopago-sdk-python-b345a69/.github/dependabot.yml000066400000000000000000000026001524412155200226170ustar00rootroot00000000000000# Dependabot version updates β€” sdk-python # UbicaciΓ³n obligatoria: .github/dependabot.yml # Ecosistemas: pip (Python) + github-actions version: 2 updates: # ── Python / pip ───────────────────────────────────────────────────── - package-ecosystem: "pip" directory: "/" schedule: interval: "weekly" day: "monday" time: "09:00" timezone: "America/Bogota" open-pull-requests-limit: 5 assignees: - "luismeli10" - "orojaspardo" - "barajas-d" labels: - "dependencies" commit-message: prefix: "chore(deps)" include: "scope" # pip puede ejecutar cΓ³digo de setup.py durante el update β€” lo bloqueamos insecure-external-code-execution: "deny" ignore: - dependency-name: "*" update-types: ["version-update:semver-major"] # ── GitHub Actions (CI) ────────────────────────────────────────────── - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" day: "monday" time: "09:00" timezone: "America/Bogota" open-pull-requests-limit: 1 labels: - "dependencies" - "ci" commit-message: prefix: "chore(ci)" mercadopago-sdk-python-b345a69/.github/workflows/000077500000000000000000000000001524412155200220265ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/.github/workflows/cd.yml000066400000000000000000000016441524412155200231440ustar00rootroot00000000000000# This workflow will install Python dependencies and upload a version in the PyPI name: CD - Upload PyPI on: release: types: [ published ] jobs: upload: runs-on: ubuntu-latest permissions: contents: read id-token: write steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 # Sets up python - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v5 with: python-version: 3.12 # Install dependencies - name: "Installs dependencies" run: | python3 -m pip install --upgrade pip python3 -m pip install setuptools build twine python3 -m pip install . - name: Build distribution run: | python3 -m build python3 -m twine check dist/* - name: Publish package distributions to PyPI uses: pypa/gh-action-pypi-publish@release/v1 mercadopago-sdk-python-b345a69/.github/workflows/ci.yml000066400000000000000000000025531524412155200231510ustar00rootroot00000000000000name: CI on: push: branches: ["master"] pull_request: branches: ["master"] jobs: test: name: Test on Python ${{ matrix.python-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Setup Python ${{ matrix.python-version }} uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip "setuptools>=83.0.0" python -m pip install requests pylint isort pip-audit python -m pip install -e . - name: Lint with Pylint run: | pylint mercadopago pylint --rcfile=tests/.pylintrc tests - name: Lint with isort run: isort --check-only . - name: Run unit tests run: python -m unittest discover tests/ - name: Dependency audit run: pip-audit - name: Dependency review if: github.event_name == 'pull_request' uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v4 with: fail-on-severity: high mercadopago-sdk-python-b345a69/.gitignore000066400000000000000000000005721524412155200204250ustar00rootroot00000000000000*.py[cod] *.pyc .DS_Store .idea venv # C extensions *.so # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg lib64 __pycache__ # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject # Demo img/ PRESS.md # vscode .vscode mercadopago-sdk-python-b345a69/.pre-commit-config.yaml000066400000000000000000000006531524412155200227160ustar00rootroot00000000000000repos: - repo: https://github.com/melisource/fury_websec-git-hooks rev: v2.0.0 hooks: - id: pre_commit_hook stages: [pre-commit] - id: post_commit_hook stages: [post-commit] - repo: https://github.com/melisource/fury_datasec-git-hooks rev: 1.2.2 hooks: - id: pre_commit_hook stages: [pre-commit] - id: post_commit_hook stages: [post-commit] mercadopago-sdk-python-b345a69/.pylintrc000066400000000000000000000001501524412155200202720ustar00rootroot00000000000000[MESSAGES CONTROL] disable= C0116, C0301, C0325, C0415, R0801, R0903, R0917 mercadopago-sdk-python-b345a69/CHANGELOG.md000066400000000000000000000075551524412155200202560ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [3.6.0] - 2026-08-27 ### Added - **Credential-on-file and automatic payments**: support `network_data`, expanded gateway network data, and `automatic_payments.subscription`. ### CI - Publish to PyPI through GitHub OIDC trusted publishing. ## [3.5.0] - 2026-08-11 ### Changed - **Item and shipment classes**: renamed to generic classes without `Order` prefix ([#145](https://github.com/mercadopago/sdk-python/pull/145)) - **Payer classes**: consolidated into a single generic `payer.py` ([#145](https://github.com/mercadopago/sdk-python/pull/145)) ### CI - Add Python 3.13 and 3.14 to CI matrix ([#145](https://github.com/mercadopago/sdk-python/pull/145)) - Drop Python 3.9 from CI matrix β€” not supported by this SDK ([#145](https://github.com/mercadopago/sdk-python/pull/145)) - Standardize CI/CD workflows ([#145](https://github.com/mercadopago/sdk-python/pull/145)) ## [3.4.0] - 2026-08-04 ### Added - **SDK ergonomics**: typed exceptions, configurable retry, and auto-pagination ([#141](https://github.com/mercadopago/sdk-python/pull/141)) - `MPApiException` now has 12 specific subtypes per HTTP status code - Request options gain optional `max_retries`, `retry_on`, `initial_delay_ms`, `max_delay_ms` and `on_retry` callback - New auto-pagination support on search endpoints - **Missing API methods** β€” `disbursement_refund.list()`, `advanced_payment.update()`, `customer_card.update()`, `payment.update()` ([#140](https://github.com/mercadopago/sdk-python/pull/140)) - **CREDENTIAL_ON_FILE messaging fields** on Payment types ([#139](https://github.com/mercadopago/sdk-python/pull/139)): `first_transaction`, `storage`, `transaction_initiator`, `reference` ### Fixed - Webhook `tolerance_seconds` unit mismatch β€” `ts` header value compared in seconds against a millisecond clock ([#142](https://github.com/mercadopago/sdk-python/pull/142)) - `constant_time_equals` error on multibyte v1 hash ([#142](https://github.com/mercadopago/sdk-python/pull/142)) ### Dependencies - Bump `actions/checkout` to `v7.0.1` ([#138](https://github.com/mercadopago/sdk-python/pull/138)) ## [3.3.0] - 2026-06-30 ### Added - **Orders Checkout Pro**: beta support helpers, example payload, and wire-level tests for creation through `sdk.order().create()`, including `config.online`, `config.payment_method`, redirect URLs, tracking pixels, shipment, items, and vertical `additional_info` fields. - **Orders**: added `sdk.order().refund()` as a backwards-compatible alias for the existing order refund endpoint. ## [3.2.0] - 2026-05-27 ### Added - **OAuth**: authorization URL builder, token exchange, and token refresh (`sdk.oauth().get_authorization_url()`, `.create()`, `.refresh()`). Enables marketplace and platform integrations to operate on behalf of other sellers via the OAuth 2.0 authorization code flow. Endpoints: `POST /oauth/token`. - **Point**: in-person payment intent management for MercadoPago Point devices (`sdk.point().get_devices()`, `.create()`, `.get()`, `.cancel()`). Enables card-present transactions through physical Point card readers. Endpoints: `GET /point/integration-api/devices`, `POST /point/integration-api/devices/{device_id}/payment-intents`, `GET /point/integration-api/payment-intents/{id}`, `DELETE /point/integration-api/devices/{device_id}/payment-intents/{id}`. Note: `change_operating_mode` (PATCH) is not included; requires HttpClient PATCH support. - **Invoice**: retrieval and search of subscription billing invoices (`sdk.invoice().get()`, `.search()`). Enables monitoring of authorized payments generated by PreApproval billing cycles. Endpoints: `GET /authorized_payments/{id}`, `GET /authorized_payments/search`. mercadopago-sdk-python-b345a69/CODE_OF_CONDUCT.md000066400000000000000000000061061524412155200212330ustar00rootroot00000000000000# Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment of individuals or the company * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct that could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned with this Code of Conduct, as well as temporarily or permanently ban any contributor for other behavior deemed inappropriate, threatening, offensive, or harmful with or without prior notice.. ## Scope This Code of Conduct applies within all project spaces and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. This Code of Conduct also applies outside the project spaces when there is a reasonable belief that an individual's behavior may have a negative impact on the project, the company or the community. ## Enforcement Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faqmercadopago-sdk-python-b345a69/CODING_GUIDELINES.md000066400000000000000000000114211524412155200214250ustar00rootroot00000000000000# Coding Guidelines The Mercado Pago Python SDK is a collaborative effort from the start. The SDK team thinks that contributions from different developer will enrich it's feature set and make it more relevant to the community. However; absorbing all contributions as-is, while expedient, might lead to difficulties in maintenance of the codebase is left unchecked. Collaborative codebases often establish guidelines for contributors to ensure code remains maintainable over time. The effort to maintain the SDK is no different in this regard so a bit of guidance is in order. The purpose of this guide is to set a baseline for contributions. These guidelines are not intended to limit the tools at your disposal nor to rewire the way you think but rather to encourage good neighbor behavior. ## Language Guidelines We use **english** language. This is to be consistent everywhere, and to be considerate with developers that do not speak our native language. Therefore: source code, comments, documentation, commit messages, review comments, and any other kind of contribution *MUST* use english language. Typos are unavoidable, but try to reduce them by using a spellchecker. Most IDEs can be configured to run one automatically. ## Code Guidelines * Set your IDE to follow the [`.editorconfig`](https://editorconfig.org/) in each repository. * Follow the [PEP 8 Style Guide](https://pep8.org/). Generally speaking, be conscious when contributing and try following the same style that the code in the SDK already has. If you have any doubts, just ask us! This rules will be enforced automatically when making a pull requests, and checks will fail if you do not follow them, resulting in your contribution being automatically rejected until fixed. ## Comment Guidelines Comments in code are a hard thing to write, not because the words are difficult to produce but because it is hard to make relevant comments. Too much of it and people do not read comments (and it obfuscates code reading) and too little of it gives you no recourse but to read large portions of codebase to get insight as to what a feature/codeblock is doing. Both situations are undesirable and efforts should be made at all time to have a please comment reading experience As a general rule you would have to comment on decisions you made while coding that are not part of any specification. In particular you should always comment any decision that: * Departs from common wisdom or convention (The **why's** are necessary). * Takes a significant amount of time to produce. A good rule of thumb here is that if you spent more than 1 hour thinking on how to produce a fragment of code that took 2 minutes of wrist time to write you should document your thinking to aid reader and allow for validation. * Need to preserve properties of the implementation. This is the case of performance sensitive portions of the codebase, goroutines synchronization, implementations of security primitives, congestion control algorithms, etc. As a general rule of what not to comment you should avoid: * Commenting on structure of programs that is already part of a convention, specified or otherwise. * Having pedantic explanations of behavior that can be found by immediate examination of the surrounding code artifacts. * Commenting on behavior you cannot attest. ### Branching Guidelines Currently `master` is our only long term branch, below a few suggestions of short term branches naming: * `hotfix/something-needs-fix`: Small routine patches in code to features already there. * `feature/something-new`: A new feature or a change in a existent feature. Beware of breaking changes that would require a major version bump. * `doc/improves-documentation-for-this-feature`: If you add or change documentation with no impact to the source code. ### Git Guidelines All commits **SHOULD** follow the [seven rules of a great Git commit message](https://chris.beams.io/posts/git-commit): 1. Separate subject from body with a blank line. 2. Limit the subject line to 72 characters. 3. Capitalize the subject line. 4. Do not end the subject line with a period. 5. Use the imperative mood in the subject line. 6. Wrap the body at 72 characters. 7. Use the body to explain what and why vs. how. Commits such as "fix tests", "now it's working" and many other common messages we find usually in code **WON'T** be accepted. Ideally we would like to enforce these rules, but we are realistic and understand that it might be a big change for some people. So unless deviating heavily from what was stated we might accept your commits even if not following these rules perfectly. Please avoid taking to much time to deliver code, and always [rebase](https://git-scm.com/docs/git-rebase) your code to avoid reverse merge commits. When reviewing, check if the PR adheres to [PEP 8 Style Guide](https://pep8.org/). mercadopago-sdk-python-b345a69/CONTRIBUTING.md000066400000000000000000000112471524412155200206670ustar00rootroot00000000000000# Contributing to the Mercado Pago Python SDK Thank you for your interest in contributing to the Mercado Pago Python SDK! ## How to contribute In order to contribute to the Mercado Pago Python SDK effectively we provide guidelines to address common case for contributions. Presently we have guides for the following type of changes. * Request For Change (RFC) / Feature Request: These are suggestions / requests for features the SDK currently does not have. The SDK team evaluates these requests for adequacy / relevance / capacity and overall architectural consistency. * Bug Reports: These are reports of non compliant behavior with the SDK specification and other blatantly wrong behavior of the Mercado Pago Python SDK. In addition to contributing in the form of Bug Reports and RFCs it is also possible to contribute directly in code with a Pull Request (PR). In the case of a Pull Request you should also indicate the nature of the Pull Request (Feature/Bug/etc.) to help the team asses the Pull Request. If you are enthusiastic about a particular Feature being added or a bug being fixed, a PR is often the quickest way to promote your change as the team does not have to allocate as much resources to process the contribution. In the case of PRs it is often best to consult with the SDK team before embarking on a PR, specially if it's a beefy one. Spending time on a PR that might later be rejected because major discrepancies with vision or competing contributions is an uncomfortable outcome for all involved people. Remember the SDK team with privilege overall consistency and progress over any one particular contribution. ## Coding Guidance All contributions *MUST* follow the [Coding Guidelines](CODING_GUIDELINES.md). Contributions that fail to follow this guidelines will be disregarded and told to make the required modifications to do so. ## Request For Change / Feature Request Generally speaking an RFC is needed when you want to add a new feature or change an existing one in an incompatible way that might result in a major version bump to the toolkit. Though it seems a little bureaucratic, the process is in place in order to avoid frustration of a potential contributor by making the discussions take place before any code is written. Once the design and direction is fully agreed then the contributor can work peacefully knowing that their change will be committed. As of this moment all you need to do is create an issue and use the [Feature Request Template](.github/ISSUE_TEMPLATE/feature_request.md). Please prepend your issue title with `[RFC]` so that's easier to filter. ## Bug Reports Bugs are a reality in software. We can't fix what we don't know about, so please report liberally. If you're not sure if something is a bug or not, feel free to file it anyway. Before reporting a bug, please search existing issues and pull requests, as it's possible that someone else has already reported your error. In the off case that you find your issue as fixed/closed, please add a reference to it on your new one. Your issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a bug report is to make it easy for yourself - and others - to replicate the bug and develop a fix. Opening an issue is as easy as following [this link](https://github.com/mercadopago/sdk-dotnet/issues/new) and filling out the given template. Bug reports may also be sent in the form of a [pull request](#pull-request) containing a failing test. ## Pull Request First and foremost: Source code, documentation, commit messages, review comments, and any other kind of contribution must *MUST* follow the [Coding Guidelines](CODING_GUIDELINES.md). We use the "fork and pull" model [described here](https://help.github.com/articles/about-collaborative-development-models/), where contributors push changes to their personal fork and create pull requests to bring those changes into the source repository. Your basic steps to get going: * Fork the corresponding toolkit repository and create a branch from master for the issue you are working on. * Commit as you go following our git conventions. * Include tests that cover all non-trivial code. The existing tests should provide a template on how to test the toolkit correctly. * Make sure all test passes. * All code changes are expected to comply with the formatting style. * Push your commits to GitHub and create a pull request against the corresponding toolkit component master branch. If taking to much time to deliver code, **always** [rebase](https://git-scm.com/docs/git-rebase) towards `master` before asking for a review, and avoid reverse merge commits. mercadopago-sdk-python-b345a69/LICENSE000066400000000000000000000020661524412155200174420ustar00rootroot00000000000000MIT License Copyright (c) 2021 MercadoPago Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.mercadopago-sdk-python-b345a69/MANIFEST.in000077500000000000000000000000421524412155200201660ustar00rootroot00000000000000include README.rst include LICENSEmercadopago-sdk-python-b345a69/README.md000066400000000000000000000124671524412155200177220ustar00rootroot00000000000000# 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. ## πŸ’‘ Requirements Python 3.9 or higher. ## πŸ“² Installation Run ```pip3 install mercadopago``` ## 🌟 Getting Started First time using Mercado Pago? Create your [Mercado Pago account](https://www.mercadopago.com). Copy your `Access Token` in the [credentials panel](https://www.mercadopago.com/developers/panel/credentials) and replace the text `YOUR_ACCESS_TOKEN` with it. ### Simple usage β€” Orders API The [Orders API](https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/create-order/post) (`/v1/orders`) is the recommended way to accept payments. `sdk.order().create()` accepts either a plain `dict` or the optional typed request dataclasses (`OrderCreateRequest` and friends). Both routes produce the exact same JSON body. ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") request_options = mercadopago.config.RequestOptions() request_options.custom_headers = { 'x-idempotency-key': '' } order_data = { "type": "online", "total_amount": "100.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", "token": "CARD_TOKEN", "installments": 1, }, } ] }, "payer": { "email": "test_user_123456@testuser.com" }, } result = sdk.order().create(order_data, request_options) order = result["response"] print(order) ``` #### Typed request classes (optional) Instead of a `dict`, you can build the request with the typed dataclasses. `None` 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 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)], ) result = sdk.order().create(order) print(result["response"]) ``` For a complete recurring / Automatic Payments example (stored credential, subscription data, integration data), see [`examples/order/create_order_automatic_payment.py`](examples/order/create_order_automatic_payment.py). ### Creating a payment (legacy Payments API) ```python import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") request_options = mercadopago.config.RequestOptions() request_options.custom_headers = { 'x-idempotency-key': '' } payment_data = { "transaction_amount": 100, "token": "CARD_TOKEN", "description": "Payment description", "payment_method_id": 'visa', "installments": 1, "payer": { "email": 'test_user_123456@testuser.com' } } result = sdk.payment().create(payment_data, request_options) payment = result["response"] print(payment) ``` ### Per-request configuration All methods that make API calls accept an optional `RequestOptions` object. This can be used to configure some special options of the request, such as changing credentials or custom headers. ```python import mercadopago from mercadopago.config import RequestOptions request_options = RequestOptions(access_token='YOUR_ACCESS_TOKEN') # ... 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) Check our official code reference to explore all available functionalities. ## 🀝 Contributing All contributions are welcome, ranging from people wanting to triage issues, others wanting to write documentation, to people wanting to contribute code. Please read and follow our [contribution guidelines](CONTRIBUTING.md). Contributions not following this guidelines will be disregarded. The guidelines are in place to make all of our lives easier and make contribution a consistent process for everyone. ## ❀️ Support If you require technical support, please contact our support team at [developers.mercadopago.com](https://developers.mercadopago.com). ## 🏻 License ``` MIT license. Copyright (c) 2021 - Mercado Pago / Mercado Libre For more information, see the LICENSE file. ``` mercadopago-sdk-python-b345a69/SUPPORT.md000066400000000000000000000107421524412155200201330ustar00rootroot00000000000000# πŸ†˜ Support and Help > **Quick guide:** Have a bug? β†’ [Bug Report](../../issues/new/choose) | Questions? β†’ [Question](../../issues/new/choose) | New idea? β†’ [Feature Request](../../issues/new/choose) --- ## 🎯 Quick Decision Guide | If you need... | Then... | |----------------|---------| | πŸ’¬ Question about how to use the SDK | [Create Question](../../issues/new/choose) | | πŸ› Report an error or bug | [Create Bug Report](../../issues/new/choose) | | ✨ Propose new feature | [Create Feature Request](../../issues/new/choose) | | πŸ’³ Problem with your MP account | [Official MP Support - ES ](https://www.mercadopago.com.co/developers/en/support/center)- [Official MP Support - PT ](https://www.mercadopago.com.co/developers/pt/support/center) | --- ## πŸ“š Before Creating an Issue **Search first, ask later:** 1. **[Official Documentation](https://www.mercadopago.com/developers/es/docs)** - Most questions are answered here 2. **[Closed Issues](../../issues?q=is%3Aissue+is%3Aclosed)** - Your problem may be solved 3. **[Open Issues](../../issues?q=is%3Aissue+is%3Aopen)** - Your problem may be already reported --- ## πŸ’¬ How to Report Issues ### 1. For Questions πŸ’¬ **When to use?** Doubts about usage, configuration, or best practices. **Steps:** 1. Search in [closed questions](../../issues?q=is%3Aissue+is%3Aclosed+label%3Aquestion) 2. [Create new question](../../issues/new/choose) 3. **Include:** SDK version, country, environment, code example. ### 2. For Bugs πŸ› **When to use?** Errors, unexpected behavior and/or crashes. **Steps:** 1. Verify [latest version](../../releases/latest) 2. Search in [existing bugs](../../issues?q=is%3Aissue+label%3Abug) 3. [Report bug](../../issues/new/choose) 4. **Include:** reproducible steps, logs, environment, SDK version. ### 3. For Features ✨ **When to use?** Propose improvements or new features **Steps:** 1. Search in [feature requests](../../issues?q=is%3Aissue+label%3Afeature%20request) 2. [Propose feature](../../issues/new/choose) 3. **Explain:** problem it solves, use cases, benefit. ### 4. To Contribute 🀝 **Want to help?** Read [CONTRIBUTING.md](./CONTRIBUTING.md) --- ## πŸ”’ Security ### ⚠️ NEVER Share in Public Issues: - ❌ Access tokens or production credentials - ❌ Client IDs / Client Secrets - ❌ Customer or card data - ❌ Personally Identifiable Information (PII) > **⚠️ IMPORTANT:** Issues with real data will be closed and reported immediately. --- ## 🌎 Official Mercado Pago SDK Support ### ⚑ GitHub Issues Scope **GitHub Issues is ONLY for SDK technical support.** βœ… **Use GitHub for:** - SDK bugs - Questions about SDK usage - SDK features - Code contributions ❌ **DO NOT use GitHub for:** - Problems with your MP account - Specific transactions or payments - Commercial or billing topics - Homologation/certification - Account access or credentials - Webhook configuration in your account ### 🏒 Contact Official MP Support for: [**πŸ”— Official Mercado Pago Support - ES**](https://www.mercadopago.com.co/developers/es/support/center) [**πŸ”— Official Mercado Pago Support - PT**](https://www.mercadopago.com.co/developers/pt/support/center) - βœ‰οΈ Account problems - πŸ’³ Transactions and payments - 🀝 Commercial topics - πŸ“‹ Homologation - πŸ” Account access - 🌐 Webhooks in your account - πŸ“Š Reports and statistics --- ## πŸ”— Resources and Contacts ### Documentation - **[Official Documentation](https://www.mercadopago.com/developers/es/docs)** - Complete guides - **[API Reference](https://www.mercadopago.com/developers/en/reference)** - API reference - **[SDKs](https://www.mercadopago.com/developers/en/docs/sdks-library/server-side)** - Other SDKs ### Support - **[GitHub Issues](../../issues/new/choose)** - SDK technical support ### Community channels - **[Discord](https://discord.gg/96nqqpaycN)** - Community channel - **[Newsletter](https://www.mercadopago.com/developers/panel/contact)** - Mercado Pago Newsletter - **[Status Page](https://status.mercadopago.com/)** - Service status --- ## πŸ’‘ Tips for Getting Quick Help 1. **πŸ” Search first** - Saves everyone time 2. **πŸ“ Be specific** - "Error 400 on POST /payments" vs "It doesn't work" 3. **πŸ’» Reproducible code** - Minimal and complete example 4. **πŸ“‹ Follow templates** - They're designed to help you 5. **🚫 No sensitive data** - Protect your security 6. **🀝 Be respectful** - We're all part of the community --- πŸ’™ **Thank you for being part of the Mercado Pago developer community!**mercadopago-sdk-python-b345a69/docs/000077500000000000000000000000001524412155200173615ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/docs/config/000077500000000000000000000000001524412155200206265ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/docs/config/config.html000066400000000000000000000352071524412155200227700ustar00rootroot00000000000000 mercadopago.config.config API documentation

Module mercadopago.config.config

Module: config

Expand source code
"""
Module: config
"""
import platform


class Config:
    """
    General infos of your SDK
    """

    def __init__(self):
        self.__version = "2.2.0"
        self.__user_agent = "MercadoPago Python SDK v" + self.__version
        self.__product_id = "bc32bpftrpp001u8nhlg"
        self.__tracking_id = "platform:" + platform.python_version()
        self.__tracking_id += ",type:SDK" + self.__version + ",so;"

    __api_base_url = "https://api.mercadopago.com"
    __mime_json = "application/json"
    __mime_form = "application/x-www-form-urlencoded"

    @property
    def version(self):
        """
        Sets the attribute value of version
        """
        return self.__version

    @property
    def user_agent(self):
        """
        Sets the attribute value of user agent
        """
        return self.__user_agent

    @property
    def product_id(self):
        """
        Sets the attribute value of product id
        """
        return self.__product_id

    @property
    def tracking_id(self):
        """
        Sets the attribute value of tracking id
        """
        return self.__tracking_id

    @property
    def api_base_url(self):
        """
        Sets the attribute value of api base url
        """
        return self.__api_base_url

    @property
    def mime_json(self):
        """
        Sets the attribute value of mime json
        """
        return self.__mime_json

    @property
    def mime_form(self):
        """
        Sets the attribute value of mime form
        """
        return self.__mime_form

Classes

class Config

General infos of your SDK

Expand source code
class Config:
    """
    General infos of your SDK
    """

    def __init__(self):
        self.__version = "2.2.0"
        self.__user_agent = "MercadoPago Python SDK v" + self.__version
        self.__product_id = "bc32bpftrpp001u8nhlg"
        self.__tracking_id = "platform:" + platform.python_version()
        self.__tracking_id += ",type:SDK" + self.__version + ",so;"

    __api_base_url = "https://api.mercadopago.com"
    __mime_json = "application/json"
    __mime_form = "application/x-www-form-urlencoded"

    @property
    def version(self):
        """
        Sets the attribute value of version
        """
        return self.__version

    @property
    def user_agent(self):
        """
        Sets the attribute value of user agent
        """
        return self.__user_agent

    @property
    def product_id(self):
        """
        Sets the attribute value of product id
        """
        return self.__product_id

    @property
    def tracking_id(self):
        """
        Sets the attribute value of tracking id
        """
        return self.__tracking_id

    @property
    def api_base_url(self):
        """
        Sets the attribute value of api base url
        """
        return self.__api_base_url

    @property
    def mime_json(self):
        """
        Sets the attribute value of mime json
        """
        return self.__mime_json

    @property
    def mime_form(self):
        """
        Sets the attribute value of mime form
        """
        return self.__mime_form

Instance variables

var api_base_url

Sets the attribute value of api base url

Expand source code
@property
def api_base_url(self):
    """
    Sets the attribute value of api base url
    """
    return self.__api_base_url
var mime_form

Sets the attribute value of mime form

Expand source code
@property
def mime_form(self):
    """
    Sets the attribute value of mime form
    """
    return self.__mime_form
var mime_json

Sets the attribute value of mime json

Expand source code
@property
def mime_json(self):
    """
    Sets the attribute value of mime json
    """
    return self.__mime_json
var product_id

Sets the attribute value of product id

Expand source code
@property
def product_id(self):
    """
    Sets the attribute value of product id
    """
    return self.__product_id
var tracking_id

Sets the attribute value of tracking id

Expand source code
@property
def tracking_id(self):
    """
    Sets the attribute value of tracking id
    """
    return self.__tracking_id
var user_agent

Sets the attribute value of user agent

Expand source code
@property
def user_agent(self):
    """
    Sets the attribute value of user agent
    """
    return self.__user_agent
var version

Sets the attribute value of version

Expand source code
@property
def version(self):
    """
    Sets the attribute value of version
    """
    return self.__version
mercadopago-sdk-python-b345a69/docs/config/index.html000066400000000000000000000710661524412155200226350ustar00rootroot00000000000000 mercadopago.config API documentation

Module mercadopago.config

Module: config/init.py

Expand source code
"""
Module: config/__init__.py
"""
from mercadopago.config.config import Config
from mercadopago.config.request_options import RequestOptions


__all__ = (
    'Config',
    'RequestOptions',
)

Sub-modules

mercadopago.config.config

Module: config

mercadopago.config.request_options

Module: request_options

Classes

class Config

General infos of your SDK

Expand source code
class Config:
    """
    General infos of your SDK
    """

    def __init__(self):
        self.__version = "2.2.0"
        self.__user_agent = "MercadoPago Python SDK v" + self.__version
        self.__product_id = "bc32bpftrpp001u8nhlg"
        self.__tracking_id = "platform:" + platform.python_version()
        self.__tracking_id += ",type:SDK" + self.__version + ",so;"

    __api_base_url = "https://api.mercadopago.com"
    __mime_json = "application/json"
    __mime_form = "application/x-www-form-urlencoded"

    @property
    def version(self):
        """
        Sets the attribute value of version
        """
        return self.__version

    @property
    def user_agent(self):
        """
        Sets the attribute value of user agent
        """
        return self.__user_agent

    @property
    def product_id(self):
        """
        Sets the attribute value of product id
        """
        return self.__product_id

    @property
    def tracking_id(self):
        """
        Sets the attribute value of tracking id
        """
        return self.__tracking_id

    @property
    def api_base_url(self):
        """
        Sets the attribute value of api base url
        """
        return self.__api_base_url

    @property
    def mime_json(self):
        """
        Sets the attribute value of mime json
        """
        return self.__mime_json

    @property
    def mime_form(self):
        """
        Sets the attribute value of mime form
        """
        return self.__mime_form

Instance variables

var api_base_url

Sets the attribute value of api base url

Expand source code
@property
def api_base_url(self):
    """
    Sets the attribute value of api base url
    """
    return self.__api_base_url
var mime_form

Sets the attribute value of mime form

Expand source code
@property
def mime_form(self):
    """
    Sets the attribute value of mime form
    """
    return self.__mime_form
var mime_json

Sets the attribute value of mime json

Expand source code
@property
def mime_json(self):
    """
    Sets the attribute value of mime json
    """
    return self.__mime_json
var product_id

Sets the attribute value of product id

Expand source code
@property
def product_id(self):
    """
    Sets the attribute value of product id
    """
    return self.__product_id
var tracking_id

Sets the attribute value of tracking id

Expand source code
@property
def tracking_id(self):
    """
    Sets the attribute value of tracking id
    """
    return self.__tracking_id
var user_agent

Sets the attribute value of user agent

Expand source code
@property
def user_agent(self):
    """
    Sets the attribute value of user agent
    """
    return self.__user_agent
var version

Sets the attribute value of version

Expand source code
@property
def version(self):
    """
    Sets the attribute value of version
    """
    return self.__version
class RequestOptions (access_token=None, connection_timeout=60.0, custom_headers=None, corporation_id=None, integrator_id=None, platform_id=None, max_retries=3)

This object hold all configurations that will be used in ur REST call.

All here u can customize as well add params in the requisition header (custom_headers)

Initialize

Args

access_token : str, optional
Your User Access Token. Defaults to None.
connection_timeout : float, optional
Time to timeout the REST call. Defaults to 60.0.
custom_headers : dict, optional
A Dict with params to be added to the requests params.
Defaults to None.
corporation_id : str, optional
Your Corporation ID if any. Defaults to None.
integrator_id : str, optional
Your Integrator ID if any. Defaults to None.
platform_id : str, optional
Your Platform ID if any. Defaults to None.
max_retries : int, optional
How many retries must be done in case of fail.

Defaults to 3.

Raises

ValueError
Param access_token must be a String
ValueError
Param connection_timeout must be a Float
ValueError
Param custom_headers must be a Dictionary
ValueError
Param corporation_id must be a String
ValueError
Param integrator_id must be a String
ValueError
Param platform_id must be a String
ValueError
Param max_retries must be an Integer
Expand source code
class RequestOptions:  # pylint: disable=too-many-instance-attributes

    """This object hold all configurations that will be used in ur REST call.

    All here u can customize as well add params in the requisition header (custom_headers)
    """

    __access_token = None
    __connection_timeout = None
    __custom_headers = None
    __max_retries = None
    __corporation_id = None
    __integrator_id = None
    __platform_id = None

    def __init__(  # pylint: disable=too-many-arguments
        self,
        access_token=None,
        connection_timeout=60.0,
        custom_headers=None,
        corporation_id=None,
        integrator_id=None,
        platform_id=None,
        max_retries=3,
    ):
        """Initialize

        Args:
            access_token (str, optional): Your User Access Token. Defaults to None.
            connection_timeout (float, optional): Time to timeout the REST call. Defaults to 60.0.
            custom_headers (dict, optional): A Dict with params to be added to the requests params.
            Defaults to None.
            corporation_id (str, optional): Your Corporation ID if any. Defaults to None.
            integrator_id (str, optional): Your Integrator ID if any. Defaults to None.
            platform_id (str, optional): Your Platform ID if any. Defaults to None.
            max_retries (int, optional): How many retries must be done in case of fail.
            Defaults to 3.

        Raises:
            ValueError: Param access_token must be a String
            ValueError: Param connection_timeout must be a Float
            ValueError: Param custom_headers must be a Dictionary
            ValueError: Param corporation_id must be a String
            ValueError: Param integrator_id must be a String
            ValueError: Param platform_id must be a String
            ValueError: Param max_retries must be an Integer
        """

        if access_token is not None:
            self.access_token = access_token
        if connection_timeout is not None:
            self.connection_timeout = connection_timeout
        if custom_headers is not None:
            self.custom_headers = custom_headers
        if max_retries is not None:
            self.max_retries = max_retries
        if corporation_id is not None:
            self.corporation_id = corporation_id
        if integrator_id is not None:
            self.integrator_id = integrator_id
        if platform_id is not None:
            self.platform_id = platform_id

        self.__config = Config()

    def get_headers(self):
        """
        Sets the attribute values of headers
        """
        headers = {"Authorization": "Bearer " + self.__access_token,
                   "x-product-id": self.__config.product_id,
                   "x-tracking-id": self.__config.tracking_id,
                   "x-idempotency-key": str(uuid.uuid4().int),
                   "User-Agent": self.__config.user_agent,
                   "Accept": self.__config.mime_json}

        if self.__corporation_id is not None:
            headers["x-corporation-id"] = self.__corporation_id

        if self.__integrator_id is not None:
            headers["x-integrator-id"] = self.__integrator_id

        if self.__platform_id is not None:
            headers["x-platform-id"] = self.__platform_id

        if self.__custom_headers is not None:
            headers.update(self.__custom_headers)

        return headers

    @property
    def access_token(self):
        """
        Sets the attribute value and validates access_token
        """
        return self.__access_token

    @access_token.setter
    def access_token(self, value):
        if not isinstance(value, str):
            raise ValueError("Param access_token must be a String")
        self.__access_token = value

    @property
    def connection_timeout(self):
        """
        Sets the attribute value and validates connection timeout
        """
        return self.__connection_timeout

    @connection_timeout.setter
    def connection_timeout(self, value):
        if not isinstance(value, float):
            raise ValueError("Param connection_timeout must be a Float")
        self.__connection_timeout = value

    @property
    def corporation_id(self):
        """
        Sets the attribute value and validates corporation id
        """
        return self.__corporation_id

    @corporation_id.setter
    def corporation_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param corporation_id must be a String")
        self.__corporation_id = value

    @property
    def custom_headers(self):
        """
        Sets the attribute value and validates custom headers
        """
        return self.__custom_headers

    @custom_headers.setter
    def custom_headers(self, value):
        if not isinstance(value, dict):
            raise ValueError("Param custom_headers must be a Dictionary")
        self.__custom_headers = value

    @property
    def integrator_id(self):
        """
        Sets the attribute value and validates integrator id
        """
        return self.__integrator_id

    @integrator_id.setter
    def integrator_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param integrator_id must be a String")
        self.__integrator_id = value

    @property
    def max_retries(self):
        """
        Sets the attribute value and validates max retries
        """
        return self.__max_retries

    @max_retries.setter
    def max_retries(self, value):
        if not isinstance(value, int):
            raise ValueError("Param max_retries must be an Integer")
        self.__max_retries = value

    @property
    def platform_id(self):
        """
        Sets the attribute value and validates platform id
        """
        return self.__platform_id

    @platform_id.setter
    def platform_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param platform_id must be a String")
        self.__platform_id = value

Instance variables

var access_token

Sets the attribute value and validates access_token

Expand source code
@property
def access_token(self):
    """
    Sets the attribute value and validates access_token
    """
    return self.__access_token
var connection_timeout

Sets the attribute value and validates connection timeout

Expand source code
@property
def connection_timeout(self):
    """
    Sets the attribute value and validates connection timeout
    """
    return self.__connection_timeout
var corporation_id

Sets the attribute value and validates corporation id

Expand source code
@property
def corporation_id(self):
    """
    Sets the attribute value and validates corporation id
    """
    return self.__corporation_id
var custom_headers

Sets the attribute value and validates custom headers

Expand source code
@property
def custom_headers(self):
    """
    Sets the attribute value and validates custom headers
    """
    return self.__custom_headers
var integrator_id

Sets the attribute value and validates integrator id

Expand source code
@property
def integrator_id(self):
    """
    Sets the attribute value and validates integrator id
    """
    return self.__integrator_id
var max_retries

Sets the attribute value and validates max retries

Expand source code
@property
def max_retries(self):
    """
    Sets the attribute value and validates max retries
    """
    return self.__max_retries
var platform_id

Sets the attribute value and validates platform id

Expand source code
@property
def platform_id(self):
    """
    Sets the attribute value and validates platform id
    """
    return self.__platform_id

Methods

def get_headers(self)

Sets the attribute values of headers

Expand source code
def get_headers(self):
    """
    Sets the attribute values of headers
    """
    headers = {"Authorization": "Bearer " + self.__access_token,
               "x-product-id": self.__config.product_id,
               "x-tracking-id": self.__config.tracking_id,
               "x-idempotency-key": str(uuid.uuid4().int),
               "User-Agent": self.__config.user_agent,
               "Accept": self.__config.mime_json}

    if self.__corporation_id is not None:
        headers["x-corporation-id"] = self.__corporation_id

    if self.__integrator_id is not None:
        headers["x-integrator-id"] = self.__integrator_id

    if self.__platform_id is not None:
        headers["x-platform-id"] = self.__platform_id

    if self.__custom_headers is not None:
        headers.update(self.__custom_headers)

    return headers
mercadopago-sdk-python-b345a69/docs/config/request_options.html000066400000000000000000000700661524412155200247700ustar00rootroot00000000000000 mercadopago.config.request_options API documentation

Module mercadopago.config.request_options

Module: request_options

Expand source code
"""
Module: request_options
"""
import uuid

from .config import Config


class RequestOptions:  # pylint: disable=too-many-instance-attributes

    """This object hold all configurations that will be used in ur REST call.

    All here u can customize as well add params in the requisition header (custom_headers)
    """

    __access_token = None
    __connection_timeout = None
    __custom_headers = None
    __max_retries = None
    __corporation_id = None
    __integrator_id = None
    __platform_id = None

    def __init__(  # pylint: disable=too-many-arguments
        self,
        access_token=None,
        connection_timeout=60.0,
        custom_headers=None,
        corporation_id=None,
        integrator_id=None,
        platform_id=None,
        max_retries=3,
    ):
        """Initialize

        Args:
            access_token (str, optional): Your User Access Token. Defaults to None.
            connection_timeout (float, optional): Time to timeout the REST call. Defaults to 60.0.
            custom_headers (dict, optional): A Dict with params to be added to the requests params.
            Defaults to None.
            corporation_id (str, optional): Your Corporation ID if any. Defaults to None.
            integrator_id (str, optional): Your Integrator ID if any. Defaults to None.
            platform_id (str, optional): Your Platform ID if any. Defaults to None.
            max_retries (int, optional): How many retries must be done in case of fail.
            Defaults to 3.

        Raises:
            ValueError: Param access_token must be a String
            ValueError: Param connection_timeout must be a Float
            ValueError: Param custom_headers must be a Dictionary
            ValueError: Param corporation_id must be a String
            ValueError: Param integrator_id must be a String
            ValueError: Param platform_id must be a String
            ValueError: Param max_retries must be an Integer
        """

        if access_token is not None:
            self.access_token = access_token
        if connection_timeout is not None:
            self.connection_timeout = connection_timeout
        if custom_headers is not None:
            self.custom_headers = custom_headers
        if max_retries is not None:
            self.max_retries = max_retries
        if corporation_id is not None:
            self.corporation_id = corporation_id
        if integrator_id is not None:
            self.integrator_id = integrator_id
        if platform_id is not None:
            self.platform_id = platform_id

        self.__config = Config()

    def get_headers(self):
        """
        Sets the attribute values of headers
        """
        headers = {"Authorization": "Bearer " + self.__access_token,
                   "x-product-id": self.__config.product_id,
                   "x-tracking-id": self.__config.tracking_id,
                   "x-idempotency-key": str(uuid.uuid4().int),
                   "User-Agent": self.__config.user_agent,
                   "Accept": self.__config.mime_json}

        if self.__corporation_id is not None:
            headers["x-corporation-id"] = self.__corporation_id

        if self.__integrator_id is not None:
            headers["x-integrator-id"] = self.__integrator_id

        if self.__platform_id is not None:
            headers["x-platform-id"] = self.__platform_id

        if self.__custom_headers is not None:
            headers.update(self.__custom_headers)

        return headers

    @property
    def access_token(self):
        """
        Sets the attribute value and validates access_token
        """
        return self.__access_token

    @access_token.setter
    def access_token(self, value):
        if not isinstance(value, str):
            raise ValueError("Param access_token must be a String")
        self.__access_token = value

    @property
    def connection_timeout(self):
        """
        Sets the attribute value and validates connection timeout
        """
        return self.__connection_timeout

    @connection_timeout.setter
    def connection_timeout(self, value):
        if not isinstance(value, float):
            raise ValueError("Param connection_timeout must be a Float")
        self.__connection_timeout = value

    @property
    def corporation_id(self):
        """
        Sets the attribute value and validates corporation id
        """
        return self.__corporation_id

    @corporation_id.setter
    def corporation_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param corporation_id must be a String")
        self.__corporation_id = value

    @property
    def custom_headers(self):
        """
        Sets the attribute value and validates custom headers
        """
        return self.__custom_headers

    @custom_headers.setter
    def custom_headers(self, value):
        if not isinstance(value, dict):
            raise ValueError("Param custom_headers must be a Dictionary")
        self.__custom_headers = value

    @property
    def integrator_id(self):
        """
        Sets the attribute value and validates integrator id
        """
        return self.__integrator_id

    @integrator_id.setter
    def integrator_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param integrator_id must be a String")
        self.__integrator_id = value

    @property
    def max_retries(self):
        """
        Sets the attribute value and validates max retries
        """
        return self.__max_retries

    @max_retries.setter
    def max_retries(self, value):
        if not isinstance(value, int):
            raise ValueError("Param max_retries must be an Integer")
        self.__max_retries = value

    @property
    def platform_id(self):
        """
        Sets the attribute value and validates platform id
        """
        return self.__platform_id

    @platform_id.setter
    def platform_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param platform_id must be a String")
        self.__platform_id = value

Classes

class RequestOptions (access_token=None, connection_timeout=60.0, custom_headers=None, corporation_id=None, integrator_id=None, platform_id=None, max_retries=3)

This object hold all configurations that will be used in ur REST call.

All here u can customize as well add params in the requisition header (custom_headers)

Initialize

Args

access_token : str, optional
Your User Access Token. Defaults to None.
connection_timeout : float, optional
Time to timeout the REST call. Defaults to 60.0.
custom_headers : dict, optional
A Dict with params to be added to the requests params.
Defaults to None.
corporation_id : str, optional
Your Corporation ID if any. Defaults to None.
integrator_id : str, optional
Your Integrator ID if any. Defaults to None.
platform_id : str, optional
Your Platform ID if any. Defaults to None.
max_retries : int, optional
How many retries must be done in case of fail.

Defaults to 3.

Raises

ValueError
Param access_token must be a String
ValueError
Param connection_timeout must be a Float
ValueError
Param custom_headers must be a Dictionary
ValueError
Param corporation_id must be a String
ValueError
Param integrator_id must be a String
ValueError
Param platform_id must be a String
ValueError
Param max_retries must be an Integer
Expand source code
class RequestOptions:  # pylint: disable=too-many-instance-attributes

    """This object hold all configurations that will be used in ur REST call.

    All here u can customize as well add params in the requisition header (custom_headers)
    """

    __access_token = None
    __connection_timeout = None
    __custom_headers = None
    __max_retries = None
    __corporation_id = None
    __integrator_id = None
    __platform_id = None

    def __init__(  # pylint: disable=too-many-arguments
        self,
        access_token=None,
        connection_timeout=60.0,
        custom_headers=None,
        corporation_id=None,
        integrator_id=None,
        platform_id=None,
        max_retries=3,
    ):
        """Initialize

        Args:
            access_token (str, optional): Your User Access Token. Defaults to None.
            connection_timeout (float, optional): Time to timeout the REST call. Defaults to 60.0.
            custom_headers (dict, optional): A Dict with params to be added to the requests params.
            Defaults to None.
            corporation_id (str, optional): Your Corporation ID if any. Defaults to None.
            integrator_id (str, optional): Your Integrator ID if any. Defaults to None.
            platform_id (str, optional): Your Platform ID if any. Defaults to None.
            max_retries (int, optional): How many retries must be done in case of fail.
            Defaults to 3.

        Raises:
            ValueError: Param access_token must be a String
            ValueError: Param connection_timeout must be a Float
            ValueError: Param custom_headers must be a Dictionary
            ValueError: Param corporation_id must be a String
            ValueError: Param integrator_id must be a String
            ValueError: Param platform_id must be a String
            ValueError: Param max_retries must be an Integer
        """

        if access_token is not None:
            self.access_token = access_token
        if connection_timeout is not None:
            self.connection_timeout = connection_timeout
        if custom_headers is not None:
            self.custom_headers = custom_headers
        if max_retries is not None:
            self.max_retries = max_retries
        if corporation_id is not None:
            self.corporation_id = corporation_id
        if integrator_id is not None:
            self.integrator_id = integrator_id
        if platform_id is not None:
            self.platform_id = platform_id

        self.__config = Config()

    def get_headers(self):
        """
        Sets the attribute values of headers
        """
        headers = {"Authorization": "Bearer " + self.__access_token,
                   "x-product-id": self.__config.product_id,
                   "x-tracking-id": self.__config.tracking_id,
                   "x-idempotency-key": str(uuid.uuid4().int),
                   "User-Agent": self.__config.user_agent,
                   "Accept": self.__config.mime_json}

        if self.__corporation_id is not None:
            headers["x-corporation-id"] = self.__corporation_id

        if self.__integrator_id is not None:
            headers["x-integrator-id"] = self.__integrator_id

        if self.__platform_id is not None:
            headers["x-platform-id"] = self.__platform_id

        if self.__custom_headers is not None:
            headers.update(self.__custom_headers)

        return headers

    @property
    def access_token(self):
        """
        Sets the attribute value and validates access_token
        """
        return self.__access_token

    @access_token.setter
    def access_token(self, value):
        if not isinstance(value, str):
            raise ValueError("Param access_token must be a String")
        self.__access_token = value

    @property
    def connection_timeout(self):
        """
        Sets the attribute value and validates connection timeout
        """
        return self.__connection_timeout

    @connection_timeout.setter
    def connection_timeout(self, value):
        if not isinstance(value, float):
            raise ValueError("Param connection_timeout must be a Float")
        self.__connection_timeout = value

    @property
    def corporation_id(self):
        """
        Sets the attribute value and validates corporation id
        """
        return self.__corporation_id

    @corporation_id.setter
    def corporation_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param corporation_id must be a String")
        self.__corporation_id = value

    @property
    def custom_headers(self):
        """
        Sets the attribute value and validates custom headers
        """
        return self.__custom_headers

    @custom_headers.setter
    def custom_headers(self, value):
        if not isinstance(value, dict):
            raise ValueError("Param custom_headers must be a Dictionary")
        self.__custom_headers = value

    @property
    def integrator_id(self):
        """
        Sets the attribute value and validates integrator id
        """
        return self.__integrator_id

    @integrator_id.setter
    def integrator_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param integrator_id must be a String")
        self.__integrator_id = value

    @property
    def max_retries(self):
        """
        Sets the attribute value and validates max retries
        """
        return self.__max_retries

    @max_retries.setter
    def max_retries(self, value):
        if not isinstance(value, int):
            raise ValueError("Param max_retries must be an Integer")
        self.__max_retries = value

    @property
    def platform_id(self):
        """
        Sets the attribute value and validates platform id
        """
        return self.__platform_id

    @platform_id.setter
    def platform_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param platform_id must be a String")
        self.__platform_id = value

Instance variables

var access_token

Sets the attribute value and validates access_token

Expand source code
@property
def access_token(self):
    """
    Sets the attribute value and validates access_token
    """
    return self.__access_token
var connection_timeout

Sets the attribute value and validates connection timeout

Expand source code
@property
def connection_timeout(self):
    """
    Sets the attribute value and validates connection timeout
    """
    return self.__connection_timeout
var corporation_id

Sets the attribute value and validates corporation id

Expand source code
@property
def corporation_id(self):
    """
    Sets the attribute value and validates corporation id
    """
    return self.__corporation_id
var custom_headers

Sets the attribute value and validates custom headers

Expand source code
@property
def custom_headers(self):
    """
    Sets the attribute value and validates custom headers
    """
    return self.__custom_headers
var integrator_id

Sets the attribute value and validates integrator id

Expand source code
@property
def integrator_id(self):
    """
    Sets the attribute value and validates integrator id
    """
    return self.__integrator_id
var max_retries

Sets the attribute value and validates max retries

Expand source code
@property
def max_retries(self):
    """
    Sets the attribute value and validates max retries
    """
    return self.__max_retries
var platform_id

Sets the attribute value and validates platform id

Expand source code
@property
def platform_id(self):
    """
    Sets the attribute value and validates platform id
    """
    return self.__platform_id

Methods

def get_headers(self)

Sets the attribute values of headers

Expand source code
def get_headers(self):
    """
    Sets the attribute values of headers
    """
    headers = {"Authorization": "Bearer " + self.__access_token,
               "x-product-id": self.__config.product_id,
               "x-tracking-id": self.__config.tracking_id,
               "x-idempotency-key": str(uuid.uuid4().int),
               "User-Agent": self.__config.user_agent,
               "Accept": self.__config.mime_json}

    if self.__corporation_id is not None:
        headers["x-corporation-id"] = self.__corporation_id

    if self.__integrator_id is not None:
        headers["x-integrator-id"] = self.__integrator_id

    if self.__platform_id is not None:
        headers["x-platform-id"] = self.__platform_id

    if self.__custom_headers is not None:
        headers.update(self.__custom_headers)

    return headers
mercadopago-sdk-python-b345a69/docs/core/000077500000000000000000000000001524412155200203115ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/docs/core/index.html000066400000000000000000000376551524412155200223260ustar00rootroot00000000000000 mercadopago.core API documentation

Module mercadopago.core

Module: core/init.py

Expand source code
"""
Module: core/__init__.py
"""
from mercadopago.core.mp_base import MPBase


__all__ = (
    'MPBase',
)

Sub-modules

mercadopago.core.mp_base

Module: mp_base

Classes

class MPBase (request_options, http_client)

All mercadopago.resources extends this one to call the REST services

Args

request_options (mercadopago.config.request_options, optional):
An instance of RequestOptions can be pass changing or adding custom options
to ur REST calls. Defaults to None.
http_client : mercadopago.http.http_client, optional
An implementation of

HttpClient can be pass to be used to make the REST calls. Defaults to None.

Raises

ValueError
Param request_options must be a RequestOptions Object
ValueError
Filters must be a Dictionary
Expand source code
class MPBase:
    """All mercadopago.resources extends this one to call the REST services

    Args:
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding custom options
        to ur REST calls. Defaults to None.
        http_client (mercadopago.http.http_client, optional): An implementation of
        HttpClient can be pass to be used to make the REST calls. Defaults to None.

    Raises:
        ValueError: Param request_options must be a RequestOptions Object
        ValueError: Filters must be a Dictionary
    """

    def __init__(self, request_options, http_client):
        if not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")

        self.__request_options = request_options
        self.__http_client = http_client
        self.__config = Config()

    def __check_request_options(self, request_options):
        if request_options is not None and not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        if request_options is None:
            request_options = self.__request_options

        if request_options.access_token is None:
            request_options.access_token = self.__request_options.access_token

        return request_options

    def __check_headers(self, request_options, extra_headers=None):
        headers = self.__request_options.get_headers()
        if request_options is not None:
            headers = request_options.get_headers()

        if extra_headers is not None:
            headers.update(extra_headers)

        return headers

    def _get(self, uri, filters=None, request_options=None):
        if filters is not None and not isinstance(filters, dict):
            raise ValueError("Filters must be a Dictionary")

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.get(
            url=self.__config.api_base_url + uri,
            params=filters,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _post(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.post(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _put(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.put(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _delete(self, uri, params=None, request_options=None):
        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(request_options)

        return self.__http_client.delete(
            url=self.__config.api_base_url + uri,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

    @property
    def config(self):
        """
        Returns the attribute value of the function
        """
        return self.__config

Subclasses

Instance variables

var config

Returns the attribute value of the function

Expand source code
@property
def config(self):
    """
    Returns the attribute value of the function
    """
    return self.__config
var request_options

Returns the attribute value of the function

Expand source code
@property
def request_options(self):
    """
    Returns the attribute value of the function
    """
    return self.__request_options
mercadopago-sdk-python-b345a69/docs/core/mp_base.html000066400000000000000000000500511524412155200226060ustar00rootroot00000000000000 mercadopago.core.mp_base API documentation

Module mercadopago.core.mp_base

Module: mp_base

Expand source code
"""
Module: mp_base
"""
from json.encoder import JSONEncoder

from mercadopago.config.config import Config
from mercadopago.config.request_options import RequestOptions


class MPBase:
    """All mercadopago.resources extends this one to call the REST services

    Args:
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding custom options
        to ur REST calls. Defaults to None.
        http_client (mercadopago.http.http_client, optional): An implementation of
        HttpClient can be pass to be used to make the REST calls. Defaults to None.

    Raises:
        ValueError: Param request_options must be a RequestOptions Object
        ValueError: Filters must be a Dictionary
    """

    def __init__(self, request_options, http_client):
        if not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")

        self.__request_options = request_options
        self.__http_client = http_client
        self.__config = Config()

    def __check_request_options(self, request_options):
        if request_options is not None and not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        if request_options is None:
            request_options = self.__request_options

        if request_options.access_token is None:
            request_options.access_token = self.__request_options.access_token

        return request_options

    def __check_headers(self, request_options, extra_headers=None):
        headers = self.__request_options.get_headers()
        if request_options is not None:
            headers = request_options.get_headers()

        if extra_headers is not None:
            headers.update(extra_headers)

        return headers

    def _get(self, uri, filters=None, request_options=None):
        if filters is not None and not isinstance(filters, dict):
            raise ValueError("Filters must be a Dictionary")

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.get(
            url=self.__config.api_base_url + uri,
            params=filters,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _post(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.post(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _put(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.put(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _delete(self, uri, params=None, request_options=None):
        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(request_options)

        return self.__http_client.delete(
            url=self.__config.api_base_url + uri,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

    @property
    def config(self):
        """
        Returns the attribute value of the function
        """
        return self.__config

Classes

class MPBase (request_options, http_client)

All mercadopago.resources extends this one to call the REST services

Args

request_options (mercadopago.config.request_options, optional):
An instance of RequestOptions can be pass changing or adding custom options
to ur REST calls. Defaults to None.
http_client : mercadopago.http.http_client, optional
An implementation of

HttpClient can be pass to be used to make the REST calls. Defaults to None.

Raises

ValueError
Param request_options must be a RequestOptions Object
ValueError
Filters must be a Dictionary
Expand source code
class MPBase:
    """All mercadopago.resources extends this one to call the REST services

    Args:
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding custom options
        to ur REST calls. Defaults to None.
        http_client (mercadopago.http.http_client, optional): An implementation of
        HttpClient can be pass to be used to make the REST calls. Defaults to None.

    Raises:
        ValueError: Param request_options must be a RequestOptions Object
        ValueError: Filters must be a Dictionary
    """

    def __init__(self, request_options, http_client):
        if not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")

        self.__request_options = request_options
        self.__http_client = http_client
        self.__config = Config()

    def __check_request_options(self, request_options):
        if request_options is not None and not isinstance(request_options, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        if request_options is None:
            request_options = self.__request_options

        if request_options.access_token is None:
            request_options.access_token = self.__request_options.access_token

        return request_options

    def __check_headers(self, request_options, extra_headers=None):
        headers = self.__request_options.get_headers()
        if request_options is not None:
            headers = request_options.get_headers()

        if extra_headers is not None:
            headers.update(extra_headers)

        return headers

    def _get(self, uri, filters=None, request_options=None):
        if filters is not None and not isinstance(filters, dict):
            raise ValueError("Filters must be a Dictionary")

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.get(
            url=self.__config.api_base_url + uri,
            params=filters,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _post(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.post(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _put(self, uri, data=None, params=None, request_options=None):
        if data is not None:
            data = JSONEncoder().encode(data)

        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(
            request_options, {"Content-type": self.__config.mime_json})

        return self.__http_client.put(
            url=self.__config.api_base_url + uri,
            data=data,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    def _delete(self, uri, params=None, request_options=None):
        request_options = self.__check_request_options(request_options)
        headers = self.__check_headers(request_options)

        return self.__http_client.delete(
            url=self.__config.api_base_url + uri,
            params=params,
            headers=headers,
            timeout=request_options.connection_timeout,
            maxretries=request_options.max_retries,
        )

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

    @property
    def config(self):
        """
        Returns the attribute value of the function
        """
        return self.__config

Subclasses

Instance variables

var config

Returns the attribute value of the function

Expand source code
@property
def config(self):
    """
    Returns the attribute value of the function
    """
    return self.__config
var request_options

Returns the attribute value of the function

Expand source code
@property
def request_options(self):
    """
    Returns the attribute value of the function
    """
    return self.__request_options
mercadopago-sdk-python-b345a69/docs/http/000077500000000000000000000000001524412155200203405ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/docs/http/http_client.html000066400000000000000000000415021524412155200235450ustar00rootroot00000000000000 mercadopago.http.http_client API documentation

Module mercadopago.http.http_client

Module: http_client

Expand source code
"""
Module: http_client
"""
import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry


class HttpClient:
    """
    Default implementation to call all REST API's
    """

    def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
        """Makes a call to the API.

        All **kwargs are passed verbatim to ``requests.request``.
        """
        retry_strategy = Retry(
            total=maxretries,
            status_forcelist=[429, 500, 502, 503, 504]
        )
        http = requests.Session()
        http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
        with http as session:
            api_result = session.request(method, url, **kwargs)
            response = {
                "status": api_result.status_code,
                "response": api_result.json()
            }

        return response

    def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a GET request to the API"""
        return self.request(
            "GET",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a POST request to the API"""
        return self.request(
            "POST",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a PUT request to the API"""
        return self.request(
            "PUT",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a DELETE request to the API"""
        return self.request(
            "DELETE",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

Classes

class HttpClient

Default implementation to call all REST API's

Expand source code
class HttpClient:
    """
    Default implementation to call all REST API's
    """

    def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
        """Makes a call to the API.

        All **kwargs are passed verbatim to ``requests.request``.
        """
        retry_strategy = Retry(
            total=maxretries,
            status_forcelist=[429, 500, 502, 503, 504]
        )
        http = requests.Session()
        http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
        with http as session:
            api_result = session.request(method, url, **kwargs)
            response = {
                "status": api_result.status_code,
                "response": api_result.json()
            }

        return response

    def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a GET request to the API"""
        return self.request(
            "GET",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a POST request to the API"""
        return self.request(
            "POST",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a PUT request to the API"""
        return self.request(
            "PUT",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a DELETE request to the API"""
        return self.request(
            "DELETE",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

Methods

def delete(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a DELETE request to the API

Expand source code
def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a DELETE request to the API"""
    return self.request(
        "DELETE",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def get(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a GET request to the API

Expand source code
def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a GET request to the API"""
    return self.request(
        "GET",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a POST request to the API

Expand source code
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a POST request to the API"""
    return self.request(
        "POST",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a PUT request to the API

Expand source code
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a PUT request to the API"""
    return self.request(
        "PUT",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def request(self, method, url, maxretries=None, **kwargs)

Makes a call to the API.

All **kwargs are passed verbatim to requests.request.

Expand source code
def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
    """Makes a call to the API.

    All **kwargs are passed verbatim to ``requests.request``.
    """
    retry_strategy = Retry(
        total=maxretries,
        status_forcelist=[429, 500, 502, 503, 504]
    )
    http = requests.Session()
    http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
    with http as session:
        api_result = session.request(method, url, **kwargs)
        response = {
            "status": api_result.status_code,
            "response": api_result.json()
        }

    return response
mercadopago-sdk-python-b345a69/docs/http/index.html000066400000000000000000000351621524412155200223440ustar00rootroot00000000000000 mercadopago.http API documentation

Module mercadopago.http

Module: http/init.py

Expand source code
"""
Module: http/__init__.py
"""
from mercadopago.http.http_client import HttpClient


__all__ = (
    'HttpClient',
)

Sub-modules

mercadopago.http.http_client

Module: http_client

Classes

class HttpClient

Default implementation to call all REST API's

Expand source code
class HttpClient:
    """
    Default implementation to call all REST API's
    """

    def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
        """Makes a call to the API.

        All **kwargs are passed verbatim to ``requests.request``.
        """
        retry_strategy = Retry(
            total=maxretries,
            status_forcelist=[429, 500, 502, 503, 504]
        )
        http = requests.Session()
        http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
        with http as session:
            api_result = session.request(method, url, **kwargs)
            response = {
                "status": api_result.status_code,
                "response": api_result.json()
            }

        return response

    def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a GET request to the API"""
        return self.request(
            "GET",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a POST request to the API"""
        return self.request(
            "POST",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a PUT request to the API"""
        return self.request(
            "PUT",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a DELETE request to the API"""
        return self.request(
            "DELETE",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

Methods

def delete(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a DELETE request to the API

Expand source code
def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a DELETE request to the API"""
    return self.request(
        "DELETE",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def get(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a GET request to the API

Expand source code
def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a GET request to the API"""
    return self.request(
        "GET",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a POST request to the API

Expand source code
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a POST request to the API"""
    return self.request(
        "POST",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a PUT request to the API

Expand source code
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a PUT request to the API"""
    return self.request(
        "PUT",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def request(self, method, url, maxretries=None, **kwargs)

Makes a call to the API.

All **kwargs are passed verbatim to requests.request.

Expand source code
def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
    """Makes a call to the API.

    All **kwargs are passed verbatim to ``requests.request``.
    """
    retry_strategy = Retry(
        total=maxretries,
        status_forcelist=[429, 500, 502, 503, 504]
    )
    http = requests.Session()
    http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
    with http as session:
        api_result = session.request(method, url, **kwargs)
        response = {
            "status": api_result.status_code,
            "response": api_result.json()
        }

    return response
mercadopago-sdk-python-b345a69/docs/index.html000066400000000000000000000653671524412155200213770ustar00rootroot00000000000000 mercadopago API documentation

Package mercadopago

Module: mercadopago/init.py

Expand source code
"""
Module: mercadopago/__init__.py
"""
from mercadopago.sdk import SDK


__all__ = (
    'SDK',
)

Sub-modules

mercadopago.config

Module: config/init.py

mercadopago.core

Module: core/init.py

mercadopago.http

Module: http/init.py

mercadopago.resources

Module: resources/init.py

mercadopago.sdk

Module: sdk

Classes

class SDK (access_token, http_client=None, request_options=None)

Generate access to all API' modules, which are:

  1. Advanced Payment
  2. Card Token
  3. Card
  4. Customer
  5. Disbursement Refund
  6. Identification Type
  7. Merchant Order
  8. Payment Methods
  9. Payment
  10. Preapproval
  11. Preference
  12. Refund
  13. User

Construct ur SDK Object to have access to all APIs modules.

Args

Click here for more info
http_client : mercadopago.http.http_client, optional
An implementation of
HttpClient can be pass to be used to make the REST calls. Defaults to None.
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST calls. Defaults to None.

Raises

ValueError
Param request_options must be a RequestOptions Object
Expand source code
class SDK:
    """Generate access to all API' modules, which are:

        1. Advanced Payment
        2. Card Token
        3. Card
        4. Customer
        5. Disbursement Refund
        6. Identification Type
        7. Merchant Order
        8. Payment Methods
        9. Payment
        10. Preapproval
        11. Preference
        12. Refund
        13. User
    """

    def __init__(
        self,
        access_token,
        http_client=None,
        request_options=None,
    ):
        """Construct ur SDK Object to have access to all APIs modules.
        Args:
            [Click here for more info](https://www.mercadopago.com/mlb/account/credentials)
            http_client (mercadopago.http.http_client, optional): An implementation of
            HttpClient can be pass to be used to make the REST calls. Defaults to None.
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            calls. Defaults to None.
        Raises:
            ValueError: Param request_options must be a RequestOptions Object
        """

        self.http_client = http_client
        if http_client is None:
            self.http_client = HttpClient()

        self.request_options = request_options
        if request_options is None:
            self.request_options = RequestOptions()

        self.request_options.access_token = access_token

    def advanced_payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return AdvancedPayment(request_options is not None and request_options
                               or self.request_options, self.http_client)

    def card_token(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return CardToken(request_options is not None and request_options
                         or self.request_options, self.http_client)

    def card(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Card(request_options is not None and request_options
                    or self.request_options, self.http_client)

    def customer(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Customer(request_options is not None and request_options
                        or self.request_options, self.http_client)

    def disbursement_refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return DisbursementRefund(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def identification_type(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return IdentificationType(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def merchant_order(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return MerchantOrder(request_options is not None and request_options
                             or self.request_options, self.http_client)

    def payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Payment(request_options is not None and request_options
                       or self.request_options, self.http_client)

    def payment_methods(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PaymentMethods(request_options is not None and request_options
                              or self.request_options, self.http_client)

    def preapproval(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PreApproval(request_options is not None and request_options
                           or self.request_options, self.http_client)

    def preference(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Preference(request_options is not None and request_options
                          or self.request_options, self.http_client)

    def refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Refund(request_options is not None and request_options
                      or self.request_options, self.http_client)

    def user(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return User(request_options is not None and request_options
                    or self.request_options, self.http_client)

    @property
    def request_options(self):
        """
        Sets the attribute value and validates request_options
        """
        return self.__request_options

    @request_options.setter
    def request_options(self, value):
        if value is not None and not isinstance(value, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        self.__request_options = value

    @property
    def http_client(self):
        """
        Sets the attribute value and validates http_client
        """
        return self.__http_client

    @http_client.setter
    def http_client(self, value):
        if value is not None and not isinstance(value, HttpClient):
            raise ValueError("Param http_client must be a HttpClient Object")
        self.__http_client = value

Instance variables

var http_client

Sets the attribute value and validates http_client

Expand source code
@property
def http_client(self):
    """
    Sets the attribute value and validates http_client
    """
    return self.__http_client
var request_options

Sets the attribute value and validates request_options

Expand source code
@property
def request_options(self):
    """
    Sets the attribute value and validates request_options
    """
    return self.__request_options

Methods

def advanced_payment(self, request_options=None)

Returns the attribute value of the function

Expand source code
def advanced_payment(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return AdvancedPayment(request_options is not None and request_options
                           or self.request_options, self.http_client)
def card(self, request_options=None)

Returns the attribute value of the function

Expand source code
def card(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Card(request_options is not None and request_options
                or self.request_options, self.http_client)
def card_token(self, request_options=None)

Returns the attribute value of the function

Expand source code
def card_token(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return CardToken(request_options is not None and request_options
                     or self.request_options, self.http_client)
def customer(self, request_options=None)

Returns the attribute value of the function

Expand source code
def customer(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Customer(request_options is not None and request_options
                    or self.request_options, self.http_client)
def disbursement_refund(self, request_options=None)

Returns the attribute value of the function

Expand source code
def disbursement_refund(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return DisbursementRefund(request_options is not None and request_options
                              or self.request_options, self.http_client)
def identification_type(self, request_options=None)

Returns the attribute value of the function

Expand source code
def identification_type(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return IdentificationType(request_options is not None and request_options
                              or self.request_options, self.http_client)
def merchant_order(self, request_options=None)

Returns the attribute value of the function

Expand source code
def merchant_order(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return MerchantOrder(request_options is not None and request_options
                         or self.request_options, self.http_client)
def payment(self, request_options=None)

Returns the attribute value of the function

Expand source code
def payment(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Payment(request_options is not None and request_options
                   or self.request_options, self.http_client)
def payment_methods(self, request_options=None)

Returns the attribute value of the function

Expand source code
def payment_methods(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return PaymentMethods(request_options is not None and request_options
                          or self.request_options, self.http_client)
def preapproval(self, request_options=None)

Returns the attribute value of the function

Expand source code
def preapproval(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return PreApproval(request_options is not None and request_options
                       or self.request_options, self.http_client)
def preference(self, request_options=None)

Returns the attribute value of the function

Expand source code
def preference(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Preference(request_options is not None and request_options
                      or self.request_options, self.http_client)
def refund(self, request_options=None)

Returns the attribute value of the function

Expand source code
def refund(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Refund(request_options is not None and request_options
                  or self.request_options, self.http_client)
def user(self, request_options=None)

Returns the attribute value of the function

Expand source code
def user(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return User(request_options is not None and request_options
                or self.request_options, self.http_client)
mercadopago-sdk-python-b345a69/docs/resources/000077500000000000000000000000001524412155200213735ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/docs/resources/advanced_payment.html000066400000000000000000001125671524412155200255770ustar00rootroot00000000000000 mercadopago.resources.advanced_payment API documentation

Module mercadopago.resources.advanced_payment

Module: advanced_payment

Expand source code
"""
    Module: advanced_payment
"""
from datetime import datetime

from mercadopago.core import MPBase


class AdvancedPayment(MPBase):
    """
    Access to Advanced Payments
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments_id_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding custom options
            to ur REST call. Defaults to None.

        Returns:
            dict: Advanced Payment search response
        """
        return self._get(uri="/v1/advanced_payments/search", filters=filters,
                         request_options=request_options)

    def get(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment find response
        """
        return self._get(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         request_options=request_options)

    def create(self, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_object (dict): Advanced Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment creation response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._post(uri="/v1/advanced_payments", data=advanced_payment_object,
                          request_options=request_options)

    def capture(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment capture response
        """
        capture_object = {"capture": True}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=capture_object, request_options=request_options)

    def update(self, advanced_payment_id, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            advanced_payment_object (dict): Advanced Payment to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment modification response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=advanced_payment_object, request_options=request_options)

    def cancel(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Advanced Payment cancelation response
        """
        cancel_object = {"status": "cancelled"}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=cancel_object, request_options=request_options)

    def update_release_date(self, advanced_payment_id, release_date, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id_disbursements_disbursement_id_disburses/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            release_date (datetime): Advanced Payment to be canceled
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param release_date must be a DateTime

        Returns:
            dict: Advanced Payment release date modification response
        """
        if not isinstance(release_date, datetime):
            raise ValueError("Param release_date must be a DateTime")

        disbursement_object = {
            "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")}

        return self._post(uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/disburses",
                          data=disbursement_object, request_options=request_options)

Classes

class AdvancedPayment (request_options, http_client)

Access to Advanced Payments

Expand source code
class AdvancedPayment(MPBase):
    """
    Access to Advanced Payments
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments_id_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding custom options
            to ur REST call. Defaults to None.

        Returns:
            dict: Advanced Payment search response
        """
        return self._get(uri="/v1/advanced_payments/search", filters=filters,
                         request_options=request_options)

    def get(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment find response
        """
        return self._get(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         request_options=request_options)

    def create(self, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_object (dict): Advanced Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment creation response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._post(uri="/v1/advanced_payments", data=advanced_payment_object,
                          request_options=request_options)

    def capture(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment capture response
        """
        capture_object = {"capture": True}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=capture_object, request_options=request_options)

    def update(self, advanced_payment_id, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            advanced_payment_object (dict): Advanced Payment to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment modification response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=advanced_payment_object, request_options=request_options)

    def cancel(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Advanced Payment cancelation response
        """
        cancel_object = {"status": "cancelled"}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=cancel_object, request_options=request_options)

    def update_release_date(self, advanced_payment_id, release_date, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id_disbursements_disbursement_id_disburses/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            release_date (datetime): Advanced Payment to be canceled
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param release_date must be a DateTime

        Returns:
            dict: Advanced Payment release date modification response
        """
        if not isinstance(release_date, datetime):
            raise ValueError("Param release_date must be a DateTime")

        disbursement_object = {
            "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")}

        return self._post(uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/disburses",
                          data=disbursement_object, request_options=request_options)

Ancestors

Methods

def cancel(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment cancelation response
Expand source code
def cancel(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Advanced Payment cancelation response
    """
    cancel_object = {"status": "cancelled"}
    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=cancel_object, request_options=request_options)
def capture(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment capture response
Expand source code
def capture(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Returns:
        dict: Advanced Payment capture response
    """
    capture_object = {"capture": True}
    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=capture_object, request_options=request_options)
def create(self, advanced_payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_object : dict
Advanced Payment to be created
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param advanced_payment_object must be a Dictionary

Returns

dict
Advanced Payment creation response
Expand source code
def create(self, advanced_payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments/post/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_object (dict): Advanced Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Raises:
        ValueError: Param advanced_payment_object must be a Dictionary

    Returns:
        dict: Advanced Payment creation response
    """
    if not isinstance(advanced_payment_object, dict):
        raise ValueError(
            "Param advanced_payment_object must be a Dictionary")

    return self._post(uri="/v1/advanced_payments", data=advanced_payment_object,
                      request_options=request_options)
def get(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment find response
Expand source code
def get(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/get/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Returns:
        dict: Advanced Payment find response
    """
    return self._get(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment search response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments_id_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding custom options
        to ur REST call. Defaults to None.

    Returns:
        dict: Advanced Payment search response
    """
    return self._get(uri="/v1/advanced_payments/search", filters=filters,
                     request_options=request_options)
def update(self, advanced_payment_id, advanced_payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
advanced_payment_object : dict
Advanced Payment to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param advanced_payment_object must be a Dictionary

Returns

dict
Advanced Payment modification response
Expand source code
def update(self, advanced_payment_id, advanced_payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        advanced_payment_object (dict): Advanced Payment to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param advanced_payment_object must be a Dictionary

    Returns:
        dict: Advanced Payment modification response
    """
    if not isinstance(advanced_payment_object, dict):
        raise ValueError(
            "Param advanced_payment_object must be a Dictionary")

    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=advanced_payment_object, request_options=request_options)
def update_release_date(self, advanced_payment_id, release_date, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
release_date : datetime
Advanced Payment to be canceled
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param release_date must be a DateTime

Returns

dict
Advanced Payment release date modification response
Expand source code
def update_release_date(self, advanced_payment_id, release_date, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id_disbursements_disbursement_id_disburses/post/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        release_date (datetime): Advanced Payment to be canceled
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param release_date must be a DateTime

    Returns:
        dict: Advanced Payment release date modification response
    """
    if not isinstance(release_date, datetime):
        raise ValueError("Param release_date must be a DateTime")

    disbursement_object = {
        "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")}

    return self._post(uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/disburses",
                      data=disbursement_object, request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/card.html000066400000000000000000000705771524412155200232120ustar00rootroot00000000000000 mercadopago.resources.card API documentation

Module mercadopago.resources.card

Module: card

Expand source code
"""
    Module: card
"""
from mercadopago.core import MPBase


class Card(MPBase):
    """
    The cards class is the way to store card data of your customers
    safely to improve the shopping experience.

    This will allow your customers to complete their purchases much
    faster and easily, since they will not have to complete their
    card data again.

    This class must be used in conjunction with the Customer class.

    [Click here for more info](https://www.mercadopago.com/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def list_all(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards",
            request_options=request_options,
        )

    def get(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_id (dict): Card ID to be found
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards/{str(card_id)}",
            request_options=request_options,
        )

    def create(self, customer_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/post/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_object (dict): Card object to be created
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card creation response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._post(uri="/v1/customers/" + str(customer_id)
                          + "/cards/", data=card_object, request_options=request_options)

    def update(self, customer_id, card_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be modified
            card_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card modification response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id)
                         + "/cards/" + str(card_id), data=card_object,
                         request_options=request_options)

    def delete(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/delete/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be deleted
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id)
                            + "/cards/" + str(card_id), request_options=request_options)

Classes

class Card (request_options, http_client)

The cards class is the way to store card data of your customers safely to improve the shopping experience.

This will allow your customers to complete their purchases much faster and easily, since they will not have to complete their card data again.

This class must be used in conjunction with the Customer class.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Card(MPBase):
    """
    The cards class is the way to store card data of your customers
    safely to improve the shopping experience.

    This will allow your customers to complete their purchases much
    faster and easily, since they will not have to complete their
    card data again.

    This class must be used in conjunction with the Customer class.

    [Click here for more info](https://www.mercadopago.com/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def list_all(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards",
            request_options=request_options,
        )

    def get(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_id (dict): Card ID to be found
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards/{str(card_id)}",
            request_options=request_options,
        )

    def create(self, customer_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/post/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_object (dict): Card object to be created
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card creation response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._post(uri="/v1/customers/" + str(customer_id)
                          + "/cards/", data=card_object, request_options=request_options)

    def update(self, customer_id, card_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be modified
            card_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card modification response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id)
                         + "/cards/" + str(card_id), data=card_object,
                         request_options=request_options)

    def delete(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/delete/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be deleted
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id)
                            + "/cards/" + str(card_id), request_options=request_options)

Ancestors

Methods

def create(self, customer_id, card_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
card_object : dict
Card object to be created

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_object must be a Dictionary

Returns

dict
Card creation response
Expand source code
def create(self, customer_id, card_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/post/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        card_object (dict): Card object to be created
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param card_object must be a Dictionary

    Returns:
        dict: Card creation response
    """
    if not isinstance(card_object, dict):
        raise ValueError("Param card_object must be a Dictionary")

    return self._post(uri="/v1/customers/" + str(customer_id)
                      + "/cards/", data=card_object, request_options=request_options)
def delete(self, customer_id, card_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
Customer ID owner
card_id : str
Card ID to be deleted

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card exclusion response
Expand source code
def delete(self, customer_id, card_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/delete/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): Customer ID owner
        card_id (str): Card ID to be deleted
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Card exclusion response
    """
    return self._delete(uri="/v1/customers/" + str(customer_id)
                        + "/cards/" + str(card_id), request_options=request_options)
def get(self, customer_id, card_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
card_id : dict
Card ID to be found

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card find response
Expand source code
def get(self, customer_id, card_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        card_id (dict): Card ID to be found
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Card find response
    """
    return self._get(
        uri=f"/v1/customers/{str(customer_id)}/cards/{str(card_id)}",
        request_options=request_options,
    )
def list_all(self, customer_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Cards find response
Expand source code
def list_all(self, customer_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Cards find response
    """
    return self._get(
        uri=f"/v1/customers/{str(customer_id)}/cards",
        request_options=request_options,
    )
def update(self, customer_id, card_id, card_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
Customer ID owner
card_id : str
Card ID to be modified
card_object : dict
Values to be modified

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_object must be a Dictionary

Returns

dict
Card modification response
Expand source code
def update(self, customer_id, card_id, card_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/put/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): Customer ID owner
        card_id (str): Card ID to be modified
        card_object (dict): Values to be modified
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param card_object must be a Dictionary

    Returns:
        dict: Card modification response
    """
    if not isinstance(card_object, dict):
        raise ValueError("Param card_object must be a Dictionary")

    return self._put(uri="/v1/customers/" + str(customer_id)
                     + "/cards/" + str(card_id), data=card_object,
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/card_token.html000066400000000000000000000347501524412155200244030ustar00rootroot00000000000000 mercadopago.resources.card_token API documentation

Module mercadopago.resources.card_token

Module: card_token

Expand source code
"""
    Module: card_token
"""
from mercadopago.core import MPBase


class CardToken(MPBase):
    """
    This class will allow you to send your customers card data for Mercado Pago
    server and receive a token to complete the payments transactions.
    """

    def get(self, card_token_id, request_options=None):
        """Args:
            card_token_id (str): The Card Token ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Card Token find response
        """
        return self._get(uri="/v1/card_tokens/" + str(card_token_id),
                         request_options=request_options)

    def create(self, card_token_object, request_options=None):
        """Args:
            card_token_object (dict): Card Token to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param card_token_object must be a Dictionary

        Returns:
            dict: Card Token creation response
        """
        if not isinstance(card_token_object, dict):
            raise ValueError("Param card_token_object must be a Dictionary")

        return self._post(uri="/v1/card_tokens", data=card_token_object,
                          request_options=request_options)

Classes

class CardToken (request_options, http_client)

This class will allow you to send your customers card data for Mercado Pago server and receive a token to complete the payments transactions.

Expand source code
class CardToken(MPBase):
    """
    This class will allow you to send your customers card data for Mercado Pago
    server and receive a token to complete the payments transactions.
    """

    def get(self, card_token_id, request_options=None):
        """Args:
            card_token_id (str): The Card Token ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Card Token find response
        """
        return self._get(uri="/v1/card_tokens/" + str(card_token_id),
                         request_options=request_options)

    def create(self, card_token_object, request_options=None):
        """Args:
            card_token_object (dict): Card Token to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param card_token_object must be a Dictionary

        Returns:
            dict: Card Token creation response
        """
        if not isinstance(card_token_object, dict):
            raise ValueError("Param card_token_object must be a Dictionary")

        return self._post(uri="/v1/card_tokens", data=card_token_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, card_token_object, request_options=None)

Args

card_token_object : dict
Card Token to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_token_object must be a Dictionary

Returns

dict
Card Token creation response
Expand source code
def create(self, card_token_object, request_options=None):
    """Args:
        card_token_object (dict): Card Token to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param card_token_object must be a Dictionary

    Returns:
        dict: Card Token creation response
    """
    if not isinstance(card_token_object, dict):
        raise ValueError("Param card_token_object must be a Dictionary")

    return self._post(uri="/v1/card_tokens", data=card_token_object,
                      request_options=request_options)
def get(self, card_token_id, request_options=None)

Args

card_token_id : str
The Card Token ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card Token find response
Expand source code
def get(self, card_token_id, request_options=None):
    """Args:
        card_token_id (str): The Card Token ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Card Token find response
    """
    return self._get(uri="/v1/card_tokens/" + str(card_token_id),
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/customer.html000066400000000000000000000654731524412155200241410ustar00rootroot00000000000000 mercadopago.resources.customer API documentation

Module mercadopago.resources.customer

Module: customer

Expand source code
"""
    Module: customer
"""
from mercadopago.core import MPBase


class Customer(MPBase):
    """
    This class allows you to store customers data safely to improve the shopping experience.

    This will allow your customer to complete their purchases much faster and easily when
    used in conjunction with the Cards class.

    [Click here for more info](https://mercadopago.com.br/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/search", filters=filters,
                         request_options=request_options)

    def get(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/" + str(customer_id), request_options=request_options)

    def create(self, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers/post/)  # pylint: disable=line-too-long

        Args:
            customer_object (dict): Customer object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer creation response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._post(uri="/v1/customers", data=customer_object,
                          request_options=request_options)

    def update(self, customer_id, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            customer_object (dict): Customer object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValeuError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer modification response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id), data=customer_object,
                         request_options=request_options)

    def delete(self, customer_id, request_options=None):
        """
        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id),
                            request_options=request_options)

Classes

class Customer (request_options, http_client)

This class allows you to store customers data safely to improve the shopping experience.

This will allow your customer to complete their purchases much faster and easily when used in conjunction with the Cards class.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Customer(MPBase):
    """
    This class allows you to store customers data safely to improve the shopping experience.

    This will allow your customer to complete their purchases much faster and easily when
    used in conjunction with the Cards class.

    [Click here for more info](https://mercadopago.com.br/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/search", filters=filters,
                         request_options=request_options)

    def get(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/" + str(customer_id), request_options=request_options)

    def create(self, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers/post/)  # pylint: disable=line-too-long

        Args:
            customer_object (dict): Customer object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer creation response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._post(uri="/v1/customers", data=customer_object,
                          request_options=request_options)

    def update(self, customer_id, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            customer_object (dict): Customer object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValeuError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer modification response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id), data=customer_object,
                         request_options=request_options)

    def delete(self, customer_id, request_options=None):
        """
        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id),
                            request_options=request_options)

Ancestors

Methods

def create(self, customer_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_object : dict
Customer object to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param customer_object must be a Dictionary

Returns

dict
Customer creation response
Expand source code
def create(self, customer_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers/post/)  # pylint: disable=line-too-long

    Args:
        customer_object (dict): Customer object to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param customer_object must be a Dictionary

    Returns:
        dict: Customer creation response
    """
    if not isinstance(customer_object, dict):
        raise ValueError("Param customer_object must be a Dictionary")

    return self._post(uri="/v1/customers", data=customer_object,
                      request_options=request_options)
def delete(self, customer_id, request_options=None)

Args

customer_id : str
The Customer ID owner
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer exclusion response
Expand source code
def delete(self, customer_id, request_options=None):
    """
    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer exclusion response
    """
    return self._delete(uri="/v1/customers/" + str(customer_id),
                        request_options=request_options)
def get(self, customer_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer find response
Expand source code
def get(self, customer_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer find response
    """
    return self._get(uri="/v1/customers/" + str(customer_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer find response
    """
    return self._get(uri="/v1/customers/search", filters=filters,
                     request_options=request_options)
def update(self, customer_id, customer_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
customer_object : dict
Customer object to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValeuError
Param customer_object must be a Dictionary

Returns

dict
Customer modification response
Expand source code
def update(self, customer_id, customer_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_id/put/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        customer_object (dict): Customer object to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValeuError: Param customer_object must be a Dictionary

    Returns:
        dict: Customer modification response
    """
    if not isinstance(customer_object, dict):
        raise ValueError("Param customer_object must be a Dictionary")

    return self._put(uri="/v1/customers/" + str(customer_id), data=customer_object,
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/disbursement_refund.html000066400000000000000000000575511524412155200263450ustar00rootroot00000000000000 mercadopago.resources.disbursement_refund API documentation

Module mercadopago.resources.disbursement_refund

Module: disbursement_refund

Expand source code
"""
    Module: disbursement_refund
"""
from mercadopago.core import MPBase


class DisbursementRefund(MPBase):

    """
    Access to Advanced Payments Refunds
    """

    def list_all(self, advanced_payment_id, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Disbursement Refund find response
        """
        uri = f"/v1/advanced_payments/{str(advanced_payment_id)}/refunds"
        return self._get(uri=uri, request_options=request_options)

    def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_refund_object (dict): Disbursement Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund creation all response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        return self._post(
            uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/refunds",
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def create(self, advanced_payment_id, disbursement_id, amount, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            amount: Amount to be refunded
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param amount must be a Float

        Returns:
            dict: Disbursement Refund creation response
        """
        if not isinstance(amount, float):
            raise ValueError("Param amount must be a Float")

        disbursement_refund_object = {"amount": amount}

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object,
             request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            disbursement_refund_object (dict): Disbursement Refund to be saved
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund save response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

Classes

class DisbursementRefund (request_options, http_client)

Access to Advanced Payments Refunds

Expand source code
class DisbursementRefund(MPBase):

    """
    Access to Advanced Payments Refunds
    """

    def list_all(self, advanced_payment_id, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Disbursement Refund find response
        """
        uri = f"/v1/advanced_payments/{str(advanced_payment_id)}/refunds"
        return self._get(uri=uri, request_options=request_options)

    def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_refund_object (dict): Disbursement Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund creation all response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        return self._post(
            uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/refunds",
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def create(self, advanced_payment_id, disbursement_id, amount, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            amount: Amount to be refunded
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param amount must be a Float

        Returns:
            dict: Disbursement Refund creation response
        """
        if not isinstance(amount, float):
            raise ValueError("Param amount must be a Float")

        disbursement_refund_object = {"amount": amount}

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object,
             request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            disbursement_refund_object (dict): Disbursement Refund to be saved
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund save response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

Ancestors

Methods

def create(self, advanced_payment_id, disbursement_id, amount, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_id (str): Disbursement ID amount: Amount to be refunded request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param amount must be a Float

Returns

dict
Disbursement Refund creation response
Expand source code
def create(self, advanced_payment_id, disbursement_id, amount, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_id (str): Disbursement ID
        amount: Amount to be refunded
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param amount must be a Float

    Returns:
        dict: Disbursement Refund creation response
    """
    if not isinstance(amount, float):
        raise ValueError("Param amount must be a Float")

    disbursement_refund_object = {"amount": amount}

    uri = (
        f"/v1/advanced_payments/{str(advanced_payment_id)}"
        f"/disbursements/{str(disbursement_id)}/refunds"
    )

    return self._post(
        uri=uri,
        data=disbursement_refund_object,
        request_options=request_options,
    )
def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_refund_object (dict): Disbursement Refund to be created request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param disbursement_refund_object must be a Dictionary

Returns

dict
Disbursement Refund creation all response
Expand source code
def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_refund_object (dict): Disbursement Refund to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param disbursement_refund_object must be a Dictionary

    Returns:
        dict: Disbursement Refund creation all response
    """
    if not isinstance(disbursement_refund_object, dict):
        raise ValueError(
            "Param disbursement_refund_object must be a Dictionary")

    return self._post(
        uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/refunds",
        data=disbursement_refund_object,
        request_options=request_options,
    )
def list_all(self, advanced_payment_id, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Disbursement Refund find response
Expand source code
def list_all(self, advanced_payment_id, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Disbursement Refund find response
    """
    uri = f"/v1/advanced_payments/{str(advanced_payment_id)}/refunds"
    return self._get(uri=uri, request_options=request_options)
def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_id (str): Disbursement ID disbursement_refund_object (dict): Disbursement Refund to be saved request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param disbursement_refund_object must be a Dictionary

Returns

dict
Disbursement Refund save response
Expand source code
def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object,
         request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_id (str): Disbursement ID
        disbursement_refund_object (dict): Disbursement Refund to be saved
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param disbursement_refund_object must be a Dictionary

    Returns:
        dict: Disbursement Refund save response
    """
    if not isinstance(disbursement_refund_object, dict):
        raise ValueError(
            "Param disbursement_refund_object must be a Dictionary")

    uri = (
        f"/v1/advanced_payments/{str(advanced_payment_id)}"
        f"/disbursements/{str(disbursement_id)}/refunds"
    )

    return self._post(
        uri=uri,
        data=disbursement_refund_object,
        request_options=request_options,
    )

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/identification_type.html000066400000000000000000000267511524412155200263260ustar00rootroot00000000000000 mercadopago.resources.identification_type API documentation

Module mercadopago.resources.identification_type

Module: identification_type

Expand source code
"""
    Module: identification_type
"""
from mercadopago.core import MPBase


class IdentificationType(MPBase):
    """
    Access to Identification Types
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/identification_types/_identification_types/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Identification Types find response
        """
        return self._get(uri="/v1/identification_types", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Classes

class IdentificationType (request_options, http_client)

Access to Identification Types

Expand source code
class IdentificationType(MPBase):
    """
    Access to Identification Types
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/identification_types/_identification_types/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Identification Types find response
        """
        return self._get(uri="/v1/identification_types", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def list_all(self, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Identification Types find response
Expand source code
def list_all(self, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/identification_types/_identification_types/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Identification Types find response
    """
    return self._get(uri="/v1/identification_types", request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/index.html000066400000000000000000005470231524412155200234030ustar00rootroot00000000000000 mercadopago.resources API documentation

Module mercadopago.resources

Module: resources/init.py

Expand source code
"""
Module: resources/__init__.py
"""
from mercadopago.config.request_options import RequestOptions
from mercadopago.http.http_client import HttpClient
from mercadopago.resources.advanced_payment import AdvancedPayment
from mercadopago.resources.card import Card
from mercadopago.resources.card_token import CardToken
from mercadopago.resources.customer import Customer
from mercadopago.resources.disbursement_refund import DisbursementRefund
from mercadopago.resources.identification_type import IdentificationType
from mercadopago.resources.merchant_order import MerchantOrder
from mercadopago.resources.payment import Payment
from mercadopago.resources.payment_methods import PaymentMethods
from mercadopago.resources.preapproval import PreApproval
from mercadopago.resources.preference import Preference
from mercadopago.resources.refund import Refund
from mercadopago.resources.user import User


__all__ = (
    'AdvancedPayment',
    'Card',
    'CardToken',
    'Customer',
    'DisbursementRefund',
    'HttpClient',
    'IdentificationType',
    'MerchantOrder',
    'Payment',
    'PaymentMethods',
    'PreApproval',
    'Preference',
    'Refund',
    'RequestOptions',
    'User',
)

Sub-modules

mercadopago.resources.advanced_payment

Module: advanced_payment

mercadopago.resources.card

Module: card

mercadopago.resources.card_token

Module: card_token

mercadopago.resources.customer

Module: customer

mercadopago.resources.disbursement_refund

Module: disbursement_refund

mercadopago.resources.identification_type

Module: identification_type

mercadopago.resources.merchant_order

Module: merchant_order

mercadopago.resources.payment

Module: payment

mercadopago.resources.payment_methods

Module: payment_methods

mercadopago.resources.preapproval

Module: preapproval

mercadopago.resources.preference

Module: preference

mercadopago.resources.refund

Module: refund

mercadopago.resources.user

Module: user

Classes

class AdvancedPayment (request_options, http_client)

Access to Advanced Payments

Expand source code
class AdvancedPayment(MPBase):
    """
    Access to Advanced Payments
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments_id_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding custom options
            to ur REST call. Defaults to None.

        Returns:
            dict: Advanced Payment search response
        """
        return self._get(uri="/v1/advanced_payments/search", filters=filters,
                         request_options=request_options)

    def get(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment find response
        """
        return self._get(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         request_options=request_options)

    def create(self, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_object (dict): Advanced Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment creation response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._post(uri="/v1/advanced_payments", data=advanced_payment_object,
                          request_options=request_options)

    def capture(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            call. Defaults to None.

        Returns:
            dict: Advanced Payment capture response
        """
        capture_object = {"capture": True}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=capture_object, request_options=request_options)

    def update(self, advanced_payment_id, advanced_payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            advanced_payment_object (dict): Advanced Payment to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param advanced_payment_object must be a Dictionary

        Returns:
            dict: Advanced Payment modification response
        """
        if not isinstance(advanced_payment_object, dict):
            raise ValueError(
                "Param advanced_payment_object must be a Dictionary")

        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=advanced_payment_object, request_options=request_options)

    def cancel(self, advanced_payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Advanced Payment cancelation response
        """
        cancel_object = {"status": "cancelled"}
        return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                         data=cancel_object, request_options=request_options)

    def update_release_date(self, advanced_payment_id, release_date, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id_disbursements_disbursement_id_disburses/post/)  # pylint: disable=line-too-long

        Args:
            advanced_payment_id (str): The Advanced Payment ID
            release_date (datetime): Advanced Payment to be canceled
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param release_date must be a DateTime

        Returns:
            dict: Advanced Payment release date modification response
        """
        if not isinstance(release_date, datetime):
            raise ValueError("Param release_date must be a DateTime")

        disbursement_object = {
            "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")}

        return self._post(uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/disburses",
                          data=disbursement_object, request_options=request_options)

Ancestors

Methods

def cancel(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment cancelation response
Expand source code
def cancel(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Advanced Payment cancelation response
    """
    cancel_object = {"status": "cancelled"}
    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=cancel_object, request_options=request_options)
def capture(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment capture response
Expand source code
def capture(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Returns:
        dict: Advanced Payment capture response
    """
    capture_object = {"capture": True}
    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=capture_object, request_options=request_options)
def create(self, advanced_payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_object : dict
Advanced Payment to be created
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param advanced_payment_object must be a Dictionary

Returns

dict
Advanced Payment creation response
Expand source code
def create(self, advanced_payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments/post/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_object (dict): Advanced Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Raises:
        ValueError: Param advanced_payment_object must be a Dictionary

    Returns:
        dict: Advanced Payment creation response
    """
    if not isinstance(advanced_payment_object, dict):
        raise ValueError(
            "Param advanced_payment_object must be a Dictionary")

    return self._post(uri="/v1/advanced_payments", data=advanced_payment_object,
                      request_options=request_options)
def get(self, advanced_payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment find response
Expand source code
def get(self, advanced_payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/get/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance
        of RequestOptions can be pass changing or adding custom options to ur REST
        call. Defaults to None.

    Returns:
        dict: Advanced Payment find response
    """
    return self._get(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Advanced Payment search response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/advanced_payments/_advanced_payments_id_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding custom options
        to ur REST call. Defaults to None.

    Returns:
        dict: Advanced Payment search response
    """
    return self._get(uri="/v1/advanced_payments/search", filters=filters,
                     request_options=request_options)
def update(self, advanced_payment_id, advanced_payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
advanced_payment_object : dict
Advanced Payment to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param advanced_payment_object must be a Dictionary

Returns

dict
Advanced Payment modification response
Expand source code
def update(self, advanced_payment_id, advanced_payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        advanced_payment_object (dict): Advanced Payment to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param advanced_payment_object must be a Dictionary

    Returns:
        dict: Advanced Payment modification response
    """
    if not isinstance(advanced_payment_object, dict):
        raise ValueError(
            "Param advanced_payment_object must be a Dictionary")

    return self._put(uri="/v1/advanced_payments/" + str(advanced_payment_id),
                     data=advanced_payment_object, request_options=request_options)
def update_release_date(self, advanced_payment_id, release_date, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

advanced_payment_id : str
The Advanced Payment ID
release_date : datetime
Advanced Payment to be canceled
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param release_date must be a DateTime

Returns

dict
Advanced Payment release date modification response
Expand source code
def update_release_date(self, advanced_payment_id, release_date, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/advanced_payments/_advanced_payments_id_disbursements_disbursement_id_disburses/post/)  # pylint: disable=line-too-long

    Args:
        advanced_payment_id (str): The Advanced Payment ID
        release_date (datetime): Advanced Payment to be canceled
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param release_date must be a DateTime

    Returns:
        dict: Advanced Payment release date modification response
    """
    if not isinstance(release_date, datetime):
        raise ValueError("Param release_date must be a DateTime")

    disbursement_object = {
        "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")}

    return self._post(uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/disburses",
                      data=disbursement_object, request_options=request_options)

Inherited members

class Card (request_options, http_client)

The cards class is the way to store card data of your customers safely to improve the shopping experience.

This will allow your customers to complete their purchases much faster and easily, since they will not have to complete their card data again.

This class must be used in conjunction with the Customer class.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Card(MPBase):
    """
    The cards class is the way to store card data of your customers
    safely to improve the shopping experience.

    This will allow your customers to complete their purchases much
    faster and easily, since they will not have to complete their
    card data again.

    This class must be used in conjunction with the Customer class.

    [Click here for more info](https://www.mercadopago.com/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def list_all(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards",
            request_options=request_options,
        )

    def get(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_id (dict): Card ID to be found
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card find response
        """
        return self._get(
            uri=f"/v1/customers/{str(customer_id)}/cards/{str(card_id)}",
            request_options=request_options,
        )

    def create(self, customer_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/post/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            card_object (dict): Card object to be created
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card creation response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._post(uri="/v1/customers/" + str(customer_id)
                          + "/cards/", data=card_object, request_options=request_options)

    def update(self, customer_id, card_id, card_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be modified
            card_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param card_object must be a Dictionary

        Returns:
            dict: Card modification response
        """
        if not isinstance(card_object, dict):
            raise ValueError("Param card_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id)
                         + "/cards/" + str(card_id), data=card_object,
                         request_options=request_options)

    def delete(self, customer_id, card_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/delete/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): Customer ID owner
            card_id (str): Card ID to be deleted
            request_options (mercadopago.config.request_options, optional):
            An instance of RequestOptions can be pass changing or adding
            custom options to ur REST call. Defaults to None.

        Returns:
            dict: Card exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id)
                            + "/cards/" + str(card_id), request_options=request_options)

Ancestors

Methods

def create(self, customer_id, card_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
card_object : dict
Card object to be created

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_object must be a Dictionary

Returns

dict
Card creation response
Expand source code
def create(self, customer_id, card_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/post/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        card_object (dict): Card object to be created
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param card_object must be a Dictionary

    Returns:
        dict: Card creation response
    """
    if not isinstance(card_object, dict):
        raise ValueError("Param card_object must be a Dictionary")

    return self._post(uri="/v1/customers/" + str(customer_id)
                      + "/cards/", data=card_object, request_options=request_options)
def delete(self, customer_id, card_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
Customer ID owner
card_id : str
Card ID to be deleted

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card exclusion response
Expand source code
def delete(self, customer_id, card_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/delete/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): Customer ID owner
        card_id (str): Card ID to be deleted
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Card exclusion response
    """
    return self._delete(uri="/v1/customers/" + str(customer_id)
                        + "/cards/" + str(card_id), request_options=request_options)
def get(self, customer_id, card_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
card_id : dict
Card ID to be found

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card find response
Expand source code
def get(self, customer_id, card_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        card_id (dict): Card ID to be found
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Card find response
    """
    return self._get(
        uri=f"/v1/customers/{str(customer_id)}/cards/{str(card_id)}",
        request_options=request_options,
    )
def list_all(self, customer_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Cards find response
Expand source code
def list_all(self, customer_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Returns:
        dict: Cards find response
    """
    return self._get(
        uri=f"/v1/customers/{str(customer_id)}/cards",
        request_options=request_options,
    )
def update(self, customer_id, card_id, card_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
Customer ID owner
card_id : str
Card ID to be modified
card_object : dict
Values to be modified

request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_object must be a Dictionary

Returns

dict
Card modification response
Expand source code
def update(self, customer_id, card_id, card_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards_id/put/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): Customer ID owner
        card_id (str): Card ID to be modified
        card_object (dict): Values to be modified
        request_options (mercadopago.config.request_options, optional):
        An instance of RequestOptions can be pass changing or adding
        custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param card_object must be a Dictionary

    Returns:
        dict: Card modification response
    """
    if not isinstance(card_object, dict):
        raise ValueError("Param card_object must be a Dictionary")

    return self._put(uri="/v1/customers/" + str(customer_id)
                     + "/cards/" + str(card_id), data=card_object,
                     request_options=request_options)

Inherited members

class CardToken (request_options, http_client)

This class will allow you to send your customers card data for Mercado Pago server and receive a token to complete the payments transactions.

Expand source code
class CardToken(MPBase):
    """
    This class will allow you to send your customers card data for Mercado Pago
    server and receive a token to complete the payments transactions.
    """

    def get(self, card_token_id, request_options=None):
        """Args:
            card_token_id (str): The Card Token ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Card Token find response
        """
        return self._get(uri="/v1/card_tokens/" + str(card_token_id),
                         request_options=request_options)

    def create(self, card_token_object, request_options=None):
        """Args:
            card_token_object (dict): Card Token to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param card_token_object must be a Dictionary

        Returns:
            dict: Card Token creation response
        """
        if not isinstance(card_token_object, dict):
            raise ValueError("Param card_token_object must be a Dictionary")

        return self._post(uri="/v1/card_tokens", data=card_token_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, card_token_object, request_options=None)

Args

card_token_object : dict
Card Token to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param card_token_object must be a Dictionary

Returns

dict
Card Token creation response
Expand source code
def create(self, card_token_object, request_options=None):
    """Args:
        card_token_object (dict): Card Token to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param card_token_object must be a Dictionary

    Returns:
        dict: Card Token creation response
    """
    if not isinstance(card_token_object, dict):
        raise ValueError("Param card_token_object must be a Dictionary")

    return self._post(uri="/v1/card_tokens", data=card_token_object,
                      request_options=request_options)
def get(self, card_token_id, request_options=None)

Args

card_token_id : str
The Card Token ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Card Token find response
Expand source code
def get(self, card_token_id, request_options=None):
    """Args:
        card_token_id (str): The Card Token ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Card Token find response
    """
    return self._get(uri="/v1/card_tokens/" + str(card_token_id),
                     request_options=request_options)

Inherited members

class Customer (request_options, http_client)

This class allows you to store customers data safely to improve the shopping experience.

This will allow your customer to complete their purchases much faster and easily when used in conjunction with the Cards class.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Customer(MPBase):
    """
    This class allows you to store customers data safely to improve the shopping experience.

    This will allow your customer to complete their purchases much faster and easily when
    used in conjunction with the Cards class.

    [Click here for more info](https://mercadopago.com.br/developers/en/guides/online-payments/web-tokenize-checkout/customers-and-cards)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/search", filters=filters,
                         request_options=request_options)

    def get(self, customer_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer find response
        """
        return self._get(uri="/v1/customers/" + str(customer_id), request_options=request_options)

    def create(self, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers/post/)  # pylint: disable=line-too-long

        Args:
            customer_object (dict): Customer object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer creation response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._post(uri="/v1/customers", data=customer_object,
                          request_options=request_options)

    def update(self, customer_id, customer_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_id/put/)  # pylint: disable=line-too-long

        Args:
            customer_id (str): The Customer ID owner
            customer_object (dict): Customer object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValeuError: Param customer_object must be a Dictionary

        Returns:
            dict: Customer modification response
        """
        if not isinstance(customer_object, dict):
            raise ValueError("Param customer_object must be a Dictionary")

        return self._put(uri="/v1/customers/" + str(customer_id), data=customer_object,
                         request_options=request_options)

    def delete(self, customer_id, request_options=None):
        """
        Args:
            customer_id (str): The Customer ID owner
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Customer exclusion response
        """
        return self._delete(uri="/v1/customers/" + str(customer_id),
                            request_options=request_options)

Ancestors

Methods

def create(self, customer_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_object : dict
Customer object to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param customer_object must be a Dictionary

Returns

dict
Customer creation response
Expand source code
def create(self, customer_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers/post/)  # pylint: disable=line-too-long

    Args:
        customer_object (dict): Customer object to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param customer_object must be a Dictionary

    Returns:
        dict: Customer creation response
    """
    if not isinstance(customer_object, dict):
        raise ValueError("Param customer_object must be a Dictionary")

    return self._post(uri="/v1/customers", data=customer_object,
                      request_options=request_options)
def delete(self, customer_id, request_options=None)

Args

customer_id : str
The Customer ID owner
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer exclusion response
Expand source code
def delete(self, customer_id, request_options=None):
    """
    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer exclusion response
    """
    return self._delete(uri="/v1/customers/" + str(customer_id),
                        request_options=request_options)
def get(self, customer_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer find response
Expand source code
def get(self, customer_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/customers/_customers_id/get/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer find response
    """
    return self._get(uri="/v1/customers/" + str(customer_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Customer find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Customer find response
    """
    return self._get(uri="/v1/customers/search", filters=filters,
                     request_options=request_options)
def update(self, customer_id, customer_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

customer_id : str
The Customer ID owner
customer_object : dict
Customer object to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValeuError
Param customer_object must be a Dictionary

Returns

dict
Customer modification response
Expand source code
def update(self, customer_id, customer_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/customers/_customers_id/put/)  # pylint: disable=line-too-long

    Args:
        customer_id (str): The Customer ID owner
        customer_object (dict): Customer object to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValeuError: Param customer_object must be a Dictionary

    Returns:
        dict: Customer modification response
    """
    if not isinstance(customer_object, dict):
        raise ValueError("Param customer_object must be a Dictionary")

    return self._put(uri="/v1/customers/" + str(customer_id), data=customer_object,
                     request_options=request_options)

Inherited members

class DisbursementRefund (request_options, http_client)

Access to Advanced Payments Refunds

Expand source code
class DisbursementRefund(MPBase):

    """
    Access to Advanced Payments Refunds
    """

    def list_all(self, advanced_payment_id, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Disbursement Refund find response
        """
        uri = f"/v1/advanced_payments/{str(advanced_payment_id)}/refunds"
        return self._get(uri=uri, request_options=request_options)

    def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_refund_object (dict): Disbursement Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund creation all response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        return self._post(
            uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/refunds",
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def create(self, advanced_payment_id, disbursement_id, amount, request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            amount: Amount to be refunded
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param amount must be a Float

        Returns:
            dict: Disbursement Refund creation response
        """
        if not isinstance(amount, float):
            raise ValueError("Param amount must be a Float")

        disbursement_refund_object = {"amount": amount}

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

    def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object,
             request_options=None):
        """[Args:
            advanced_payment_id (str): The Advanced Payment ID
            disbursement_id (str): Disbursement ID
            disbursement_refund_object (dict): Disbursement Refund to be saved
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
        ValueError: Param disbursement_refund_object must be a Dictionary

        Returns:
            dict: Disbursement Refund save response
        """
        if not isinstance(disbursement_refund_object, dict):
            raise ValueError(
                "Param disbursement_refund_object must be a Dictionary")

        uri = (
            f"/v1/advanced_payments/{str(advanced_payment_id)}"
            f"/disbursements/{str(disbursement_id)}/refunds"
        )

        return self._post(
            uri=uri,
            data=disbursement_refund_object,
            request_options=request_options,
        )

Ancestors

Methods

def create(self, advanced_payment_id, disbursement_id, amount, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_id (str): Disbursement ID amount: Amount to be refunded request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param amount must be a Float

Returns

dict
Disbursement Refund creation response
Expand source code
def create(self, advanced_payment_id, disbursement_id, amount, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_id (str): Disbursement ID
        amount: Amount to be refunded
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param amount must be a Float

    Returns:
        dict: Disbursement Refund creation response
    """
    if not isinstance(amount, float):
        raise ValueError("Param amount must be a Float")

    disbursement_refund_object = {"amount": amount}

    uri = (
        f"/v1/advanced_payments/{str(advanced_payment_id)}"
        f"/disbursements/{str(disbursement_id)}/refunds"
    )

    return self._post(
        uri=uri,
        data=disbursement_refund_object,
        request_options=request_options,
    )
def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_refund_object (dict): Disbursement Refund to be created request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param disbursement_refund_object must be a Dictionary

Returns

dict
Disbursement Refund creation all response
Expand source code
def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_refund_object (dict): Disbursement Refund to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param disbursement_refund_object must be a Dictionary

    Returns:
        dict: Disbursement Refund creation all response
    """
    if not isinstance(disbursement_refund_object, dict):
        raise ValueError(
            "Param disbursement_refund_object must be a Dictionary")

    return self._post(
        uri="/v1/advanced_payments/" + str(advanced_payment_id) + "/refunds",
        data=disbursement_refund_object,
        request_options=request_options,
    )
def list_all(self, advanced_payment_id, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Disbursement Refund find response
Expand source code
def list_all(self, advanced_payment_id, request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Disbursement Refund find response
    """
    uri = f"/v1/advanced_payments/{str(advanced_payment_id)}/refunds"
    return self._get(uri=uri, request_options=request_options)
def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object, request_options=None)

[Args: advanced_payment_id (str): The Advanced Payment ID disbursement_id (str): Disbursement ID disbursement_refund_object (dict): Disbursement Refund to be saved request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises: ValueError: Param disbursement_refund_object must be a Dictionary

Returns

dict
Disbursement Refund save response
Expand source code
def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object,
         request_options=None):
    """[Args:
        advanced_payment_id (str): The Advanced Payment ID
        disbursement_id (str): Disbursement ID
        disbursement_refund_object (dict): Disbursement Refund to be saved
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
    ValueError: Param disbursement_refund_object must be a Dictionary

    Returns:
        dict: Disbursement Refund save response
    """
    if not isinstance(disbursement_refund_object, dict):
        raise ValueError(
            "Param disbursement_refund_object must be a Dictionary")

    uri = (
        f"/v1/advanced_payments/{str(advanced_payment_id)}"
        f"/disbursements/{str(disbursement_id)}/refunds"
    )

    return self._post(
        uri=uri,
        data=disbursement_refund_object,
        request_options=request_options,
    )

Inherited members

class HttpClient

Default implementation to call all REST API's

Expand source code
class HttpClient:
    """
    Default implementation to call all REST API's
    """

    def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
        """Makes a call to the API.

        All **kwargs are passed verbatim to ``requests.request``.
        """
        retry_strategy = Retry(
            total=maxretries,
            status_forcelist=[429, 500, 502, 503, 504]
        )
        http = requests.Session()
        http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
        with http as session:
            api_result = session.request(method, url, **kwargs)
            response = {
                "status": api_result.status_code,
                "response": api_result.json()
            }

        return response

    def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a GET request to the API"""
        return self.request(
            "GET",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a POST request to the API"""
        return self.request(
            "POST",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a PUT request to the API"""
        return self.request(
            "PUT",
            url=url,
            headers=headers,
            data=data,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

    def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
        """Makes a DELETE request to the API"""
        return self.request(
            "DELETE",
            url=url,
            headers=headers,
            params=params,
            timeout=timeout,
            maxretries=maxretries,
        )

Methods

def delete(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a DELETE request to the API

Expand source code
def delete(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a DELETE request to the API"""
    return self.request(
        "DELETE",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def get(self, url, headers, params=None, timeout=None, maxretries=None)

Makes a GET request to the API

Expand source code
def get(self, url, headers, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a GET request to the API"""
    return self.request(
        "GET",
        url=url,
        headers=headers,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a POST request to the API

Expand source code
def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a POST request to the API"""
    return self.request(
        "POST",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None)

Makes a PUT request to the API

Expand source code
def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None):  # pylint: disable=too-many-arguments
    """Makes a PUT request to the API"""
    return self.request(
        "PUT",
        url=url,
        headers=headers,
        data=data,
        params=params,
        timeout=timeout,
        maxretries=maxretries,
    )
def request(self, method, url, maxretries=None, **kwargs)

Makes a call to the API.

All **kwargs are passed verbatim to requests.request.

Expand source code
def request(self, method, url, maxretries=None, **kwargs):  # pylint: disable=no-self-use
    """Makes a call to the API.

    All **kwargs are passed verbatim to ``requests.request``.
    """
    retry_strategy = Retry(
        total=maxretries,
        status_forcelist=[429, 500, 502, 503, 504]
    )
    http = requests.Session()
    http.mount("https://", HTTPAdapter(max_retries=retry_strategy))
    with http as session:
        api_result = session.request(method, url, **kwargs)
        response = {
            "status": api_result.status_code,
            "response": api_result.json()
        }

    return response
class IdentificationType (request_options, http_client)

Access to Identification Types

Expand source code
class IdentificationType(MPBase):
    """
    Access to Identification Types
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/identification_types/_identification_types/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Identification Types find response
        """
        return self._get(uri="/v1/identification_types", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def list_all(self, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Identification Types find response
Expand source code
def list_all(self, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/identification_types/_identification_types/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Identification Types find response
    """
    return self._get(uri="/v1/identification_types", request_options=request_options)

Inherited members

class MerchantOrder (request_options, http_client)

This class will allow you to create and manage your orders. You can attach one or more payments in your merchant order.

Expand source code
class MerchantOrder(MPBase):
    """
    This class will allow you to create and manage your orders. You can attach
    one or more payments in your merchant order.
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Merchant Order find response
        """
        return self._get(uri="/merchant_orders/search", filters=filters,
                         request_options=request_options)

    def get(self, merchan_order_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): The Merchant Order ID
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(uri="/merchant_orders/" + str(merchan_order_id),
                         request_options=request_options)

    def update(self, merchan_order_id, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_id/put/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): Merchant Order ID
            merchant_order_object (dict): Merchant Order object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards modification response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._put(uri="/merchant_orders/" + str(merchan_order_id),
                         data=merchant_order_object, request_options=request_options)

    def create(self, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders/post/)  # pylint: disable=line-too-long

        Args:
            merchant_order_object (dict): Merchant Order object to be created
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass
                changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards creation response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._post(uri="/merchant_orders", data=merchant_order_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, merchant_order_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchant_order_object : dict
Merchant Order object to be created
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param merchant_order_object must be a Dictionary

Returns

dict
Cards creation response
Expand source code
def create(self, merchant_order_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders/post/)  # pylint: disable=line-too-long

    Args:
        merchant_order_object (dict): Merchant Order object to be created
        request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass
            changing or adding custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param merchant_order_object must be a Dictionary

    Returns:
        dict: Cards creation response
    """
    if not isinstance(merchant_order_object, dict):
        raise ValueError(
            "Param merchant_order_object must be a Dictionary")

    return self._post(uri="/merchant_orders", data=merchant_order_object,
                      request_options=request_options)
def get(self, merchan_order_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchan_order_id : str
The Merchant Order ID
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Cards find response
Expand source code
def get(self, merchan_order_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

    Args:
        merchan_order_id (str): The Merchant Order ID
        request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

    Returns:
        dict: Cards find response
    """
    return self._get(uri="/merchant_orders/" + str(merchan_order_id),
                     request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Merchant Order find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Merchant Order find response
    """
    return self._get(uri="/merchant_orders/search", filters=filters,
                     request_options=request_options)
def update(self, merchan_order_id, merchant_order_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchan_order_id : str
Merchant Order ID
merchant_order_object : dict
Merchant Order object to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param merchant_order_object must be a Dictionary

Returns

dict
Cards modification response
Expand source code
def update(self, merchan_order_id, merchant_order_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_id/put/)  # pylint: disable=line-too-long

    Args:
        merchan_order_id (str): Merchant Order ID
        merchant_order_object (dict): Merchant Order object to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param merchant_order_object must be a Dictionary

    Returns:
        dict: Cards modification response
    """
    if not isinstance(merchant_order_object, dict):
        raise ValueError(
            "Param merchant_order_object must be a Dictionary")

    return self._put(uri="/merchant_orders/" + str(merchan_order_id),
                     data=merchant_order_object, request_options=request_options)

Inherited members

class Payment (request_options, http_client)

This class provides the methods to access the API that will allow you to create your own payment experience on your website.

From basic to advanced configurations, you control the whole experience.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Payment(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own payment experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-api/introduction/)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_search/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/search", filters=filters,
                         request_options=request_options)

    def get(self, payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/" + str(payment_id), request_options=request_options)

    def create(self, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments/post/)  # pylint: disable=line-too-long

        Args:
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment creation response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._post(uri="/v1/payments", data=payment_object, request_options=request_options)

    def update(self, payment_id, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/payments/_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment modification response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._put(uri="/v1/payments/" + str(payment_id), data=payment_object,
                         request_options=request_options)

Ancestors

Methods

def create(self, payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_object : dict
Payment to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param payment_object must be a Dictionary

Returns

dict
Payment creation response
Expand source code
def create(self, payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments/post/)  # pylint: disable=line-too-long

    Args:
        payment_object (dict): Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param payment_object must be a Dictionary

    Returns:
        dict: Payment creation response
    """
    if not isinstance(payment_object, dict):
        raise ValueError("Param payment_object must be a Dictionary")

    return self._post(uri="/v1/payments", data=payment_object, request_options=request_options)
def get(self, payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_id : str
The Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment find response
Expand source code
def get(self, payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_id/get/)  # pylint: disable=line-too-long

    Args:
        payment_id (str): The Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment find response
    """
    return self._get(uri="/v1/payments/" + str(payment_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_search/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment find response
    """
    return self._get(uri="/v1/payments/search", filters=filters,
                     request_options=request_options)
def update(self, payment_id, payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_id : str
The Payment ID
payment_object : dict
Payment to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param payment_object must be a Dictionary

Returns

dict
Payment modification response
Expand source code
def update(self, payment_id, payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/payments/_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        payment_id (str): The Payment ID
        payment_object (dict): Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param payment_object must be a Dictionary

    Returns:
        dict: Payment modification response
    """
    if not isinstance(payment_object, dict):
        raise ValueError("Param payment_object must be a Dictionary")

    return self._put(uri="/v1/payments/" + str(payment_id), data=payment_object,
                     request_options=request_options)

Inherited members

class PaymentMethods (request_options, http_client)

Access to Payment Methods

Expand source code
class PaymentMethods(MPBase):
    """
    Access to Payment Methods
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payment_methods/_payment_methods/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment Methods find response
        """
        return self._get(uri="/v1/payment_methods", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def list_all(self, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment Methods find response
Expand source code
def list_all(self, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payment_methods/_payment_methods/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment Methods find response
    """
    return self._get(uri="/v1/payment_methods", request_options=request_options)

Inherited members

class PreApproval (request_options, http_client)

This class provides the methods to access the API that will allow you to create your own preapproval experience on your website.

From basic to advanced configurations, you control the whole experience.

Click here for more info # pylint: disable=line-too-long

Expand source code
class PreApproval(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own preapproval experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/subscriptions/introduction)  # pylint: disable=line-too-long
    """

    def __init__(self, request_options, http_client):
        MPBase.__init__(self, request_options, http_client)

    def search(self, filters=None, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/search", filters=filters,
                         request_options=request_options)

    def get(self, preapproval_id, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/" + str(preapproval_id), request_options=request_options)

    def create(self, preapproval_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/)  # pylint: disable=line-too-long

        Args:
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval creation response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._post(uri="/preapproval",
                          data=preapproval_object, request_options=request_options)

    def update(self, preapproval_id, preapproval_object, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval modification response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._put(uri="/preapproval" + str(preapproval_id),
                         data=preapproval_object, request_options=request_options)

Ancestors

Methods

def create(self, preapproval_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preapproval_object : dict
PreApproval to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preapproval_object must be a Dictionary

Returns

dict
PreApproval creation response
Expand source code
def create(self, preapproval_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/)  # pylint: disable=line-too-long

    Args:
        preapproval_object (dict): PreApproval to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preapproval_object must be a Dictionary

    Returns:
        dict: PreApproval creation response
    """
    if not isinstance(preapproval_object, dict):
        raise ValueError("Param preapproval_object must be a Dictionary")

    return self._post(uri="/preapproval",
                      data=preapproval_object, request_options=request_options)
def get(self, preapproval_id, request_options=None)

Args

preapproval_id : str
The PreApproval ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
PreApproval find response
Expand source code
def get(self, preapproval_id, request_options=None):
    """Args:
        preapproval_id (str): The PreApproval ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: PreApproval find response
    """
    return self._get(uri="/preapproval/" + str(preapproval_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
PreApproval find response
Expand source code
def search(self, filters=None, request_options=None):
    """Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: PreApproval find response
    """
    return self._get(uri="/preapproval/search", filters=filters,
                     request_options=request_options)
def update(self, preapproval_id, preapproval_object, request_options=None)

Args

preapproval_id : str
The PreApproval ID
preapproval_object : dict
PreApproval to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preapproval_object must be a Dictionary

Returns

dict
PreApproval modification response
Expand source code
def update(self, preapproval_id, preapproval_object, request_options=None):
    """Args:
        preapproval_id (str): The PreApproval ID
        preapproval_object (dict): PreApproval to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preapproval_object must be a Dictionary

    Returns:
        dict: PreApproval modification response
    """
    if not isinstance(preapproval_object, dict):
        raise ValueError("Param preapproval_object must be a Dictionary")

    return self._put(uri="/preapproval" + str(preapproval_id),
                     data=preapproval_object, request_options=request_options)

Inherited members

class Preference (request_options, http_client)

This class will allow you to charge your customers through our web form from any device in a simple, fast and secure way.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Preference(MPBase):
    """
    This class will allow you to charge your customers through our web form
    from any device in a simple, fast and secure way.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-pro/introduction)  # pylint: disable=line-too-long
    """

    def get(self, preference_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Preference find response
        """
        return self._get(uri="/checkout/preferences/" + str(preference_id),
                         request_options=request_options)

    def update(self, preference_id, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/put/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            preference_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference modification response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._put(uri="/checkout/preferences/" + str(preference_id), data=preference_object,
                         request_options=request_options)

    def create(self, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences/post/) # pylint: disable=line-too-long

        Args:
            preference_object (dict): Preference object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
                RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference creation response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._post(uri="/checkout/preferences", data=preference_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, preference_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_object : dict
Preference object to be created
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preference_object must be a Dictionary

Returns

dict
Preference creation response
Expand source code
def create(self, preference_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences/post/) # pylint: disable=line-too-long

    Args:
        preference_object (dict): Preference object to be created
        request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param preference_object must be a Dictionary

    Returns:
        dict: Preference creation response
    """
    if not isinstance(preference_object, dict):
        raise ValueError("Param preference_object must be a Dictionary")

    return self._post(uri="/checkout/preferences", data=preference_object,
                      request_options=request_options)
def get(self, preference_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_id : str
The Preference ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Preference find response
Expand source code
def get(self, preference_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/)  # pylint: disable=line-too-long

    Args:
        preference_id (str): The Preference ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Preference find response
    """
    return self._get(uri="/checkout/preferences/" + str(preference_id),
                     request_options=request_options)
def update(self, preference_id, preference_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_id : str
The Preference ID
preference_object : dict
Values to be modified
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preference_object must be a Dictionary

Returns

dict
Preference modification response
Expand source code
def update(self, preference_id, preference_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/put/)  # pylint: disable=line-too-long

    Args:
        preference_id (str): The Preference ID
        preference_object (dict): Values to be modified
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preference_object must be a Dictionary

    Returns:
        dict: Preference modification response
    """
    if not isinstance(preference_object, dict):
        raise ValueError("Param preference_object must be a Dictionary")

    return self._put(uri="/checkout/preferences/" + str(preference_id), data=preference_object,
                     request_options=request_options)

Inherited members

class Refund (request_options, http_client)

This class will allow you to refund payments created through the Payments class.

You can refund a payment within 180 days after it was approved.

You must have sufficient funds in your account in order to successfully refund the payment amount. Otherwise, you will get a 400 Bad Request error.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Refund(MPBase):
    """
    This class will allow you to refund payments created through the Payments class.

    You can refund a payment within 180 days after it was approved.

    You must have sufficient funds in your account in order to successfully refund
    the payment amount. Otherwise, you will get a 400 Bad Request error.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/manage-account/account/cancellations-and-refunds#bookmark_refunds)  # pylint: disable=line-too-long
    """

    def list_all(self, payment_id, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: List all refunds of a payment
        """
        return self._get(uri="/v1/payments/" + str(payment_id) + "/refunds",
                         request_options=request_options)

    def create(self, payment_id, refund_object=None, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            refund_object (dict): Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param refund_object must be a Dictionary

        Returns:
            dict: Refund creation response
        """
        if refund_object is not None and not isinstance(refund_object, dict):
            raise ValueError("Param refund_object must be a Dictionary")

        return self._post(uri="/v1/payments/" + str(payment_id) + "/refunds",
                          data=refund_object, request_options=request_options)

Ancestors

Methods

def create(self, payment_id, refund_object=None, request_options=None)

Args

payment_id : str
The Payment ID
refund_object : dict
Refund to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param refund_object must be a Dictionary

Returns

dict
Refund creation response
Expand source code
def create(self, payment_id, refund_object=None, request_options=None):
    """Args:
        payment_id (str): The Payment ID
        refund_object (dict): Refund to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param refund_object must be a Dictionary

    Returns:
        dict: Refund creation response
    """
    if refund_object is not None and not isinstance(refund_object, dict):
        raise ValueError("Param refund_object must be a Dictionary")

    return self._post(uri="/v1/payments/" + str(payment_id) + "/refunds",
                      data=refund_object, request_options=request_options)
def list_all(self, payment_id, request_options=None)

Args

payment_id : str
The Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
List all refunds of a payment
Expand source code
def list_all(self, payment_id, request_options=None):
    """Args:
        payment_id (str): The Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: List all refunds of a payment
    """
    return self._get(uri="/v1/payments/" + str(payment_id) + "/refunds",
                     request_options=request_options)

Inherited members

class RequestOptions (access_token=None, connection_timeout=60.0, custom_headers=None, corporation_id=None, integrator_id=None, platform_id=None, max_retries=3)

This object hold all configurations that will be used in ur REST call.

All here u can customize as well add params in the requisition header (custom_headers)

Initialize

Args

access_token : str, optional
Your User Access Token. Defaults to None.
connection_timeout : float, optional
Time to timeout the REST call. Defaults to 60.0.
custom_headers : dict, optional
A Dict with params to be added to the requests params.
Defaults to None.
corporation_id : str, optional
Your Corporation ID if any. Defaults to None.
integrator_id : str, optional
Your Integrator ID if any. Defaults to None.
platform_id : str, optional
Your Platform ID if any. Defaults to None.
max_retries : int, optional
How many retries must be done in case of fail.

Defaults to 3.

Raises

ValueError
Param access_token must be a String
ValueError
Param connection_timeout must be a Float
ValueError
Param custom_headers must be a Dictionary
ValueError
Param corporation_id must be a String
ValueError
Param integrator_id must be a String
ValueError
Param platform_id must be a String
ValueError
Param max_retries must be an Integer
Expand source code
class RequestOptions:  # pylint: disable=too-many-instance-attributes

    """This object hold all configurations that will be used in ur REST call.

    All here u can customize as well add params in the requisition header (custom_headers)
    """

    __access_token = None
    __connection_timeout = None
    __custom_headers = None
    __max_retries = None
    __corporation_id = None
    __integrator_id = None
    __platform_id = None

    def __init__(  # pylint: disable=too-many-arguments
        self,
        access_token=None,
        connection_timeout=60.0,
        custom_headers=None,
        corporation_id=None,
        integrator_id=None,
        platform_id=None,
        max_retries=3,
    ):
        """Initialize

        Args:
            access_token (str, optional): Your User Access Token. Defaults to None.
            connection_timeout (float, optional): Time to timeout the REST call. Defaults to 60.0.
            custom_headers (dict, optional): A Dict with params to be added to the requests params.
            Defaults to None.
            corporation_id (str, optional): Your Corporation ID if any. Defaults to None.
            integrator_id (str, optional): Your Integrator ID if any. Defaults to None.
            platform_id (str, optional): Your Platform ID if any. Defaults to None.
            max_retries (int, optional): How many retries must be done in case of fail.
            Defaults to 3.

        Raises:
            ValueError: Param access_token must be a String
            ValueError: Param connection_timeout must be a Float
            ValueError: Param custom_headers must be a Dictionary
            ValueError: Param corporation_id must be a String
            ValueError: Param integrator_id must be a String
            ValueError: Param platform_id must be a String
            ValueError: Param max_retries must be an Integer
        """

        if access_token is not None:
            self.access_token = access_token
        if connection_timeout is not None:
            self.connection_timeout = connection_timeout
        if custom_headers is not None:
            self.custom_headers = custom_headers
        if max_retries is not None:
            self.max_retries = max_retries
        if corporation_id is not None:
            self.corporation_id = corporation_id
        if integrator_id is not None:
            self.integrator_id = integrator_id
        if platform_id is not None:
            self.platform_id = platform_id

        self.__config = Config()

    def get_headers(self):
        """
        Sets the attribute values of headers
        """
        headers = {"Authorization": "Bearer " + self.__access_token,
                   "x-product-id": self.__config.product_id,
                   "x-tracking-id": self.__config.tracking_id,
                   "x-idempotency-key": str(uuid.uuid4().int),
                   "User-Agent": self.__config.user_agent,
                   "Accept": self.__config.mime_json}

        if self.__corporation_id is not None:
            headers["x-corporation-id"] = self.__corporation_id

        if self.__integrator_id is not None:
            headers["x-integrator-id"] = self.__integrator_id

        if self.__platform_id is not None:
            headers["x-platform-id"] = self.__platform_id

        if self.__custom_headers is not None:
            headers.update(self.__custom_headers)

        return headers

    @property
    def access_token(self):
        """
        Sets the attribute value and validates access_token
        """
        return self.__access_token

    @access_token.setter
    def access_token(self, value):
        if not isinstance(value, str):
            raise ValueError("Param access_token must be a String")
        self.__access_token = value

    @property
    def connection_timeout(self):
        """
        Sets the attribute value and validates connection timeout
        """
        return self.__connection_timeout

    @connection_timeout.setter
    def connection_timeout(self, value):
        if not isinstance(value, float):
            raise ValueError("Param connection_timeout must be a Float")
        self.__connection_timeout = value

    @property
    def corporation_id(self):
        """
        Sets the attribute value and validates corporation id
        """
        return self.__corporation_id

    @corporation_id.setter
    def corporation_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param corporation_id must be a String")
        self.__corporation_id = value

    @property
    def custom_headers(self):
        """
        Sets the attribute value and validates custom headers
        """
        return self.__custom_headers

    @custom_headers.setter
    def custom_headers(self, value):
        if not isinstance(value, dict):
            raise ValueError("Param custom_headers must be a Dictionary")
        self.__custom_headers = value

    @property
    def integrator_id(self):
        """
        Sets the attribute value and validates integrator id
        """
        return self.__integrator_id

    @integrator_id.setter
    def integrator_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param integrator_id must be a String")
        self.__integrator_id = value

    @property
    def max_retries(self):
        """
        Sets the attribute value and validates max retries
        """
        return self.__max_retries

    @max_retries.setter
    def max_retries(self, value):
        if not isinstance(value, int):
            raise ValueError("Param max_retries must be an Integer")
        self.__max_retries = value

    @property
    def platform_id(self):
        """
        Sets the attribute value and validates platform id
        """
        return self.__platform_id

    @platform_id.setter
    def platform_id(self, value):
        if not isinstance(value, str):
            raise ValueError("Param platform_id must be a String")
        self.__platform_id = value

Instance variables

var access_token

Sets the attribute value and validates access_token

Expand source code
@property
def access_token(self):
    """
    Sets the attribute value and validates access_token
    """
    return self.__access_token
var connection_timeout

Sets the attribute value and validates connection timeout

Expand source code
@property
def connection_timeout(self):
    """
    Sets the attribute value and validates connection timeout
    """
    return self.__connection_timeout
var corporation_id

Sets the attribute value and validates corporation id

Expand source code
@property
def corporation_id(self):
    """
    Sets the attribute value and validates corporation id
    """
    return self.__corporation_id
var custom_headers

Sets the attribute value and validates custom headers

Expand source code
@property
def custom_headers(self):
    """
    Sets the attribute value and validates custom headers
    """
    return self.__custom_headers
var integrator_id

Sets the attribute value and validates integrator id

Expand source code
@property
def integrator_id(self):
    """
    Sets the attribute value and validates integrator id
    """
    return self.__integrator_id
var max_retries

Sets the attribute value and validates max retries

Expand source code
@property
def max_retries(self):
    """
    Sets the attribute value and validates max retries
    """
    return self.__max_retries
var platform_id

Sets the attribute value and validates platform id

Expand source code
@property
def platform_id(self):
    """
    Sets the attribute value and validates platform id
    """
    return self.__platform_id

Methods

def get_headers(self)

Sets the attribute values of headers

Expand source code
def get_headers(self):
    """
    Sets the attribute values of headers
    """
    headers = {"Authorization": "Bearer " + self.__access_token,
               "x-product-id": self.__config.product_id,
               "x-tracking-id": self.__config.tracking_id,
               "x-idempotency-key": str(uuid.uuid4().int),
               "User-Agent": self.__config.user_agent,
               "Accept": self.__config.mime_json}

    if self.__corporation_id is not None:
        headers["x-corporation-id"] = self.__corporation_id

    if self.__integrator_id is not None:
        headers["x-integrator-id"] = self.__integrator_id

    if self.__platform_id is not None:
        headers["x-platform-id"] = self.__platform_id

    if self.__custom_headers is not None:
        headers.update(self.__custom_headers)

    return headers
class User (request_options, http_client)

Access to Users

Expand source code
class User(MPBase):
    """
    Access to Users
    """

    def get(self, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: User find response
        """
        return self._get(uri="/users/me", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def get(self, request_options=None)

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
User find response
Expand source code
def get(self, request_options=None):
    """Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: User find response
    """
    return self._get(uri="/users/me", request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/merchant_order.html000066400000000000000000000602011524412155200252540ustar00rootroot00000000000000 mercadopago.resources.merchant_order API documentation

Module mercadopago.resources.merchant_order

Module: merchant_order

Expand source code
"""
    Module: merchant_order
"""
from mercadopago.core import MPBase


class MerchantOrder(MPBase):
    """
    This class will allow you to create and manage your orders. You can attach
    one or more payments in your merchant order.
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Merchant Order find response
        """
        return self._get(uri="/merchant_orders/search", filters=filters,
                         request_options=request_options)

    def get(self, merchan_order_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): The Merchant Order ID
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(uri="/merchant_orders/" + str(merchan_order_id),
                         request_options=request_options)

    def update(self, merchan_order_id, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_id/put/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): Merchant Order ID
            merchant_order_object (dict): Merchant Order object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards modification response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._put(uri="/merchant_orders/" + str(merchan_order_id),
                         data=merchant_order_object, request_options=request_options)

    def create(self, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders/post/)  # pylint: disable=line-too-long

        Args:
            merchant_order_object (dict): Merchant Order object to be created
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass
                changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards creation response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._post(uri="/merchant_orders", data=merchant_order_object,
                          request_options=request_options)

Classes

class MerchantOrder (request_options, http_client)

This class will allow you to create and manage your orders. You can attach one or more payments in your merchant order.

Expand source code
class MerchantOrder(MPBase):
    """
    This class will allow you to create and manage your orders. You can attach
    one or more payments in your merchant order.
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_search/get/)  # pylint: disable=line-too-long

        Args:
            filters (dict): The search filters parameters
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Merchant Order find response
        """
        return self._get(uri="/merchant_orders/search", filters=filters,
                         request_options=request_options)

    def get(self, merchan_order_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): The Merchant Order ID
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Returns:
            dict: Cards find response
        """
        return self._get(uri="/merchant_orders/" + str(merchan_order_id),
                         request_options=request_options)

    def update(self, merchan_order_id, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_id/put/)  # pylint: disable=line-too-long

        Args:
            merchan_order_id (str): Merchant Order ID
            merchant_order_object (dict): Merchant Order object to be updated
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards modification response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._put(uri="/merchant_orders/" + str(merchan_order_id),
                         data=merchant_order_object, request_options=request_options)

    def create(self, merchant_order_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders/post/)  # pylint: disable=line-too-long

        Args:
            merchant_order_object (dict): Merchant Order object to be created
            request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass
                changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param merchant_order_object must be a Dictionary

        Returns:
            dict: Cards creation response
        """
        if not isinstance(merchant_order_object, dict):
            raise ValueError(
                "Param merchant_order_object must be a Dictionary")

        return self._post(uri="/merchant_orders", data=merchant_order_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, merchant_order_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchant_order_object : dict
Merchant Order object to be created
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param merchant_order_object must be a Dictionary

Returns

dict
Cards creation response
Expand source code
def create(self, merchant_order_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders/post/)  # pylint: disable=line-too-long

    Args:
        merchant_order_object (dict): Merchant Order object to be created
        request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass
            changing or adding custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param merchant_order_object must be a Dictionary

    Returns:
        dict: Cards creation response
    """
    if not isinstance(merchant_order_object, dict):
        raise ValueError(
            "Param merchant_order_object must be a Dictionary")

    return self._post(uri="/merchant_orders", data=merchant_order_object,
                      request_options=request_options)
def get(self, merchan_order_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchan_order_id : str
The Merchant Order ID
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Cards find response
Expand source code
def get(self, merchan_order_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/cards/_customers_customer_id_cards/get/)  # pylint: disable=line-too-long

    Args:
        merchan_order_id (str): The Merchant Order ID
        request_options (mercadopago.config.request_options, optional): An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

    Returns:
        dict: Cards find response
    """
    return self._get(uri="/merchant_orders/" + str(merchan_order_id),
                     request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

filters : dict
The search filters parameters
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Merchant Order find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_search/get/)  # pylint: disable=line-too-long

    Args:
        filters (dict): The search filters parameters
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Merchant Order find response
    """
    return self._get(uri="/merchant_orders/search", filters=filters,
                     request_options=request_options)
def update(self, merchan_order_id, merchant_order_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

merchan_order_id : str
Merchant Order ID
merchant_order_object : dict
Merchant Order object to be updated
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param merchant_order_object must be a Dictionary

Returns

dict
Cards modification response
Expand source code
def update(self, merchan_order_id, merchant_order_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/merchant_orders/_merchant_orders_id/put/)  # pylint: disable=line-too-long

    Args:
        merchan_order_id (str): Merchant Order ID
        merchant_order_object (dict): Merchant Order object to be updated
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param merchant_order_object must be a Dictionary

    Returns:
        dict: Cards modification response
    """
    if not isinstance(merchant_order_object, dict):
        raise ValueError(
            "Param merchant_order_object must be a Dictionary")

    return self._put(uri="/merchant_orders/" + str(merchan_order_id),
                     data=merchant_order_object, request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/payment.html000066400000000000000000000565351524412155200237540ustar00rootroot00000000000000 mercadopago.resources.payment API documentation

Module mercadopago.resources.payment

Module: payment

Expand source code
"""
    Module: payment
"""
from mercadopago.core import MPBase


class Payment(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own payment experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-api/introduction/)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_search/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/search", filters=filters,
                         request_options=request_options)

    def get(self, payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/" + str(payment_id), request_options=request_options)

    def create(self, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments/post/)  # pylint: disable=line-too-long

        Args:
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment creation response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._post(uri="/v1/payments", data=payment_object, request_options=request_options)

    def update(self, payment_id, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/payments/_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment modification response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._put(uri="/v1/payments/" + str(payment_id), data=payment_object,
                         request_options=request_options)

Classes

class Payment (request_options, http_client)

This class provides the methods to access the API that will allow you to create your own payment experience on your website.

From basic to advanced configurations, you control the whole experience.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Payment(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own payment experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-api/introduction/)  # pylint: disable=line-too-long
    """

    def search(self, filters=None, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_search/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/search", filters=filters,
                         request_options=request_options)

    def get(self, payment_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_id/get/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment find response
        """
        return self._get(uri="/v1/payments/" + str(payment_id), request_options=request_options)

    def create(self, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments/post/)  # pylint: disable=line-too-long

        Args:
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment creation response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._post(uri="/v1/payments", data=payment_object, request_options=request_options)

    def update(self, payment_id, payment_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/payments/_payments_id/put/)  # pylint: disable=line-too-long

        Args:
            payment_id (str): The Payment ID
            payment_object (dict): Payment to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param payment_object must be a Dictionary

        Returns:
            dict: Payment modification response
        """
        if not isinstance(payment_object, dict):
            raise ValueError("Param payment_object must be a Dictionary")

        return self._put(uri="/v1/payments/" + str(payment_id), data=payment_object,
                         request_options=request_options)

Ancestors

Methods

def create(self, payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_object : dict
Payment to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param payment_object must be a Dictionary

Returns

dict
Payment creation response
Expand source code
def create(self, payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments/post/)  # pylint: disable=line-too-long

    Args:
        payment_object (dict): Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param payment_object must be a Dictionary

    Returns:
        dict: Payment creation response
    """
    if not isinstance(payment_object, dict):
        raise ValueError("Param payment_object must be a Dictionary")

    return self._post(uri="/v1/payments", data=payment_object, request_options=request_options)
def get(self, payment_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_id : str
The Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment find response
Expand source code
def get(self, payment_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_id/get/)  # pylint: disable=line-too-long

    Args:
        payment_id (str): The Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment find response
    """
    return self._get(uri="/v1/payments/" + str(payment_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment find response
Expand source code
def search(self, filters=None, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payments/_payments_search/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment find response
    """
    return self._get(uri="/v1/payments/search", filters=filters,
                     request_options=request_options)
def update(self, payment_id, payment_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

payment_id : str
The Payment ID
payment_object : dict
Payment to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param payment_object must be a Dictionary

Returns

dict
Payment modification response
Expand source code
def update(self, payment_id, payment_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com.br/developers/en/reference/payments/_payments_id/put/)  # pylint: disable=line-too-long

    Args:
        payment_id (str): The Payment ID
        payment_object (dict): Payment to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param payment_object must be a Dictionary

    Returns:
        dict: Payment modification response
    """
    if not isinstance(payment_object, dict):
        raise ValueError("Param payment_object must be a Dictionary")

    return self._put(uri="/v1/payments/" + str(payment_id), data=payment_object,
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/payment_methods.html000066400000000000000000000264571524412155200254770ustar00rootroot00000000000000 mercadopago.resources.payment_methods API documentation

Module mercadopago.resources.payment_methods

Module: payment_methods

Expand source code
"""
    Module: payment_methods
"""
from mercadopago.core import MPBase


class PaymentMethods(MPBase):
    """
    Access to Payment Methods
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payment_methods/_payment_methods/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment Methods find response
        """
        return self._get(uri="/v1/payment_methods", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Classes

class PaymentMethods (request_options, http_client)

Access to Payment Methods

Expand source code
class PaymentMethods(MPBase):
    """
    Access to Payment Methods
    """

    def list_all(self, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payment_methods/_payment_methods/get/)  # pylint: disable=line-too-long

        Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Payment Methods find response
        """
        return self._get(uri="/v1/payment_methods", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def list_all(self, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Payment Methods find response
Expand source code
def list_all(self, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/payment_methods/_payment_methods/get/)  # pylint: disable=line-too-long

    Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Payment Methods find response
    """
    return self._get(uri="/v1/payment_methods", request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/preapproval.html000066400000000000000000000546561524412155200246340ustar00rootroot00000000000000 mercadopago.resources.preapproval API documentation

Module mercadopago.resources.preapproval

Module: preapproval

Expand source code
"""
    Module: preapproval
"""
from mercadopago.core import MPBase


class PreApproval(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own preapproval experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/subscriptions/introduction)  # pylint: disable=line-too-long
    """

    def __init__(self, request_options, http_client):
        MPBase.__init__(self, request_options, http_client)

    def search(self, filters=None, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/search", filters=filters,
                         request_options=request_options)

    def get(self, preapproval_id, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/" + str(preapproval_id), request_options=request_options)

    def create(self, preapproval_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/)  # pylint: disable=line-too-long

        Args:
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval creation response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._post(uri="/preapproval",
                          data=preapproval_object, request_options=request_options)

    def update(self, preapproval_id, preapproval_object, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval modification response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._put(uri="/preapproval" + str(preapproval_id),
                         data=preapproval_object, request_options=request_options)

Classes

class PreApproval (request_options, http_client)

This class provides the methods to access the API that will allow you to create your own preapproval experience on your website.

From basic to advanced configurations, you control the whole experience.

Click here for more info # pylint: disable=line-too-long

Expand source code
class PreApproval(MPBase):
    """
    This class provides the methods to access the API that will allow you to create
    your own preapproval experience on your website.

    From basic to advanced configurations, you control the whole experience.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/subscriptions/introduction)  # pylint: disable=line-too-long
    """

    def __init__(self, request_options, http_client):
        MPBase.__init__(self, request_options, http_client)

    def search(self, filters=None, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/search", filters=filters,
                         request_options=request_options)

    def get(self, preapproval_id, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: PreApproval find response
        """
        return self._get(uri="/preapproval/" + str(preapproval_id), request_options=request_options)

    def create(self, preapproval_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/)  # pylint: disable=line-too-long

        Args:
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval creation response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._post(uri="/preapproval",
                          data=preapproval_object, request_options=request_options)

    def update(self, preapproval_id, preapproval_object, request_options=None):
        """Args:
            preapproval_id (str): The PreApproval ID
            preapproval_object (dict): PreApproval to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preapproval_object must be a Dictionary

        Returns:
            dict: PreApproval modification response
        """
        if not isinstance(preapproval_object, dict):
            raise ValueError("Param preapproval_object must be a Dictionary")

        return self._put(uri="/preapproval" + str(preapproval_id),
                         data=preapproval_object, request_options=request_options)

Ancestors

Methods

def create(self, preapproval_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preapproval_object : dict
PreApproval to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preapproval_object must be a Dictionary

Returns

dict
PreApproval creation response
Expand source code
def create(self, preapproval_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/subscriptions/_preapproval/post/)  # pylint: disable=line-too-long

    Args:
        preapproval_object (dict): PreApproval to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preapproval_object must be a Dictionary

    Returns:
        dict: PreApproval creation response
    """
    if not isinstance(preapproval_object, dict):
        raise ValueError("Param preapproval_object must be a Dictionary")

    return self._post(uri="/preapproval",
                      data=preapproval_object, request_options=request_options)
def get(self, preapproval_id, request_options=None)

Args

preapproval_id : str
The PreApproval ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
PreApproval find response
Expand source code
def get(self, preapproval_id, request_options=None):
    """Args:
        preapproval_id (str): The PreApproval ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: PreApproval find response
    """
    return self._get(uri="/preapproval/" + str(preapproval_id), request_options=request_options)
def search(self, filters=None, request_options=None)

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
PreApproval find response
Expand source code
def search(self, filters=None, request_options=None):
    """Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: PreApproval find response
    """
    return self._get(uri="/preapproval/search", filters=filters,
                     request_options=request_options)
def update(self, preapproval_id, preapproval_object, request_options=None)

Args

preapproval_id : str
The PreApproval ID
preapproval_object : dict
PreApproval to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preapproval_object must be a Dictionary

Returns

dict
PreApproval modification response
Expand source code
def update(self, preapproval_id, preapproval_object, request_options=None):
    """Args:
        preapproval_id (str): The PreApproval ID
        preapproval_object (dict): PreApproval to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preapproval_object must be a Dictionary

    Returns:
        dict: PreApproval modification response
    """
    if not isinstance(preapproval_object, dict):
        raise ValueError("Param preapproval_object must be a Dictionary")

    return self._put(uri="/preapproval" + str(preapproval_id),
                     data=preapproval_object, request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/preference.html000066400000000000000000000515011524412155200244010ustar00rootroot00000000000000 mercadopago.resources.preference API documentation

Module mercadopago.resources.preference

Module: preference

Expand source code
"""
    Module: preference
"""
from mercadopago.core import MPBase


class Preference(MPBase):
    """
    This class will allow you to charge your customers through our web form
    from any device in a simple, fast and secure way.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-pro/introduction)  # pylint: disable=line-too-long
    """

    def get(self, preference_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Preference find response
        """
        return self._get(uri="/checkout/preferences/" + str(preference_id),
                         request_options=request_options)

    def update(self, preference_id, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/put/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            preference_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference modification response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._put(uri="/checkout/preferences/" + str(preference_id), data=preference_object,
                         request_options=request_options)

    def create(self, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences/post/) # pylint: disable=line-too-long

        Args:
            preference_object (dict): Preference object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
                RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference creation response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._post(uri="/checkout/preferences", data=preference_object,
                          request_options=request_options)

Classes

class Preference (request_options, http_client)

This class will allow you to charge your customers through our web form from any device in a simple, fast and secure way.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Preference(MPBase):
    """
    This class will allow you to charge your customers through our web form
    from any device in a simple, fast and secure way.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/online-payments/checkout-pro/introduction)  # pylint: disable=line-too-long
    """

    def get(self, preference_id, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: Preference find response
        """
        return self._get(uri="/checkout/preferences/" + str(preference_id),
                         request_options=request_options)

    def update(self, preference_id, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/put/)  # pylint: disable=line-too-long

        Args:
            preference_id (str): The Preference ID
            preference_object (dict): Values to be modified
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference modification response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._put(uri="/checkout/preferences/" + str(preference_id), data=preference_object,
                         request_options=request_options)

    def create(self, preference_object, request_options=None):
        """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences/post/) # pylint: disable=line-too-long

        Args:
            preference_object (dict): Preference object to be created
            request_options (mercadopago.config.request_options, optional): An instance of
                RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

        Raises:
            ValueError: Param preference_object must be a Dictionary

        Returns:
            dict: Preference creation response
        """
        if not isinstance(preference_object, dict):
            raise ValueError("Param preference_object must be a Dictionary")

        return self._post(uri="/checkout/preferences", data=preference_object,
                          request_options=request_options)

Ancestors

Methods

def create(self, preference_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_object : dict
Preference object to be created
request_options : mercadopago.config.request_options, optional
An instance of RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preference_object must be a Dictionary

Returns

dict
Preference creation response
Expand source code
def create(self, preference_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences/post/) # pylint: disable=line-too-long

    Args:
        preference_object (dict): Preference object to be created
        request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

    Raises:
        ValueError: Param preference_object must be a Dictionary

    Returns:
        dict: Preference creation response
    """
    if not isinstance(preference_object, dict):
        raise ValueError("Param preference_object must be a Dictionary")

    return self._post(uri="/checkout/preferences", data=preference_object,
                      request_options=request_options)
def get(self, preference_id, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_id : str
The Preference ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
Preference find response
Expand source code
def get(self, preference_id, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/get/)  # pylint: disable=line-too-long

    Args:
        preference_id (str): The Preference ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: Preference find response
    """
    return self._get(uri="/checkout/preferences/" + str(preference_id),
                     request_options=request_options)
def update(self, preference_id, preference_object, request_options=None)

Click here for more info # pylint: disable=line-too-long

Args

preference_id : str
The Preference ID
preference_object : dict
Values to be modified
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param preference_object must be a Dictionary

Returns

dict
Preference modification response
Expand source code
def update(self, preference_id, preference_object, request_options=None):
    """[Click here for more info](https://www.mercadopago.com/developers/en/reference/preferences/_checkout_preferences_id/put/)  # pylint: disable=line-too-long

    Args:
        preference_id (str): The Preference ID
        preference_object (dict): Values to be modified
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param preference_object must be a Dictionary

    Returns:
        dict: Preference modification response
    """
    if not isinstance(preference_object, dict):
        raise ValueError("Param preference_object must be a Dictionary")

    return self._put(uri="/checkout/preferences/" + str(preference_id), data=preference_object,
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/refund.html000066400000000000000000000375471524412155200235640ustar00rootroot00000000000000 mercadopago.resources.refund API documentation

Module mercadopago.resources.refund

Module: refund

Expand source code
"""
    Module: refund
"""
from mercadopago.core import MPBase


class Refund(MPBase):
    """
    This class will allow you to refund payments created through the Payments class.

    You can refund a payment within 180 days after it was approved.

    You must have sufficient funds in your account in order to successfully refund
    the payment amount. Otherwise, you will get a 400 Bad Request error.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/manage-account/account/cancellations-and-refunds#bookmark_refunds)  # pylint: disable=line-too-long
    """

    def list_all(self, payment_id, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: List all refunds of a payment
        """
        return self._get(uri="/v1/payments/" + str(payment_id) + "/refunds",
                         request_options=request_options)

    def create(self, payment_id, refund_object=None, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            refund_object (dict): Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param refund_object must be a Dictionary

        Returns:
            dict: Refund creation response
        """
        if refund_object is not None and not isinstance(refund_object, dict):
            raise ValueError("Param refund_object must be a Dictionary")

        return self._post(uri="/v1/payments/" + str(payment_id) + "/refunds",
                          data=refund_object, request_options=request_options)

Classes

class Refund (request_options, http_client)

This class will allow you to refund payments created through the Payments class.

You can refund a payment within 180 days after it was approved.

You must have sufficient funds in your account in order to successfully refund the payment amount. Otherwise, you will get a 400 Bad Request error.

Click here for more info # pylint: disable=line-too-long

Expand source code
class Refund(MPBase):
    """
    This class will allow you to refund payments created through the Payments class.

    You can refund a payment within 180 days after it was approved.

    You must have sufficient funds in your account in order to successfully refund
    the payment amount. Otherwise, you will get a 400 Bad Request error.

    [Click here for more info](https://www.mercadopago.com.br/developers/en/guides/manage-account/account/cancellations-and-refunds#bookmark_refunds)  # pylint: disable=line-too-long
    """

    def list_all(self, payment_id, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: List all refunds of a payment
        """
        return self._get(uri="/v1/payments/" + str(payment_id) + "/refunds",
                         request_options=request_options)

    def create(self, payment_id, refund_object=None, request_options=None):
        """Args:
            payment_id (str): The Payment ID
            refund_object (dict): Refund to be created
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Raises:
            ValueError: Param refund_object must be a Dictionary

        Returns:
            dict: Refund creation response
        """
        if refund_object is not None and not isinstance(refund_object, dict):
            raise ValueError("Param refund_object must be a Dictionary")

        return self._post(uri="/v1/payments/" + str(payment_id) + "/refunds",
                          data=refund_object, request_options=request_options)

Ancestors

Methods

def create(self, payment_id, refund_object=None, request_options=None)

Args

payment_id : str
The Payment ID
refund_object : dict
Refund to be created
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Raises

ValueError
Param refund_object must be a Dictionary

Returns

dict
Refund creation response
Expand source code
def create(self, payment_id, refund_object=None, request_options=None):
    """Args:
        payment_id (str): The Payment ID
        refund_object (dict): Refund to be created
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Raises:
        ValueError: Param refund_object must be a Dictionary

    Returns:
        dict: Refund creation response
    """
    if refund_object is not None and not isinstance(refund_object, dict):
        raise ValueError("Param refund_object must be a Dictionary")

    return self._post(uri="/v1/payments/" + str(payment_id) + "/refunds",
                      data=refund_object, request_options=request_options)
def list_all(self, payment_id, request_options=None)

Args

payment_id : str
The Payment ID
request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
List all refunds of a payment
Expand source code
def list_all(self, payment_id, request_options=None):
    """Args:
        payment_id (str): The Payment ID
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: List all refunds of a payment
    """
    return self._get(uri="/v1/payments/" + str(payment_id) + "/refunds",
                     request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/resources/user.html000066400000000000000000000244761524412155200232540ustar00rootroot00000000000000 mercadopago.resources.user API documentation

Module mercadopago.resources.user

Module: user

Expand source code
"""
    Module: user
"""
from mercadopago.core import MPBase


class User(MPBase):
    """
    Access to Users
    """

    def get(self, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: User find response
        """
        return self._get(uri="/users/me", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Classes

class User (request_options, http_client)

Access to Users

Expand source code
class User(MPBase):
    """
    Access to Users
    """

    def get(self, request_options=None):
        """Args:
            request_options (mercadopago.config.request_options, optional): An instance of
            RequestOptions can be pass changing or adding custom options to ur REST call.
            Defaults to None.

        Returns:
            dict: User find response
        """
        return self._get(uri="/users/me", request_options=request_options)

    @property
    def request_options(self):
        """
        Returns the attribute value of the function
        """
        return self.__request_options

Ancestors

Methods

def get(self, request_options=None)

Args

request_options : mercadopago.config.request_options, optional
An instance of

RequestOptions can be pass changing or adding custom options to ur REST call. Defaults to None.

Returns

dict
User find response
Expand source code
def get(self, request_options=None):
    """Args:
        request_options (mercadopago.config.request_options, optional): An instance of
        RequestOptions can be pass changing or adding custom options to ur REST call.
        Defaults to None.

    Returns:
        dict: User find response
    """
    return self._get(uri="/users/me", request_options=request_options)

Inherited members

mercadopago-sdk-python-b345a69/docs/sdk.html000066400000000000000000000775411524412155200210460ustar00rootroot00000000000000 mercadopago.sdk API documentation

Module mercadopago.sdk

Module: sdk

Expand source code
"""
Module: sdk
"""
from mercadopago.config import RequestOptions
from mercadopago.http import HttpClient
from mercadopago.resources import (
    AdvancedPayment,
    Card,
    CardToken,
    Customer,
    DisbursementRefund,
    IdentificationType,
    MerchantOrder,
    Payment,
    PaymentMethods,
    PreApproval,
    Preference,
    Refund,
    User,
)


class SDK:
    """Generate access to all API' modules, which are:

        1. Advanced Payment
        2. Card Token
        3. Card
        4. Customer
        5. Disbursement Refund
        6. Identification Type
        7. Merchant Order
        8. Payment Methods
        9. Payment
        10. Preapproval
        11. Preference
        12. Refund
        13. User
    """

    def __init__(
        self,
        access_token,
        http_client=None,
        request_options=None,
    ):
        """Construct ur SDK Object to have access to all APIs modules.
        Args:
            [Click here for more info](https://www.mercadopago.com/mlb/account/credentials)
            http_client (mercadopago.http.http_client, optional): An implementation of
            HttpClient can be pass to be used to make the REST calls. Defaults to None.
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            calls. Defaults to None.
        Raises:
            ValueError: Param request_options must be a RequestOptions Object
        """

        self.http_client = http_client
        if http_client is None:
            self.http_client = HttpClient()

        self.request_options = request_options
        if request_options is None:
            self.request_options = RequestOptions()

        self.request_options.access_token = access_token

    def advanced_payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return AdvancedPayment(request_options is not None and request_options
                               or self.request_options, self.http_client)

    def card_token(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return CardToken(request_options is not None and request_options
                         or self.request_options, self.http_client)

    def card(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Card(request_options is not None and request_options
                    or self.request_options, self.http_client)

    def customer(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Customer(request_options is not None and request_options
                        or self.request_options, self.http_client)

    def disbursement_refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return DisbursementRefund(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def identification_type(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return IdentificationType(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def merchant_order(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return MerchantOrder(request_options is not None and request_options
                             or self.request_options, self.http_client)

    def payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Payment(request_options is not None and request_options
                       or self.request_options, self.http_client)

    def payment_methods(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PaymentMethods(request_options is not None and request_options
                              or self.request_options, self.http_client)

    def preapproval(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PreApproval(request_options is not None and request_options
                           or self.request_options, self.http_client)

    def preference(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Preference(request_options is not None and request_options
                          or self.request_options, self.http_client)

    def refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Refund(request_options is not None and request_options
                      or self.request_options, self.http_client)

    def user(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return User(request_options is not None and request_options
                    or self.request_options, self.http_client)

    @property
    def request_options(self):
        """
        Sets the attribute value and validates request_options
        """
        return self.__request_options

    @request_options.setter
    def request_options(self, value):
        if value is not None and not isinstance(value, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        self.__request_options = value

    @property
    def http_client(self):
        """
        Sets the attribute value and validates http_client
        """
        return self.__http_client

    @http_client.setter
    def http_client(self, value):
        if value is not None and not isinstance(value, HttpClient):
            raise ValueError("Param http_client must be a HttpClient Object")
        self.__http_client = value

Classes

class SDK (access_token, http_client=None, request_options=None)

Generate access to all API' modules, which are:

  1. Advanced Payment
  2. Card Token
  3. Card
  4. Customer
  5. Disbursement Refund
  6. Identification Type
  7. Merchant Order
  8. Payment Methods
  9. Payment
  10. Preapproval
  11. Preference
  12. Refund
  13. User

Construct ur SDK Object to have access to all APIs modules.

Args

Click here for more info
http_client : mercadopago.http.http_client, optional
An implementation of
HttpClient can be pass to be used to make the REST calls. Defaults to None.
request_options : mercadopago.config.request_options, optional
An instance

of RequestOptions can be pass changing or adding custom options to ur REST calls. Defaults to None.

Raises

ValueError
Param request_options must be a RequestOptions Object
Expand source code
class SDK:
    """Generate access to all API' modules, which are:

        1. Advanced Payment
        2. Card Token
        3. Card
        4. Customer
        5. Disbursement Refund
        6. Identification Type
        7. Merchant Order
        8. Payment Methods
        9. Payment
        10. Preapproval
        11. Preference
        12. Refund
        13. User
    """

    def __init__(
        self,
        access_token,
        http_client=None,
        request_options=None,
    ):
        """Construct ur SDK Object to have access to all APIs modules.
        Args:
            [Click here for more info](https://www.mercadopago.com/mlb/account/credentials)
            http_client (mercadopago.http.http_client, optional): An implementation of
            HttpClient can be pass to be used to make the REST calls. Defaults to None.
            request_options (mercadopago.config.request_options, optional): An instance
            of RequestOptions can be pass changing or adding custom options to ur REST
            calls. Defaults to None.
        Raises:
            ValueError: Param request_options must be a RequestOptions Object
        """

        self.http_client = http_client
        if http_client is None:
            self.http_client = HttpClient()

        self.request_options = request_options
        if request_options is None:
            self.request_options = RequestOptions()

        self.request_options.access_token = access_token

    def advanced_payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return AdvancedPayment(request_options is not None and request_options
                               or self.request_options, self.http_client)

    def card_token(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return CardToken(request_options is not None and request_options
                         or self.request_options, self.http_client)

    def card(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Card(request_options is not None and request_options
                    or self.request_options, self.http_client)

    def customer(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Customer(request_options is not None and request_options
                        or self.request_options, self.http_client)

    def disbursement_refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return DisbursementRefund(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def identification_type(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return IdentificationType(request_options is not None and request_options
                                  or self.request_options, self.http_client)

    def merchant_order(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return MerchantOrder(request_options is not None and request_options
                             or self.request_options, self.http_client)

    def payment(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Payment(request_options is not None and request_options
                       or self.request_options, self.http_client)

    def payment_methods(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PaymentMethods(request_options is not None and request_options
                              or self.request_options, self.http_client)

    def preapproval(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return PreApproval(request_options is not None and request_options
                           or self.request_options, self.http_client)

    def preference(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Preference(request_options is not None and request_options
                          or self.request_options, self.http_client)

    def refund(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return Refund(request_options is not None and request_options
                      or self.request_options, self.http_client)

    def user(self, request_options=None):
        """
        Returns the attribute value of the function
        """
        return User(request_options is not None and request_options
                    or self.request_options, self.http_client)

    @property
    def request_options(self):
        """
        Sets the attribute value and validates request_options
        """
        return self.__request_options

    @request_options.setter
    def request_options(self, value):
        if value is not None and not isinstance(value, RequestOptions):
            raise ValueError(
                "Param request_options must be a RequestOptions Object")
        self.__request_options = value

    @property
    def http_client(self):
        """
        Sets the attribute value and validates http_client
        """
        return self.__http_client

    @http_client.setter
    def http_client(self, value):
        if value is not None and not isinstance(value, HttpClient):
            raise ValueError("Param http_client must be a HttpClient Object")
        self.__http_client = value

Instance variables

var http_client

Sets the attribute value and validates http_client

Expand source code
@property
def http_client(self):
    """
    Sets the attribute value and validates http_client
    """
    return self.__http_client
var request_options

Sets the attribute value and validates request_options

Expand source code
@property
def request_options(self):
    """
    Sets the attribute value and validates request_options
    """
    return self.__request_options

Methods

def advanced_payment(self, request_options=None)

Returns the attribute value of the function

Expand source code
def advanced_payment(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return AdvancedPayment(request_options is not None and request_options
                           or self.request_options, self.http_client)
def card(self, request_options=None)

Returns the attribute value of the function

Expand source code
def card(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Card(request_options is not None and request_options
                or self.request_options, self.http_client)
def card_token(self, request_options=None)

Returns the attribute value of the function

Expand source code
def card_token(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return CardToken(request_options is not None and request_options
                     or self.request_options, self.http_client)
def customer(self, request_options=None)

Returns the attribute value of the function

Expand source code
def customer(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Customer(request_options is not None and request_options
                    or self.request_options, self.http_client)
def disbursement_refund(self, request_options=None)

Returns the attribute value of the function

Expand source code
def disbursement_refund(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return DisbursementRefund(request_options is not None and request_options
                              or self.request_options, self.http_client)
def identification_type(self, request_options=None)

Returns the attribute value of the function

Expand source code
def identification_type(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return IdentificationType(request_options is not None and request_options
                              or self.request_options, self.http_client)
def merchant_order(self, request_options=None)

Returns the attribute value of the function

Expand source code
def merchant_order(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return MerchantOrder(request_options is not None and request_options
                         or self.request_options, self.http_client)
def payment(self, request_options=None)

Returns the attribute value of the function

Expand source code
def payment(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Payment(request_options is not None and request_options
                   or self.request_options, self.http_client)
def payment_methods(self, request_options=None)

Returns the attribute value of the function

Expand source code
def payment_methods(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return PaymentMethods(request_options is not None and request_options
                          or self.request_options, self.http_client)
def preapproval(self, request_options=None)

Returns the attribute value of the function

Expand source code
def preapproval(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return PreApproval(request_options is not None and request_options
                       or self.request_options, self.http_client)
def preference(self, request_options=None)

Returns the attribute value of the function

Expand source code
def preference(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Preference(request_options is not None and request_options
                      or self.request_options, self.http_client)
def refund(self, request_options=None)

Returns the attribute value of the function

Expand source code
def refund(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return Refund(request_options is not None and request_options
                  or self.request_options, self.http_client)
def user(self, request_options=None)

Returns the attribute value of the function

Expand source code
def user(self, request_options=None):
    """
    Returns the attribute value of the function
    """
    return User(request_options is not None and request_options
                or self.request_options, self.http_client)
mercadopago-sdk-python-b345a69/examples/000077500000000000000000000000001524412155200202475ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/examples/order/000077500000000000000000000000001524412155200213625ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/examples/order/create_order_automatic_payment.py000066400000000000000000000123141524412155200301760ustar00rootroot00000000000000"""Example: Automatic Payments flow with the MercadoPago Orders API. Demonstrates both the first payment (storing the card credential) and a subsequent recurring charge (referencing the previous transaction). """ import dataclasses import mercadopago from mercadopago.resources.order_automatic_payments import OrderAutomaticPayments from mercadopago.resources.order_stored_credential import OrderStoredCredential from mercadopago.resources.order_subscription_data import ( OrderInvoicePeriod, OrderSubscriptionData, OrderSubscriptionSequence, ) sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # ── First payment ────────────────────────────────────────────────────────── # Use first_payment=True and no prev_transaction_ref. # The API stores the credential for future charges. first_payment_order = { "type": "online", "total_amount": "100.00", "external_reference": "subscription-001-payment-1", "payer": { "email": "customer@example.com", "customer_id": "CUSTOMER_ID", }, "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", "token": "CARD_TOKEN", "installments": 1, }, "automatic_payments": dataclasses.asdict( OrderAutomaticPayments( payment_profile_id="PAYMENT_PROFILE_ID", schedule_date="2026-07-01T00:00:00.000-04:00", due_date="2026-07-05T00:00:00.000-04:00", retries=3, ) ), "stored_credential": dataclasses.asdict( OrderStoredCredential( payment_initiator="merchant", reason="recurring", store_payment_method=True, first_payment=True, # prev_transaction_ref not required on first payment ) ), "subscription_data": dataclasses.asdict( OrderSubscriptionData( invoice_id="INVOICE_001", billing_date="2026-06-01", subscription_sequence=OrderSubscriptionSequence(number=1, total=12), invoice_period=OrderInvoicePeriod(type="monthly", period=1), ) ), } ] }, } result = sdk.order().create(first_payment_order) first_order = result["response"] print("First payment order:", first_order.get("id"), "β†’", first_order.get("status")) # Save the transaction ID for use in the next charge. first_transaction_id = ( first_order.get("transactions", {}) .get("payments", [{}])[0] .get("id", "") ) # ── Subsequent recurring charge ──────────────────────────────────────────── # Use first_payment=False and include prev_transaction_ref pointing to the # previous charge. The API links this payment to the original authorization. recurring_order = { "type": "online", "total_amount": "100.00", "external_reference": "subscription-001-payment-2", "payer": { "email": "customer@example.com", "customer_id": "CUSTOMER_ID", }, "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", "token": "CARD_TOKEN", "installments": 1, }, "automatic_payments": dataclasses.asdict( OrderAutomaticPayments( payment_profile_id="PAYMENT_PROFILE_ID", schedule_date="2026-08-01T00:00:00.000-04:00", due_date="2026-08-05T00:00:00.000-04:00", retries=3, ) ), "stored_credential": dataclasses.asdict( OrderStoredCredential( payment_initiator="merchant", reason="recurring", store_payment_method=False, first_payment=False, previous_transaction_reference=first_transaction_id, # required ) ), "subscription_data": dataclasses.asdict( OrderSubscriptionData( invoice_id="INVOICE_002", billing_date="2026-07-01", subscription_sequence=OrderSubscriptionSequence(number=2, total=12), invoice_period=OrderInvoicePeriod(type="monthly", period=1), ) ), } ] }, } result = sdk.order().create(recurring_order) recurring = result["response"] print("Recurring charge order:", recurring.get("id"), "β†’", recurring.get("status")) mercadopago-sdk-python-b345a69/examples/order/create_order_credential_on_file.py000066400000000000000000000140721524412155200302630ustar00rootroot00000000000000"""Example: CREDENTIAL_ON_FILE automatic payment flows with the MercadoPago Orders API. Demonstrates three scenarios that use the ``transaction_data`` block with ``type: "CREDENTIAL_ON_FILE"``: 1. **CIT – Customer-Initiated Transaction (enrolment)** The cardholder authorises the first charge and the credential is stored for future use. ``first_transaction: True``, ``storage: "store"``, ``transaction_initiator: "customer"``. 2. **MIT – Merchant-Initiated Transaction (scheduled recurring charge)** The merchant triggers a charge without cardholder interaction, referencing the original CIT. ``first_transaction: False``, ``storage: "stored"``, ``transaction_initiator: "merchant"``, ``reference.id`` pointing to the CIT payment id. 3. **UCOF-CIT – Unscheduled Card-On-File, Customer-Initiated** The cardholder initiates a one-off purchase using a previously stored card. ``sub_type: "unscheduled"``, ``storage: "stored"``, ``transaction_initiator: "customer"``, ``first_transaction: False``. """ import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") # ── 1. CIT – Enrolment / first payment ──────────────────────────────────────── # The cardholder completes checkout and their card is stored for future charges. cit_order = { "type": "online", "total_amount": "100.00", "external_reference": "cof-subscription-001-cit", "payer": { "email": "customer@example.com", "customer_id": "CUSTOMER_ID", }, "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", "token": "CARD_TOKEN", "installments": 1, }, "transaction_data": { # CREDENTIAL_ON_FILE identifies this as a stored-credential flow. "type": "CREDENTIAL_ON_FILE", # "recurring" indicates a subscription-style agreement. "sub_type": "recurring", # "store" signals that the credential should be saved now. "storage": "store", # The cardholder is present and initiates this first charge. "transaction_initiator": "customer", # Mark as first transaction so the network creates the mandate. "first_transaction": True, }, } ] }, } result = sdk.order().create(cit_order) cit_response = result["response"] print("CIT order:", cit_response.get("id"), "β†’", cit_response.get("status")) # Capture the payment id to reference it in the subsequent MIT charges. cit_payment_id = ( cit_response.get("transactions", {}) .get("payments", [{}])[0] .get("id", "") ) # ── 2. MIT – Scheduled recurring charge ─────────────────────────────────────── # The merchant triggers the monthly charge without cardholder interaction. # The ``reference.id`` links this payment to the original CIT authorisation. mit_order = { "type": "online", "total_amount": "100.00", "external_reference": "cof-subscription-001-mit-month-2", "payer": { "email": "customer@example.com", "customer_id": "CUSTOMER_ID", }, "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", # No card token needed β€” the credential is already stored. "installments": 1, }, "transaction_data": { "type": "CREDENTIAL_ON_FILE", "sub_type": "recurring", # "stored" confirms the credential was previously persisted. "storage": "stored", # The merchant initiates this charge on the cardholder's behalf. "transaction_initiator": "merchant", "first_transaction": False, # Reference the CIT payment so the network can trace the series. "reference": { "id": cit_payment_id, }, }, } ] }, } result = sdk.order().create(mit_order) mit_response = result["response"] print("MIT order:", mit_response.get("id"), "β†’", mit_response.get("status")) # ── 3. UCOF-CIT – Unscheduled Card-On-File, Customer-Initiated ──────────────── # The cardholder returns to the site and pays with their stored card in a # one-off, unplanned transaction (e.g. top-up, on-demand purchase). ucof_cit_order = { "type": "online", "total_amount": "49.90", "external_reference": "cof-ucof-cit-purchase-001", "payer": { "email": "customer@example.com", "customer_id": "CUSTOMER_ID", }, "transactions": { "payments": [ { "amount": "49.90", "payment_method": { "id": "master", "type": "credit_card", "installments": 1, }, "transaction_data": { "type": "CREDENTIAL_ON_FILE", # "unscheduled" distinguishes this from a planned recurring charge. "sub_type": "unscheduled", # The credential was already stored from the original CIT. "storage": "stored", # The cardholder is present and actively initiates this purchase. "transaction_initiator": "customer", "first_transaction": False, }, } ] }, } result = sdk.order().create(ucof_cit_order) ucof_response = result["response"] print("UCOF-CIT order:", ucof_response.get("id"), "β†’", ucof_response.get("status")) mercadopago-sdk-python-b345a69/mercadopago/000077500000000000000000000000001524412155200207125ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/__init__.py000066400000000000000000000027011524412155200230230ustar00rootroot00000000000000"""MercadoPago Python SDK. Provides a high-level client for the MercadoPago REST API. Import the :class:`SDK` class and initialise it with your access token to get started:: import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") payment = sdk.payment().create({...}) """ from mercadopago.errors.constants import ( MPOrderErrors, MPPaymentErrors, ) from mercadopago.errors.exceptions import ( MercadoPagoError, MPAuthenticationError, MPBadRequestError, MPConnectionError, MPDependencyError, MPForbiddenError, MPIdempotencyError, MPNotFoundError, MPPaymentError, MPRateLimitError, MPResourceLockedError, MPServerError, MPValidationError, ) from mercadopago.errors.response import MPResponse from mercadopago.resources.status import ( MerchantOrderStatus, OrderStatus, PaymentStatus, PreapprovalStatus, RefundStatus, ) from mercadopago.sdk import SDK __all__ = ( 'SDK', 'MercadoPagoError', 'MPBadRequestError', 'MPAuthenticationError', 'MPPaymentError', 'MPForbiddenError', 'MPNotFoundError', 'MPIdempotencyError', 'MPValidationError', 'MPResourceLockedError', 'MPDependencyError', 'MPRateLimitError', 'MPServerError', 'MPConnectionError', 'MPOrderErrors', 'MPPaymentErrors', 'MPResponse', 'PaymentStatus', 'OrderStatus', 'PreapprovalStatus', 'MerchantOrderStatus', 'RefundStatus', ) mercadopago-sdk-python-b345a69/mercadopago/config/000077500000000000000000000000001524412155200221575ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/config/__init__.py000066400000000000000000000005641524412155200242750ustar00rootroot00000000000000"""Configuration components for the MercadoPago Python SDK. Exposes :class:`Config` (SDK-level constants) and :class:`RequestOptions` (per-request settings such as access token, timeout, and custom headers). """ from mercadopago.config.config import Config from mercadopago.config.request_options import RequestOptions __all__ = ( 'Config', 'RequestOptions', ) mercadopago-sdk-python-b345a69/mercadopago/config/config.py000066400000000000000000000046431524412155200240050ustar00rootroot00000000000000"""SDK-level configuration constants. Centralises version information, API base URL, MIME types, and tracking identifiers used by every HTTP request the SDK makes. All values are read-only after initialisation. """ import platform class Config: """Read-only container for SDK-wide constants and tracking metadata. An instance is created internally by :class:`~mercadopago.core.mp_base.MPBase` and should not need to be instantiated by end-users. Attributes: version: Semantic version string of this SDK release. user_agent: User-Agent header value sent with every request. product_id: MercadoPago-assigned product identifier for this SDK. tracking_id: Composite string with Python version and SDK version used by MercadoPago for telemetry. api_base_url: Root URL for all MercadoPago REST API calls. mime_json: MIME type for JSON payloads. mime_form: MIME type for form-encoded payloads. """ def __init__(self): """Builds version-dependent values (user_agent, tracking_id).""" self.__version = "3.6.0" self.__user_agent = "MercadoPago Python SDK v" + self.__version self.__product_id = "bc32bpftrpp001u8nhlg" self.__tracking_id = "platform:" + platform.python_version() self.__tracking_id += ",type:SDK" + self.__version + ",so;" __api_base_url = "https://api.mercadopago.com" __mime_json = "application/json" __mime_form = "application/x-www-form-urlencoded" @property def version(self): """Semantic version of the SDK (e.g. ``'2.4.0'``).""" return self.__version @property def user_agent(self): """User-Agent header value identifying this SDK.""" return self.__user_agent @property def product_id(self): """MercadoPago-assigned product identifier for SDK tracking.""" return self.__product_id @property def tracking_id(self): """Composite tracking string with Python and SDK versions.""" return self.__tracking_id @property def api_base_url(self): """Root URL for MercadoPago REST API calls.""" return self.__api_base_url @property def mime_json(self): """MIME type for JSON request/response bodies.""" return self.__mime_json @property def mime_form(self): """MIME type for form-encoded request bodies.""" return self.__mime_form mercadopago-sdk-python-b345a69/mercadopago/config/defaults.py000066400000000000000000000014401524412155200243370ustar00rootroot00000000000000"""Default configuration constants for the MercadoPago Python SDK. These match the current SDK behaviour so that callers who never set retry options receive identical results to before. Attributes: DEFAULT_TIMEOUT_SECONDS: Request timeout in seconds (60.0). DEFAULT_MAX_RETRIES: Maximum automatic retries on transient errors (3). DEFAULT_RETRY_ON: HTTP status codes that trigger a retry. DEFAULT_MAX_DELAY: Maximum delay between retries in milliseconds (30 000). DEFAULT_INITIAL_DELAY: Initial backoff delay in milliseconds (None = urllib3 default). """ DEFAULT_TIMEOUT_SECONDS = 60.0 DEFAULT_MAX_RETRIES = 3 DEFAULT_RETRY_ON = [429, 500, 502, 503, 504] DEFAULT_MAX_DELAY = 30_000 # milliseconds DEFAULT_INITIAL_DELAY = None # None = no extra backoff beyond urllib3 default mercadopago-sdk-python-b345a69/mercadopago/config/request_options.py000066400000000000000000000231121524412155200257730ustar00rootroot00000000000000"""Per-request configuration for MercadoPago API calls. Holds authentication credentials, timeout, retry policy, and any custom or platform-specific headers that should be sent with a request. """ import uuid from .config import Config from .defaults import ( DEFAULT_INITIAL_DELAY, DEFAULT_MAX_DELAY, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_SECONDS, ) class RequestOptions: # pylint: disable=too-many-instance-attributes """Mutable configuration applied to each REST call made by a resource. Callers may create a default instance via :class:`~mercadopago.sdk.SDK` and override it per-call by passing a different ``RequestOptions`` to any resource method. Attributes: access_token: OAuth access token for the MercadoPago API. connection_timeout: Seconds before a request times out. custom_headers: Extra headers merged into every request. max_retries: Maximum automatic retries on transient failures. corporation_id: Optional corporation identifier header. integrator_id: Optional integrator identifier header. platform_id: Optional platform identifier header. """ __access_token = None __connection_timeout = None __custom_headers = None __max_retries = None __corporation_id = None __integrator_id = None __platform_id = None __initial_delay = None __max_delay = None __jitter = None __retry_on = None __on_retry = None def __init__( # pylint: disable=too-many-positional-arguments # pylint: disable=too-many-arguments self, access_token=None, connection_timeout=DEFAULT_TIMEOUT_SECONDS, custom_headers=None, corporation_id=None, integrator_id=None, platform_id=None, max_retries=DEFAULT_MAX_RETRIES, initial_delay=DEFAULT_INITIAL_DELAY, max_delay=DEFAULT_MAX_DELAY, jitter=None, retry_on=None, on_retry=None, ): """Initialises request options with sensible defaults. Every parameter is validated through its property setter. Pass only the values you need to override; the rest keep their defaults. Args: access_token: OAuth access token. Obtain one from the `MercadoPago credentials page `_. connection_timeout: Request timeout in seconds. Defaults to 60.0. custom_headers: Additional headers merged into every request. corporation_id: Corporation identifier sent as ``x-corporation-id``. integrator_id: Integrator identifier sent as ``x-integrator-id``. platform_id: Platform identifier sent as ``x-platform-id``. max_retries: Retry count on transient HTTP errors. Defaults to 3. Raises: ValueError: If any parameter fails its type check. """ if access_token is not None: self.access_token = access_token if connection_timeout is not None: self.connection_timeout = connection_timeout if custom_headers is not None: self.custom_headers = custom_headers if max_retries is not None: self.max_retries = max_retries if corporation_id is not None: self.corporation_id = corporation_id if integrator_id is not None: self.integrator_id = integrator_id if platform_id is not None: self.platform_id = platform_id self.__initial_delay = initial_delay self.__max_delay = max_delay self.__jitter = jitter self.__retry_on = retry_on self.__on_retry = on_retry self.__config = Config() def get_headers(self): """Builds the full header dict for an API request. Merges authentication, tracking, idempotency, and any optional platform/integrator/corporation headers plus user-supplied ``custom_headers`` into a single dict ready for ``requests``. Returns: dict: Header name-value pairs. """ headers = {"Authorization": "Bearer " + self.__access_token, "x-product-id": self.__config.product_id, "x-tracking-id": self.__config.tracking_id, "x-idempotency-key": str(uuid.uuid4().int), "User-Agent": self.__config.user_agent, "Accept": self.__config.mime_json} if self.__corporation_id is not None: headers["x-corporation-id"] = self.__corporation_id if self.__integrator_id is not None: headers["x-integrator-id"] = self.__integrator_id if self.__platform_id is not None: headers["x-platform-id"] = self.__platform_id if self.__custom_headers is not None: headers.update(self.__custom_headers) return headers @property def access_token(self): """OAuth access token used for API authentication.""" return self.__access_token @access_token.setter def access_token(self, value): if not isinstance(value, str): raise ValueError("Param access_token must be a String") self.__access_token = value @property def connection_timeout(self): """Request timeout in seconds.""" return self.__connection_timeout @connection_timeout.setter def connection_timeout(self, value): if not isinstance(value, float): raise ValueError("Param connection_timeout must be a Float") self.__connection_timeout = value @property def corporation_id(self): """Corporation identifier sent as ``x-corporation-id`` header.""" return self.__corporation_id @corporation_id.setter def corporation_id(self, value): if not isinstance(value, str): raise ValueError("Param corporation_id must be a String") self.__corporation_id = value @property def custom_headers(self): """Extra headers merged into every API request.""" return self.__custom_headers @custom_headers.setter def custom_headers(self, value): if not isinstance(value, dict): raise ValueError("Param custom_headers must be a Dictionary") idem_key = value.get("x-idempotency-key") if idem_key is None: idem_key = value.get("X-Idempotency-Key") if idem_key is not None and not (1 <= len(str(idem_key)) <= 64): raise ValueError( "x-idempotency-key must be between 1 and 64 characters " f"(got {len(str(idem_key))})" ) self.__custom_headers = value @property def integrator_id(self): """Integrator identifier sent as ``x-integrator-id`` header.""" return self.__integrator_id @integrator_id.setter def integrator_id(self, value): if not isinstance(value, str): raise ValueError("Param integrator_id must be a String") self.__integrator_id = value @property def max_retries(self): """Maximum automatic retries on transient HTTP errors.""" return self.__max_retries @max_retries.setter def max_retries(self, value): if not isinstance(value, int): raise ValueError("Param max_retries must be an Integer") self.__max_retries = value @property def platform_id(self): """Platform identifier sent as ``x-platform-id`` header.""" return self.__platform_id @platform_id.setter def platform_id(self, value): if not isinstance(value, str): raise ValueError("Param platform_id must be a String") self.__platform_id = value @property def initial_delay(self): """Initial backoff delay in ms (None = no extra delay).""" return self.__initial_delay @initial_delay.setter def initial_delay(self, value): if value is not None and not isinstance(value, int): raise ValueError("Param initial_delay must be an Integer or None") self.__initial_delay = value @property def max_delay(self): """Maximum backoff delay cap in ms.""" return self.__max_delay @max_delay.setter def max_delay(self, value): if value is not None and not isinstance(value, int): raise ValueError("Param max_delay must be an Integer or None") self.__max_delay = value @property def jitter(self): """Whether to add random jitter to retry delay.""" return self.__jitter @jitter.setter def jitter(self, value): if value is not None and not isinstance(value, bool): raise ValueError("Param jitter must be a Boolean or None") self.__jitter = value @property def retry_on(self): """List of HTTP status codes that trigger a retry, or None for defaults.""" return self.__retry_on @retry_on.setter def retry_on(self, value): if value is not None: if not isinstance(value, list): raise ValueError("Param retry_on must be a List or None") for code in value: if not isinstance(code, int) or code < 100 or code > 599: raise ValueError(f"retry_on contains invalid HTTP status code: {code}") self.__retry_on = value @property def on_retry(self): """Optional callback(attempt, error) invoked before each retry.""" return self.__on_retry @on_retry.setter def on_retry(self, value): if value is not None and not callable(value): raise ValueError("Param on_retry must be callable or None") self.__on_retry = value mercadopago-sdk-python-b345a69/mercadopago/core/000077500000000000000000000000001524412155200216425ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/core/__init__.py000066400000000000000000000004461524412155200237570ustar00rootroot00000000000000"""Core base class for all MercadoPago API resource modules. Exposes :class:`MPBase`, the abstract superclass that provides authenticated HTTP helpers (``_get``, ``_post``, ``_put``, ``_delete``) to every resource. """ from mercadopago.core.mp_base import MPBase __all__ = ( 'MPBase', ) mercadopago-sdk-python-b345a69/mercadopago/core/mp_base.py000066400000000000000000000164761524412155200236400ustar00rootroot00000000000000"""Base class for all MercadoPago API resource modules. Provides authenticated HTTP helpers that every resource (Payment, Order, Customer, etc.) inherits. Handles request-option merging, header construction, JSON encoding, and delegation to the configured HTTP client. """ from json.encoder import JSONEncoder from urllib.parse import quote from mercadopago.config.config import Config from mercadopago.config.request_options import RequestOptions from mercadopago.errors.response import MPResponse class MPBase: """Abstract base for MercadoPago API resources. Subclasses inherit ``_get``, ``_post``, ``_put``, and ``_delete`` helpers that transparently manage authentication headers, JSON serialisation, timeout, and retry logic. Each resource class only needs to define its own public methods mapping to specific API endpoints. Attributes: request_options: The :class:`RequestOptions` instance used by default when callers do not supply a per-call override. config: Read-only :class:`Config` with SDK constants. """ def __init__(self, request_options, http_client): """Initialises the base with shared request options and HTTP client. Args: request_options: Default options (token, timeout, retries, headers) applied to every call unless overridden. http_client: :class:`~mercadopago.http.http_client.HttpClient` instance used to execute HTTP requests. Raises: ValueError: If *request_options* is not a :class:`RequestOptions` instance. """ if not isinstance(request_options, RequestOptions): raise ValueError( "Param request_options must be a RequestOptions Object") self.__request_options = request_options self.__http_client = http_client self.__config = Config() def __check_request_options(self, request_options): """Resolves and validates per-call request options. Falls back to the instance-level defaults when *request_options* is ``None``, and ensures the access token is always present. """ if request_options is not None and not isinstance(request_options, RequestOptions): raise ValueError( "Param request_options must be a RequestOptions Object") if request_options is None: request_options = self.__request_options if request_options.access_token is None: request_options.access_token = self.__request_options.access_token return request_options def __check_headers(self, request_options, extra_headers=None): """Builds the merged header dict for a request. Starts from the headers generated by *request_options* (or the instance default) and layers on any *extra_headers* such as Content-Type. """ headers = self.__request_options.get_headers() if request_options is not None: headers = request_options.get_headers() if extra_headers is not None: headers.update(extra_headers) return headers def _path_param(self, value): """Encodes a dynamic URL path segment.""" return quote(str(value), safe="") def _get(self, uri, filters=None, request_options=None): """Performs an authenticated GET request. Args: uri: API path relative to the base URL (e.g. ``/v1/payments``). filters: Optional query-string parameters. request_options: Per-call overrides; falls back to instance defaults. Raises: ValueError: If *filters* is provided but is not a ``dict``. Returns: dict: ``{"status": , "response": }``. """ if filters is not None and not isinstance(filters, dict): raise ValueError("Filters must be a Dictionary") request_options = self.__check_request_options(request_options) headers = self.__check_headers( request_options, {"Content-type": self.__config.mime_json}) return MPResponse(self.__http_client.get( url=self.__config.api_base_url + uri, params=filters, headers=headers, timeout=request_options.connection_timeout, maxretries=request_options.max_retries, retry_on=request_options.retry_on, )) def _post(self, uri, data=None, params=None, request_options=None): """Performs an authenticated POST request. Args: uri: API path relative to the base URL. data: Request body dict; JSON-encoded automatically. params: Optional query-string parameters. request_options: Per-call overrides; falls back to instance defaults. Returns: dict: ``{"status": , "response": }``. """ if data is not None: data = JSONEncoder().encode(data) request_options = self.__check_request_options(request_options) headers = self.__check_headers( request_options, {"Content-type": self.__config.mime_json}) return MPResponse(self.__http_client.post( url=self.__config.api_base_url + uri, data=data, params=params, headers=headers, timeout=request_options.connection_timeout, maxretries=request_options.max_retries, retry_on=request_options.retry_on, )) def _put(self, uri, data=None, params=None, request_options=None): """Performs an authenticated PUT request.""" if data is not None: data = JSONEncoder().encode(data) request_options = self.__check_request_options(request_options) headers = self.__check_headers( request_options, {"Content-type": self.__config.mime_json}) return MPResponse(self.__http_client.put( url=self.__config.api_base_url + uri, data=data, params=params, headers=headers, timeout=request_options.connection_timeout, maxretries=request_options.max_retries, retry_on=request_options.retry_on, )) def _delete(self, uri, params=None, request_options=None): """Performs an authenticated DELETE request. Args: uri: API path relative to the base URL. params: Optional query-string parameters. request_options: Per-call overrides; falls back to instance defaults. Returns: dict: ``{"status": , "response": }``. """ request_options = self.__check_request_options(request_options) headers = self.__check_headers(request_options) return MPResponse(self.__http_client.delete( url=self.__config.api_base_url + uri, params=params, headers=headers, timeout=request_options.connection_timeout, maxretries=request_options.max_retries, retry_on=request_options.retry_on, )) @property def request_options(self): """Default :class:`RequestOptions` for this resource instance.""" return self.__request_options @property def config(self): """Read-only :class:`Config` with SDK-wide constants.""" return self.__config mercadopago-sdk-python-b345a69/mercadopago/errors/000077500000000000000000000000001524412155200222265ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/errors/__init__.py000066400000000000000000000014421524412155200243400ustar00rootroot00000000000000"""Errors package for the MercadoPago Python SDK.""" from .exceptions import ( MercadoPagoError, MPAuthenticationError, MPBadRequestError, MPConnectionError, MPDependencyError, MPForbiddenError, MPIdempotencyError, MPNotFoundError, MPPaymentError, MPRateLimitError, MPResourceLockedError, MPServerError, MPValidationError, build_error, ) from .response import MPResponse __all__ = [ "MercadoPagoError", "MPBadRequestError", "MPAuthenticationError", "MPPaymentError", "MPForbiddenError", "MPNotFoundError", "MPIdempotencyError", "MPValidationError", "MPResourceLockedError", "MPDependencyError", "MPRateLimitError", "MPServerError", "MPConnectionError", "build_error", "MPResponse", ] mercadopago-sdk-python-b345a69/mercadopago/errors/constants.py000066400000000000000000000016101524412155200246120ustar00rootroot00000000000000"""Error string constants for MercadoPago API error codes. Use these constants instead of hard-coding ``error`` string literals so that code is refactoring-safe and benefits from IDE auto-complete. Example:: from mercadopago.errors.constants import MPOrderErrors except MPIdempotencyError as e: if e.error == MPOrderErrors.CANNOT_REFUND: handle_cannot_refund() """ class MPOrderErrors: """Machine-readable ``error`` strings returned for Order/v1 conflicts (HTTP 409).""" CANNOT_REFUND = "cannot_refund_order" CANNOT_CANCEL = "cannot_cancel_order" CANNOT_CAPTURE = "cannot_capture_order" ALREADY_REFUNDED = "order_already_refunded" ALREADY_CANCELED = "order_already_canceled" RESOURCE_LOCKED = "resource_locked" class MPPaymentErrors: """Machine-readable ``error`` strings returned for payment errors (HTTP 402).""" FAILED = "failed" mercadopago-sdk-python-b345a69/mercadopago/errors/exceptions.py000066400000000000000000000101551524412155200247630ustar00rootroot00000000000000"""Typed exception hierarchy for MercadoPago API errors. All exceptions inherit from :class:`MercadoPagoError`, preserving backward-compatible ``catch`` patterns while enabling specific handling per HTTP status code. """ class MercadoPagoError(Exception): """Base exception for all MercadoPago API errors. Raised when the API returns a non-2xx status code. Callers may catch this base class to handle any API error, or catch a subtype to react specifically to 401, 404, 429, etc. Attributes: status_code: HTTP status code (e.g. 400, 401, 500). message: Human-readable error summary from the API. error: Machine-readable error code (e.g. ``"unauthorized"``). causes: List of detailed cause dicts returned by the API. request_id: ``x-request-id`` header for support diagnosis. """ def __init__(self, status_code, response_body): self.status_code = status_code self.response = response_body or {} self.message = self.response.get("message", "") self.error = self.response.get("error", "") self.causes = self.response.get("cause", []) self.request_id = None # set by MPResponse if x-request-id header is available super().__init__(f"[{status_code}] {self.message or self.error}") class MPBadRequestError(MercadoPagoError): """HTTP 400 Bad Request β€” validation or syntax error.""" class MPAuthenticationError(MercadoPagoError): """HTTP 401 Unauthorized β€” missing or invalid credentials.""" class MPPaymentError(MercadoPagoError): """HTTP 402 Payment Required β€” transaction processing error (AP/Orders).""" class MPForbiddenError(MercadoPagoError): """HTTP 403 Forbidden.""" class MPNotFoundError(MercadoPagoError): """HTTP 404 Not Found.""" class MPIdempotencyError(MercadoPagoError): """HTTP 409 Conflict β€” idempotency-key conflict or state-machine conflict.""" class MPValidationError(MercadoPagoError): """HTTP 422 Unprocessable Entity β€” business-rule violation.""" class MPResourceLockedError(MercadoPagoError): """HTTP 423 Locked β€” idempotency key temporarily locked (retryable).""" class MPDependencyError(MercadoPagoError): """HTTP 424 Failed Dependency β€” internal dependency failure (retryable).""" class MPRateLimitError(MercadoPagoError): """HTTP 429 Too Many Requests. Attributes: retry_after: Seconds to wait before retrying, from the ``Retry-After`` header, or ``None`` if absent. """ def __init__(self, status_code, response_body, retry_after=None): super().__init__(status_code, response_body) self.retry_after = retry_after class MPServerError(MercadoPagoError): """HTTP 5xx Server Error.""" class MPConnectionError(MercadoPagoError): """Transport-level or network error (timeout, DNS failure, SSL error). *status_code* is set to ``0`` to indicate no HTTP response was received. """ def __init__(self, cause): super().__init__(0, {"message": str(cause), "error": "connection_error"}) self.__cause__ = cause _STATUS_MAP = { 400: MPBadRequestError, 401: MPAuthenticationError, 402: MPPaymentError, 403: MPForbiddenError, 404: MPNotFoundError, 409: MPIdempotencyError, 422: MPValidationError, 423: MPResourceLockedError, 424: MPDependencyError, 429: MPRateLimitError, } def build_error(status_code, response_body, retry_after=None): """Factory: maps an HTTP status code to the most specific exception subtype. Args: status_code: HTTP status code from the API response. response_body: Parsed JSON response body dict. retry_after: Seconds from the ``Retry-After`` header (only for 429). Returns: MercadoPagoError: The appropriate subtype instance. """ cls = _STATUS_MAP.get(status_code) if cls is MPRateLimitError: return MPRateLimitError(status_code, response_body, retry_after) if cls is not None: return cls(status_code, response_body) if status_code >= 500: return MPServerError(status_code, response_body) return MercadoPagoError(status_code, response_body) mercadopago-sdk-python-b345a69/mercadopago/errors/response.py000066400000000000000000000064151524412155200244440ustar00rootroot00000000000000"""MPResponse β€” backward-compatible dict wrapper with typed error support. Wraps the raw ``{"status": ..., "response": ...}`` dict returned by every :class:`~mercadopago.core.mp_base.MPBase` helper. Existing code that reads ``result["status"]`` or ``result["response"]`` continues to work unchanged; new code may call :meth:`raise_for_status` to get a typed exception instead of checking ``result["status"]`` manually. """ from .exceptions import build_error class MPResponse(dict): """Dictionary subclass for MercadoPago API responses. All :class:`~mercadopago.core.mp_base.MPBase` methods return an instance of this class. It behaves identically to a plain ``dict`` so existing code remains unaffected. Example: Existing usage (unchanged):: result = sdk.payment().get(123) print(result["status"]) # 200 print(result["response"]["status"]) # "approved" New typed usage:: result = sdk.payment().get(123) result.raise_for_status() # raises MPNotFoundError if 404 Attributes: status_code: HTTP status code (alias for ``self["status"]``). is_success: True when the status code is 2xx. """ def __init__(self, raw, request_id=None): """Wraps a raw response dict. Args: raw: Dict with ``"status"`` (int) and ``"response"`` keys. request_id: Value of the ``x-request-id`` response header, used for support diagnostics. """ super().__init__(raw) self._request_id = request_id # ── Convenience properties ──────────────────────────────────────────────── @property def status_code(self): """HTTP status code integer.""" return self.get("status", 0) @property def is_success(self): """True for 2xx status codes.""" return 200 <= self.status_code < 300 @property def error_message(self): """Human-readable error message from the API body, or empty string.""" body = self.get("response") or {} if isinstance(body, dict): return body.get("message", "") return "" @property def error_causes(self): """List of cause dicts from the API body, or empty list.""" body = self.get("response") or {} if isinstance(body, dict): return body.get("cause", []) return [] @property def request_id(self): """``x-request-id`` header value for support diagnosis, or None.""" return self._request_id # ── Error raising ───────────────────────────────────────────────────────── def raise_for_status(self): """Raises a typed :class:`~mercadopago.errors.exceptions.MercadoPagoError` if the response status code indicates an error. Raises: MercadoPagoError (or subtype): When status >= 300. """ if not self.is_success: body = self.get("response") or {} err = build_error(self.status_code, body) err.request_id = self._request_id raise err mercadopago-sdk-python-b345a69/mercadopago/examples/000077500000000000000000000000001524412155200225305ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/invoice/000077500000000000000000000000001524412155200241645ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/invoice/get_invoice.py000066400000000000000000000014441524412155200270340ustar00rootroot00000000000000from mercadopago import SDK def main(): # Initialize the SDK with your access token access_token = "" sdk = SDK(access_token) # Search invoices for a specific subscription (preapproval) filters = { "preapproval_id": "", "limit": 10, } try: invoices = sdk.invoice().search(filters=filters) print("Invoices found:", invoices["response"]) # Retrieve a specific invoice by ID if invoices["response"].get("results"): invoice_id = invoices["response"]["results"][0]["id"] invoice = sdk.invoice().get(invoice_id) print("Invoice details:", invoice["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/oauth/000077500000000000000000000000001524412155200236505ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/oauth/create_token.py000066400000000000000000000017421524412155200266710ustar00rootroot00000000000000from mercadopago import SDK def main(): # Initialize the SDK with your marketplace access token access_token = "" sdk = SDK(access_token) # Step 1: Build the authorization URL and redirect the seller to it auth_url = sdk.oauth().get_authorization_url( app_id="", redirect_uri="https://yourapp.com/callback", random_id="", ) print("Redirect seller to:", auth_url) # Step 2: After the seller authorizes, exchange the received code for tokens oauth_object = { "client_secret": access_token, "code": "", "redirect_uri": "https://yourapp.com/callback", "grant_type": "authorization_code", } try: response = sdk.oauth().create(oauth_object) print("Token created successfully:", response["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/order/000077500000000000000000000000001524412155200236435ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/order/cancel_order.py000066400000000000000000000035271524412155200266440ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "capture_mode": "manual", "processing_mode": "automatic", "total_amount": "880.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "880.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully") # Get the order ID from the response order_id = response["response"]["id"] time.sleep(5) # Call the method to CANCEL order_details = sdk.order().cancel(order_id) print("Order details:", order_details["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/capture_order.py000066400000000000000000000035611524412155200270600ustar00rootroot00000000000000import os from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "capture_mode": "manual", # Mode need to be Manual to use Capture Method. "processing_mode": "automatic", "total_amount": "880.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "880.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully") # Get the order ID from the response order_id = response["response"]["id"] # Call the method to CAPTURE the order order_details = sdk.order().capture(order_id) print("Order details:", order_details["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/create_order.py000066400000000000000000000030021524412155200266460ustar00rootroot00000000000000from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "total_amount": "880.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "880.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully:", response["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/create_order_checkout_pro.py000066400000000000000000000136611524412155200314270ustar00rootroot00000000000000"""Mercado Pago - Create Order for Checkout Pro. Checkout Pro through Orders uses ``type="online"`` and ``processing_mode="manual"``. The API returns ``checkout_url`` in the created order response; redirect the buyer to that URL to continue the payment flow. """ from mercadopago import SDK from mercadopago.resources.order_checkout_pro import ( OrderCheckoutProConfig, OrderCheckoutProDict, OrderCheckoutProInstallments, OrderCheckoutProInterestFree, OrderCheckoutProOnlineConfig, OrderCheckoutProPaymentMethod, OrderCheckoutProTrack, ) def main(): access_token = "" sdk = SDK(access_token) checkout_pro_config = OrderCheckoutProConfig( statement_descriptor="MYSTORE", default_payment_due_date="P1D", online=OrderCheckoutProOnlineConfig( available_from="2026-01-01T00:00:00Z", allowed_user_type="account_only", success_url="https://example.com/success", failure_url="https://example.com/failure", pending_url="https://example.com/pending", auto_return="approved", tracks=[ OrderCheckoutProTrack( type="google_ad", values={ "conversion_id": "21312312312123", "conversion_label": "TEST", }, ), OrderCheckoutProTrack( type="facebook_ad", values={"pixel_id": "21312312312123"}, ), ], ), payment_method=OrderCheckoutProPaymentMethod( max_installments=12, not_allowed_ids=["amex"], not_allowed_types=["ticket"], installments=OrderCheckoutProInstallments( interest_free=OrderCheckoutProInterestFree( type="range", values=[2, 6], ), ), ), ) order_object = { "type": "online", "total_amount": "500.00", "external_reference": "ext_ref_checkout_pro", "processing_mode": "manual", "capture_mode": "automatic", "marketplace_fee": "5.00", "description": "Travel package SAO-RIO with insurance", "expiration_time": "P1D", "payer": { "email": "", "first_name": "", "last_name": "", "phone": { "area_code": "11", "number": "999998888", }, "identification": { "type": "CPF", "number": "", }, "address": { "zip_code": "01310-100", "street_name": "Av. Paulista", "street_number": "1000", "neighborhood": "Bela Vista", "city": "Sao Paulo", }, }, "shipment": { "mode": "custom", "local_pickup": False, "cost": "15.00", "free_shipping": False, "free_methods": [{"id": 73328}], "address": { "zip_code": "01310-100", "street_name": "Av. Paulista", "street_number": "1000", "floor": "3", "apartment": "B", "neighborhood": "Bela Vista", "city": "Sao Paulo", }, }, "config": OrderCheckoutProDict(checkout_pro_config), "items": [ { "external_code": "ITEM-001", "title": "Flight SAO-RIO", "description": "Round trip, economy class", "category_id": "travels", "picture_url": "https://example.com/img.jpg", "quantity": 1, "unit_price": "450.00", "type": "travel", "event_date": "2027-01-15T00:00:00.000-03:00", }, { "external_code": "ITEM-002", "title": "Travel insurance", "description": "Basic coverage during trip", "category_id": "travels", "picture_url": "https://example.com/insurance.jpg", "quantity": 1, "unit_price": "50.00", "type": "travel", "event_date": "2027-01-15T00:00:00.000-03:00", }, ], # Orders accepts vertical data with dotted keys under additional_info. "additional_info": { "payer.registration_date": "2020-01-15T00:00:00.000-03:00", "payer.authentication_type": "MOBILE", "payer.is_prime_user": True, "payer.is_first_purchase_online": True, "payer.last_purchase": "2025-12-01T00:00:00.000-03:00", "travel.passengers": [ { "first_name": "", "last_name": "", "identification_type": "CPF", "identification_number": "", "item_references": ["ITEM-001"], } ], "travel.routes": [ { "departure": "SAO", "destination": "RIO", "departure_date_time": "2026-03-10T08:00:00.000-03:00", "arrival_date_time": "2026-03-10T09:00:00.000-03:00", "company": "TAM", "item_references": ["ITEM-001"], } ], }, } try: response = sdk.order().create(order_object) order = response["response"] print("Order created successfully:") print("id:", order.get("id")) print("status:", order.get("status")) print("checkout_url:", order.get("checkout_url")) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/order/create_order_pse.py000066400000000000000000000060111524412155200275200ustar00rootroot00000000000000""" Mercado Pago - Create Order with PSE (Pagos Seguros en Linea - Colombia). PSE is Colombia's standard online bank-transfer payment method. The integrator initiates the transaction with payment_method.id = "pse" and type = "bank_transfer", and must specify the buyer's bank via financial_institution. Required PSE-specific fields: - payment_method.id = "pse" (fixed) - payment_method.type = "bank_transfer" (fixed) - payment_method.financial_institution = PSE bank code (see table below) - currency = "COP" (Colombia only) - payer.entity_type = "individual" or "association" - payer.identification.type = "CC", "NIT", etc. (Colombian doc type) - additional_info.payer.ip_address (required by risk engine) - config.online.callback_url (URL the bank redirects to after authorization) Most-used PSE bank codes (full catalog via MP API): Bancolombia ........... 1007 Davivienda ............ 1051 Banco de Bogota ....... 1001 BBVA Colombia ......... 1013 Banco Popular ......... 1002 Scotiabank Colpatria .. 1019 Reference: https://www.mercadopago.com.co/developers/es/docs """ from mercadopago import SDK def main(): access_token = "" sdk = SDK(access_token) order_object = { "type": "online", "processing_mode": "automatic", "total_amount": "50000.00", "currency": "COP", "external_reference": "ref_pse_12345", "transactions": { "payments": [ { "amount": "50000.00", # PSE payment: id="pse", type="bank_transfer", financial_institution = bank code. "payment_method": { "id": "pse", "type": "bank_transfer", "financial_institution": "1007" # Bancolombia } } ] }, # Payer: entity_type + Colombian identification (CC/NIT) required for PSE. "payer": { "entity_type": "individual", "email": "", "first_name": "", "last_name": "", "identification": { "type": "CC", "number": "" } }, # additional_info.payer.ip_address - required by MP's risk engine for PSE. "additional_info": { "payer": { "ip_address": "" } }, # callback_url - where the bank redirects the buyer after authorization. "config": { "online": { "callback_url": "" } } } try: response = sdk.order().create(order_object) print("Order created successfully:", response["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/order/create_transaction.py000066400000000000000000000035561524412155200300760ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "manual", "total_amount": "200.00", "external_reference": "ext_ref_1234", "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully") # Get the order ID from the response order_id = response["response"]["id"] transaction_object = { "payments": [ { "amount": "200.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 12 } } ] } # Call the method to CREATE A TRANSACTION in the order transaction_created = sdk.order().create_transaction(order_id, transaction_object) print("Transaction created:", transaction_created["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/delete_transaction.py000066400000000000000000000037061524412155200300720ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "manual", "total_amount": "200.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "200.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 12 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully") # Get the order ID from the response order_id = response["response"]["id"] transaction_id = response["response"]["transactions"]["payments"][0]["id"] # Call the method to DELETE the transaction in the order transaction_deleted = sdk.order().delete_transaction(order_id, transaction_id) print("Transaction Successful Deleted.", transaction_deleted["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/get_order.py000066400000000000000000000033701524412155200261720ustar00rootroot00000000000000import os from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "total_amount": "880.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "880.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully!") # Get the order ID from the response order_id = response["response"]["id"] # Call the method to get the order details order_details = sdk.order().get(order_id) print("Order details:", order_details["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/process_order.py000066400000000000000000000036111524412155200270670ustar00rootroot00000000000000import os from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "manual", # Mode need to be Manual to use Process Method. "total_amount": "880.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "880.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully!") # Get the order ID from the response order_id = response["response"]["id"] print("Order ID:", order_id) # Call the method to PROCESS the order created in Manual Mode order_details = sdk.order().process(order_id) print("Order details:", order_details["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/refund_partial.py000066400000000000000000000040371524412155200272200ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "automatic", "total_amount": "500.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "500.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully.") # Get the order ID from the response order_id = response["response"]["id"] refund = { "transactions": [ { "id": response["response"]["transactions"]["payments"][0]["id"], "amount": "25.00" } ] } # Call the method to REFUND transaction_refund = sdk.order().refund_transaction(order_id, refund) print("Transaction Partially Refunded:", transaction_refund["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/refund_total.py000066400000000000000000000035471524412155200267140ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "automatic", "total_amount": "500.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "500.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully.") # Get the order ID from the response order_id = response["response"]["id"] # Call the method to REFUND TOTALLY the transaction in the order transaction_refund = sdk.order().refund_transaction(order_id) print("Transaction Total Refunded:", transaction_refund["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/order/update_transaction.py000066400000000000000000000041241524412155200301050ustar00rootroot00000000000000import os import time from mercadopago import SDK def main(): # Define the authentication token access_token = "" # Define the authentication token sdk = SDK(access_token) # Create a test card token def create_test_card(): card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"} } card_token_created = sdk.card_token().create(card_token_object) return card_token_created["response"]["id"] # Create an order object card_token_id = create_test_card() order_object = { "type": "online", "processing_mode": "manual", "total_amount": "500.00", "external_reference": "ext_ref_1234", "transactions": { "payments": [ { "amount": "500.00", "payment_method": { "id": "master", "type": "credit_card", "token": card_token_id, "installments": 2 } } ] }, "payer": { "email": "" } } try: # Call the method to create the order response = sdk.order().create(order_object) print("Order created successfully") # Get the order ID from the response order_id = response["response"]["id"] transaction_id = response["response"]["transactions"]["payments"][0]["id"] transaction_update = { "payment_method": { "type": "credit_card", "installments": 5 } } # Call the method to UPDATE the transaction in the order update = sdk.order().update_transaction(order_id, transaction_id, transaction_update) print("Transaction Updated:", update["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main()mercadopago-sdk-python-b345a69/mercadopago/examples/point/000077500000000000000000000000001524412155200236615ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/point/create_payment_intent.py000066400000000000000000000020271524412155200306150ustar00rootroot00000000000000from mercadopago import SDK def main(): # Initialize the SDK with your access token access_token = "" sdk = SDK(access_token) # List available Point devices to get a device_id devices = sdk.point().get_devices() print("Available devices:", devices["response"]) # Create a payment intent on a specific device device_id = "" payment_intent_object = { "amount": 1500, "description": "Product purchase", "payment": { "installments": 1, "type": "credit_card", }, } try: response = sdk.point().create(device_id, payment_intent_object) print("Payment intent created:", response["response"]) # Retrieve the payment intent status payment_intent_id = response["response"]["id"] status = sdk.point().get(payment_intent_id) print("Payment intent status:", status["response"]) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/preference/000077500000000000000000000000001524412155200246465ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/examples/preference/create_preference.py000066400000000000000000000050211524412155200306570ustar00rootroot00000000000000from mercadopago.sdk import SDK def main(): # Define the authentication token access_token = "" sdk = SDK(access_token) try: preference_data = { "items": [ { "title": "Dummy Item", "quantity": 1, "unit_price": 10.0, "warranty": False, "type": "default", "event_date": "2027-01-15T00:00:00.000-03:00", "category_descriptor": { "passenger": { "first_name": "", "last_name": "", "identification": { "type": "CPF", "number": "" } }, "route": { "departure": "SAO", "destination": "RIO", "departure_date_time": "2027-01-15T08:00:00.000-03:00", "arrival_date_time": "2027-01-15T09:00:00.000-03:00", "company": "TAM" } } } ], "payer": { "email": "", "date_created": "2020-01-15T00:00:00.000-03:00", "authentication_type": "MOBILE", "is_prime_user": False, "is_first_purchase_online": False, "last_purchase": "2025-12-01T00:00:00.000-03:00", "registration_date": "2020-01-15T00:00:00.000-03:00" }, "shipments": { "receiver_address": { "street_name": "Av. Paulista", "street_number": 1000, "zip_code": "01310-100", "state_name": "Sao Paulo", "city_name": "Sao Paulo", "floor": "3", "apartment": "B" }, "express_shipment": False, "local_pickup": False }, "notification_url": "https://webhook.site/test-notification" } # Call the method to create the preference preference = sdk.preference().create(preference_data) print(preference) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/examples/preference/create_with_industry_fields.py000066400000000000000000000123661524412155200330150ustar00rootroot00000000000000# Example: Preference with industry data fields for payment approval improvement from mercadopago.sdk import SDK def main(): # Define the authentication token access_token = "" sdk = SDK(access_token) try: preference_data = { "items": [ { "id": "FLIGHT-001", "title": "Flight SAO-RIO", "description": "Round trip, economy class", "picture_url": "https://example.com/flight.jpg", "category_id": "travels", "quantity": 1, "currency_id": "BRL", "unit_price": 450.00, "warranty": False, "type": "travel", "event_date": "2027-01-15T08:00:00.000-03:00", "category_descriptor": { "passenger": { "first_name": "", "last_name": "", "identification": { "type": "CPF", "number": "" } }, "route": { "departure": "SAO", "destination": "RIO", "departure_date_time": "2027-01-15T08:00:00.000-03:00", "arrival_date_time": "2027-01-15T09:00:00.000-03:00", "company": "TAM" } } }, { "id": "INSURANCE-001", "title": "Travel Insurance", "description": "Basic coverage during trip", "picture_url": "https://example.com/insurance.jpg", "category_id": "travels", "quantity": 1, "currency_id": "BRL", "unit_price": 50.00, "warranty": True, "type": "travel", "event_date": "2027-01-15T08:00:00.000-03:00", "category_descriptor": { "passenger": { "first_name": "", "last_name": "", "identification": { "type": "CPF", "number": "" } }, "route": { "departure": "SAO", "destination": "RIO", "departure_date_time": "2027-01-15T08:00:00.000-03:00", "arrival_date_time": "2027-01-15T09:00:00.000-03:00", "company": "TAM" } } } ], "payer": { "email": "", "name": "", "surname": "", "date_created": "2020-01-15T00:00:00.000-03:00", "authentication_type": "MOBILE", "is_prime_user": True, "is_first_purchase_online": False, "last_purchase": "2025-12-01T00:00:00.000-03:00", "registration_date": "2020-01-15T00:00:00.000-03:00", "phone": { "area_code": "11", "number": "999998888" }, "identification": { "type": "CPF", "number": "" }, "address": { "zip_code": "01310-100", "street_name": "Av. Paulista", "street_number": "1000" } }, "shipments": { "mode": "custom", "receiver_address": { "street_name": "Av. Paulista", "street_number": "1000", "zip_code": "01310-100", "state_name": "Sao Paulo", "city_name": "Sao Paulo", "floor": "3", "apartment": "B" }, "express_shipment": False, "local_pickup": False }, "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "auto_return": "approved", "external_reference": "TRAVEL-BOOKING-001", "notification_url": "https://example.com/notifications" } # Call the method to create the preference preference = sdk.preference().create(preference_data) print("Preference created successfully:") print("id:", preference["response"].get("id")) print("init_point:", preference["response"].get("init_point")) except Exception as e: print("Error:", e) if __name__ == "__main__": main() mercadopago-sdk-python-b345a69/mercadopago/http/000077500000000000000000000000001524412155200216715ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/http/__init__.py000066400000000000000000000004171524412155200240040ustar00rootroot00000000000000"""HTTP transport layer for the MercadoPago SDK. Exposes :class:`HttpClient`, the default ``requests``-based implementation used to execute REST calls against the MercadoPago API. """ from mercadopago.http.http_client import HttpClient __all__ = ( 'HttpClient', ) mercadopago-sdk-python-b345a69/mercadopago/http/http_client.py000066400000000000000000000115171524412155200245650ustar00rootroot00000000000000"""HTTP client implementation backed by the ``requests`` library. Provides automatic retry with exponential back-off for transient server errors (429, 500, 502, 503, 504) using ``urllib3.util.Retry``. """ # pylint: disable=too-many-arguments import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry from mercadopago.config.defaults import DEFAULT_RETRY_ON class HttpClient: """Default HTTP transport for all MercadoPago REST calls. Each call creates a fresh ``requests.Session`` with a retry-aware HTTPS adapter, executes the request, and returns a normalised response dict. The response format returned by every method is:: {"status": , "response": } where *status* is the HTTP status code and *response* is the parsed JSON body (``None`` for 204 No Content or unparseable bodies). """ def request( # pylint: disable=too-many-positional-arguments self, method, url, maxretries=None, retry_on=None, backoff_factor=None, **kwargs, ): """Executes an HTTP request with automatic retry. A new session with an HTTPS retry adapter is created per call so that retry state does not leak between requests. Args: method: HTTP verb (``GET``, ``POST``, ``PUT``, ``DELETE``). url: Fully-qualified URL to call. maxretries: Maximum number of retries on transient errors. retry_on: HTTP status codes to retry. Defaults to DEFAULT_RETRY_ON. backoff_factor: urllib3 backoff_factor in seconds (None = no extra delay). **kwargs: Forwarded to ``requests.Session.request`` (headers, data, params, timeout, etc.). Returns: dict: ``{"status": , "response": }``. Raises: MPServerError: When the response body cannot be parsed as JSON (previously a silent failure). """ from mercadopago.errors.exceptions import MPServerError # avoid circular import retry_strategy = Retry( total=maxretries, status_forcelist=retry_on if retry_on is not None else DEFAULT_RETRY_ON, backoff_factor=backoff_factor if backoff_factor is not None else 0, ) http = requests.Session() http.mount("https://", HTTPAdapter(max_retries=retry_strategy)) with http as session: api_result = session.request(method, url, **kwargs) response = {"status": api_result.status_code, "response": None} if api_result.status_code != 204 and api_result.content: try: response["response"] = api_result.json() except ValueError as exc: raise MPServerError( api_result.status_code, {"message": "Invalid JSON in response body", "error": "invalid_response"}, ) from exc return response def get(self, url, headers, params=None, timeout=None, maxretries=None, # pylint: disable=too-many-positional-arguments retry_on=None, backoff_factor=None): """Sends a GET request to the MercadoPago API.""" return self.request( "GET", url=url, headers=headers, params=params, timeout=timeout, maxretries=maxretries, retry_on=retry_on, backoff_factor=backoff_factor, ) def post(self, url, headers, data=None, params=None, timeout=None, maxretries=None, # pylint: disable=too-many-positional-arguments retry_on=None, backoff_factor=None): """Sends a POST request to the MercadoPago API.""" return self.request( "POST", url=url, headers=headers, data=data, params=params, timeout=timeout, maxretries=maxretries, retry_on=retry_on, backoff_factor=backoff_factor, ) def put(self, url, headers, data=None, params=None, timeout=None, maxretries=None, # pylint: disable=too-many-positional-arguments retry_on=None, backoff_factor=None): """Sends a PUT request to the MercadoPago API.""" return self.request( "PUT", url=url, headers=headers, data=data, params=params, timeout=timeout, maxretries=maxretries, retry_on=retry_on, backoff_factor=backoff_factor, ) def delete(self, url, headers, params=None, timeout=None, maxretries=None, # pylint: disable=too-many-positional-arguments retry_on=None, backoff_factor=None): """Sends a DELETE request to the MercadoPago API.""" return self.request( "DELETE", url=url, headers=headers, params=params, timeout=timeout, maxretries=maxretries, retry_on=retry_on, backoff_factor=backoff_factor, ) mercadopago-sdk-python-b345a69/mercadopago/pagination/000077500000000000000000000000001524412155200230435ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/pagination/__init__.py000066400000000000000000000002641524412155200251560ustar00rootroot00000000000000"""Pagination utilities for the MercadoPago Python SDK.""" from .iterator import search_auto_paging_iter from .page import Paging __all__ = ["search_auto_paging_iter", "Paging"] mercadopago-sdk-python-b345a69/mercadopago/pagination/iterator.py000066400000000000000000000040301524412155200252430ustar00rootroot00000000000000"""Auto-paging iterator for MercadoPago search resources. Creates a lazy generator that fetches pages of results on demand so callers can iterate over every matching item without managing offsets. Example: :: for payment in sdk.payment().search_auto_paging_iter({"status": "approved"}): process(payment) """ from .page import Paging def search_auto_paging_iter(search_fn, filters=None, request_options=None, limit=100): """Lazy generator that auto-fetches all pages of a search result. Yields individual items (dicts) from successive paginated API calls. The original ``search()`` method is called once per page; iteration stops when the results list is empty or the offset reaches the total. Args: search_fn: Callable matching ``search(filters, request_options) -> MPResponse``. filters: Initial search filters dict. ``limit`` and ``offset`` are managed automatically β€” callers should NOT include them here. request_options: Per-request overrides forwarded to each page call. limit: Items per page. Defaults to 100. Yields: dict: Individual result items from each page. """ filters = dict(filters or {}) filters.setdefault("limit", limit) filters["offset"] = filters.get("offset", 0) offset = filters["offset"] while True: filters["offset"] = offset result = search_fn(filters, request_options) body = result.get("response") or {} # Support different response key conventions: # - "results" β†’ payments, customers, preapprovals, preferences, etc. # - "data" β†’ Orders v2 API # - "elements" β†’ some Order patterns (Pattern B) items = (body.get("results") or body.get("data") or body.get("elements") or []) paging = Paging.from_dict(body.get("paging")) if not items: return yield from items offset += len(items) if paging.total and offset >= paging.total: return mercadopago-sdk-python-b345a69/mercadopago/pagination/page.py000066400000000000000000000013631524412155200243340ustar00rootroot00000000000000"""Pagination helpers for MercadoPago search results.""" class Paging: """Pagination metadata extracted from a search response.""" def __init__(self, total=0, limit=0, offset=0): self.total = total self.limit = limit self.offset = offset @classmethod def from_dict(cls, d): if not d: return cls() # Orders API returns total/limit/offset as strings; other APIs as ints def _int(v, default=0): try: return int(v) except (TypeError, ValueError): return default return cls( total=_int(d.get("total"), 0), limit=_int(d.get("limit"), 0), offset=_int(d.get("offset"), 0), ) mercadopago-sdk-python-b345a69/mercadopago/resources/000077500000000000000000000000001524412155200227245ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/resources/__init__.py000066400000000000000000000075211524412155200250420ustar00rootroot00000000000000"""MercadoPago API resource classes. Each class maps to a MercadoPago REST API domain (payments, orders, customers, etc.) and exposes CRUD and action methods. All resources extend :class:`~mercadopago.core.mp_base.MPBase`. """ from mercadopago.config.request_options import RequestOptions from mercadopago.http.http_client import HttpClient from mercadopago.resources.advanced_payment import AdvancedPayment from mercadopago.resources.card import Card from mercadopago.resources.card_token import CardToken from mercadopago.resources.chargeback import Chargeback from mercadopago.resources.customer import Customer from mercadopago.resources.disbursement_refund import DisbursementRefund from mercadopago.resources.identification_type import IdentificationType from mercadopago.resources.invoice import Invoice from mercadopago.resources.item import ItemRequest from mercadopago.resources.merchant_order import MerchantOrder from mercadopago.resources.oauth import OAuth from mercadopago.resources.order import Order from mercadopago.resources.order_automatic_payments import OrderAutomaticPayments from mercadopago.resources.order_checkout_pro import ( OrderCheckoutProConfig, OrderCheckoutProDict, OrderCheckoutProInstallments, OrderCheckoutProInterestFree, OrderCheckoutProOnlineConfig, OrderCheckoutProPaymentMethod, OrderCheckoutProTrack, ) from mercadopago.resources.order_create import ( OrderCreateRequest, order_request_to_dict, ) from mercadopago.resources.order_integration_data import ( OrderIntegrationData, OrderSponsor, ) from mercadopago.resources.order_stored_credential import OrderStoredCredential from mercadopago.resources.order_subscription_data import ( OrderInvoicePeriod, OrderSubscriptionData, OrderSubscriptionSequence, ) from mercadopago.resources.order_transaction import ( OrderPaymentMethodRequest, OrderPaymentRequest, OrderTransactionRequest, ) from mercadopago.resources.order_transaction_security import OrderTransactionSecurity from mercadopago.resources.payer import ( PayerAddress, PayerIdentification, PayerPhone, PayerRequest, ) from mercadopago.resources.payment import Payment from mercadopago.resources.payment_methods import PaymentMethods from mercadopago.resources.plan import Plan from mercadopago.resources.point import Point from mercadopago.resources.preapproval import PreApproval from mercadopago.resources.preference import Preference from mercadopago.resources.refund import Refund from mercadopago.resources.shipment import ( ShipmentAddress, ShipmentFreeMethod, ShipmentRequest, ) from mercadopago.resources.subscription import Subscription from mercadopago.resources.user import User __all__ = ( 'AdvancedPayment', 'Card', 'CardToken', 'Chargeback', 'Customer', 'DisbursementRefund', 'HttpClient', 'IdentificationType', 'Invoice', 'MerchantOrder', 'OAuth', 'Order', 'OrderAutomaticPayments', 'OrderCheckoutProConfig', 'OrderCheckoutProInstallments', 'OrderCheckoutProInterestFree', 'OrderCheckoutProOnlineConfig', 'OrderCheckoutProPaymentMethod', 'OrderCheckoutProTrack', 'OrderCheckoutProDict', 'OrderCreateRequest', 'OrderIntegrationData', 'OrderInvoicePeriod', 'ItemRequest', 'PayerAddress', 'PayerIdentification', 'PayerPhone', 'PayerRequest', 'ShipmentAddress', 'ShipmentFreeMethod', 'ShipmentRequest', 'OrderSponsor', 'OrderStoredCredential', 'OrderSubscriptionData', 'OrderSubscriptionSequence', 'OrderPaymentMethodRequest', 'OrderPaymentRequest', 'OrderTransactionRequest', 'OrderTransactionSecurity', 'Payment', 'PaymentMethods', 'Plan', 'Point', 'PreApproval', 'Preference', 'Refund', 'RequestOptions', 'Subscription', 'User', 'order_request_to_dict', ) mercadopago-sdk-python-b345a69/mercadopago/resources/advanced_payment.py000066400000000000000000000134361524412155200266070ustar00rootroot00000000000000"""Advanced Payment resource for the MercadoPago Marketplace API. Wraps ``/v1/advanced_payments`` endpoints used in marketplace split-payment scenarios where funds are distributed among multiple receivers. `API reference `_ (advanced_payments section not found in current reference) """ from datetime import datetime from mercadopago.core import MPBase class AdvancedPayment(MPBase): """Manages split payments in marketplace integrations. Advanced payments allow a marketplace to collect a payment and split it among multiple sellers in a single transaction. Supports two-step flows (authorise then capture) and individual disbursement release-date control. """ def search(self, filters=None, request_options=None): """Searches advanced payments matching the given filters. Args: filters: Query-string parameters. request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching advanced payments. """ return self._get( uri="/v1/advanced_payments/search", filters=filters, request_options=request_options, ) def get(self, advanced_payment_id, request_options=None): """Retrieves an advanced payment by its ID. Args: advanced_payment_id: Unique advanced payment identifier. request_options: Per-call configuration overrides. Returns: dict: Full advanced payment object. """ return self._get(uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id), request_options=request_options) def create(self, advanced_payment_object, request_options=None): """Creates a new advanced (split) payment. Args: advanced_payment_object: Dict describing the payment including ``disbursements`` (list of receiver/amount pairs). request_options: Per-call configuration overrides. Raises: ValueError: If *advanced_payment_object* is not a ``dict``. Returns: dict: Created advanced payment including its ``id``. """ if not isinstance(advanced_payment_object, dict): raise ValueError( "Param advanced_payment_object must be a Dictionary") return self._post(uri="/v1/advanced_payments", data=advanced_payment_object, request_options=request_options) def capture(self, advanced_payment_id, request_options=None): """Captures a previously authorised advanced payment. Sends ``{"capture": true}`` to finalise a two-step payment flow. Args: advanced_payment_id: Identifier of the payment to capture. request_options: Per-call configuration overrides. Returns: dict: Captured advanced payment with updated status. """ capture_object = {"capture": True} return self._put(uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id), data=capture_object, request_options=request_options) def update(self, advanced_payment_id, advanced_payment_object, request_options=None): """Updates an existing advanced payment. Args: advanced_payment_id: Identifier of the payment to update. advanced_payment_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *advanced_payment_object* is not a ``dict``. Returns: dict: Updated advanced payment object. """ if not isinstance(advanced_payment_object, dict): raise ValueError( "Param advanced_payment_object must be a Dictionary") return self._put(uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id), data=advanced_payment_object, request_options=request_options) def cancel(self, advanced_payment_id, request_options=None): """Cancels an advanced payment. Sets the payment status to ``cancelled``. Only payments that have not yet been captured can be cancelled. Args: advanced_payment_id: Identifier of the payment to cancel. request_options: Per-call configuration overrides. Returns: dict: Cancelled advanced payment with updated status. """ cancel_object = {"status": "cancelled"} return self._put(uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id), data=cancel_object, request_options=request_options) def update_release_date(self, advanced_payment_id, release_date, request_options=None): """Changes the money release date for disbursements. Allows the marketplace to control when funds become available to sellers. Args: advanced_payment_id: Identifier of the advanced payment. release_date: New release ``datetime`` for the disbursements. request_options: Per-call configuration overrides. Raises: ValueError: If *release_date* is not a ``datetime`` instance. Returns: dict: Updated disbursement schedule response. """ if not isinstance(release_date, datetime): raise ValueError("Param release_date must be a DateTime") disbursement_object = { "money_release_date": release_date.strftime("%Y-%m-%d %H:%M:%S.%f")} return self._post( uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id) + "/disburses", data=disbursement_object, request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/card.py000066400000000000000000000107601524412155200242130ustar00rootroot00000000000000"""Saved-card resource for the MercadoPago API. Wraps ``/v1/customers/{self._path_param(customer_id)}/cards`` endpoints to list, retrieve, create, update, and delete cards stored against a customer profile. `API reference `_ """ from mercadopago.core import MPBase class Card(MPBase): """Manages saved payment cards linked to a :class:`Customer`. Storing cards lets returning buyers complete checkout without re-entering card details. Every method requires the owning *customer_id*. """ def list_all(self, customer_id, request_options=None): """Lists all cards saved for a customer. Args: customer_id: Owner customer identifier. request_options: Per-call configuration overrides. Returns: dict: List of saved card objects. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cards/get-customer-cards/get """ return self._get( uri=f"/v1/customers/{self._path_param(customer_id)}/cards", request_options=request_options, ) def get(self, customer_id, card_id, request_options=None): """Retrieves a single saved card. Args: customer_id: Owner customer identifier. card_id: Identifier of the card to retrieve. request_options: Per-call configuration overrides. Returns: dict: Full card object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cards/get-card/get """ return self._get( uri=f"/v1/customers/{self._path_param(customer_id)}/cards/{self._path_param(card_id)}", request_options=request_options, ) def create(self, customer_id, card_object, request_options=None): """Saves a new card for a customer. The *card_object* typically contains a ``token`` obtained via the MercadoPago JS SDK or Card Token API. Args: customer_id: Owner customer identifier. card_object: Dict with card data (``token`` is required). request_options: Per-call configuration overrides. Raises: ValueError: If *card_object* is not a ``dict``. Returns: dict: Created card including its ``id``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cards/save-card/post """ if not isinstance(card_object, dict): raise ValueError("Param card_object must be a Dictionary") return self._post(uri="/v1/customers/" + self._path_param(customer_id) + "/cards/", data=card_object, request_options=request_options) def update(self, customer_id, card_id, card_object, request_options=None): """Updates a saved card's details. Args: customer_id: Owner customer identifier. card_id: Identifier of the card to update. card_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *card_object* is not a ``dict``. Returns: dict: Updated card object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cards/update-card/put """ if not isinstance(card_object, dict): raise ValueError("Param card_object must be a Dictionary") return self._put(uri="/v1/customers/" + self._path_param(customer_id) + "/cards/" + self._path_param(card_id), data=card_object, request_options=request_options) def delete(self, customer_id, card_id, request_options=None): """Deletes a saved card from a customer profile. Args: customer_id: Owner customer identifier. card_id: Identifier of the card to delete. request_options: Per-call configuration overrides. Returns: dict: Deletion confirmation response. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cards/delete-card/delete """ return self._delete( uri="/v1/customers/" + self._path_param(customer_id) + "/cards/" + self._path_param(card_id), request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/card_token.py000066400000000000000000000033301524412155200254060ustar00rootroot00000000000000"""Card Token resource for the MercadoPago API. Wraps ``/v1/card_tokens`` endpoints to tokenise raw card data server-side before creating a payment. The returned token is single-use and short-lived. """ from mercadopago.core import MPBase class CardToken(MPBase): """Tokenises card data for secure payment creation. Send raw card details (number, expiry, CVV) to obtain a one-time token that can be passed to :meth:`Payment.create` without exposing sensitive data in your own backend. """ def get(self, card_token_id, request_options=None): """Retrieves a card token by its ID. Args: card_token_id: Unique token identifier. request_options: Per-call configuration overrides. Returns: dict: Token metadata (last four digits, expiry, etc.). """ return self._get(uri="/v1/card_tokens/" + self._path_param(card_token_id), request_options=request_options) def create(self, card_token_object, request_options=None): """Creates a new card token from raw card data. Args: card_token_object: Dict with card details (card_number, expiration_month, expiration_year, security_code, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *card_token_object* is not a ``dict``. Returns: dict: Created token including its ``id``. """ if not isinstance(card_token_object, dict): raise ValueError("Param card_token_object must be a Dictionary") return self._post(uri="/v1/card_tokens", data=card_token_object, request_options=request_options) mercadopago-sdk-python-b345a69/mercadopago/resources/chargeback.py000066400000000000000000000027601524412155200253550ustar00rootroot00000000000000"""Chargeback resource for the MercadoPago API. Wraps ``/v1/chargebacks`` endpoints to search and retrieve chargeback records initiated by cardholders through their issuing bank. `API reference `_ """ from mercadopago.core import MPBase class Chargeback(MPBase): """Provides read access to chargeback disputes. Chargebacks are created by MercadoPago when a cardholder disputes a payment. Use :meth:`search` and :meth:`get` to monitor and respond to disputes. """ def search(self, filters=None, request_options=None): """Searches chargebacks matching the given filters. Args: filters: Query-string parameters (e.g. ``payment_id``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching chargebacks. """ return self._get(uri="/v1/chargebacks/search", filters=filters, request_options=request_options) def get(self, chargeback_id, request_options=None): """Retrieves a chargeback by its ID. Args: chargeback_id: Unique chargeback identifier. request_options: Per-call configuration overrides. Returns: dict: Full chargeback object including status and amounts. """ return self._get(uri="/v1/chargebacks/" + self._path_param(chargeback_id), request_options=request_options) mercadopago-sdk-python-b345a69/mercadopago/resources/customer.py000066400000000000000000000107151524412155200251430ustar00rootroot00000000000000"""Customer resource for the MercadoPago API. Wraps ``/v1/customers`` endpoints to search, retrieve, create, update, and delete customer records. Use alongside :class:`~mercadopago.resources.card.Card` to enable one-click payments for returning buyers. `API reference `_ """ from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class Customer(MPBase): """Stores and manages buyer profiles for faster checkout experiences. Customer records hold identification, email, and address data. Attach saved cards via the :class:`Card` resource to let returning buyers pay without re-entering card details. """ def search(self, filters=None, request_options=None): """Searches customers matching the given filters. Args: filters: Query-string parameters (e.g. ``email``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching customers. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/customers/search-customer/get """ return self._get(uri="/v1/customers/search", filters=filters, request_options=request_options) def get(self, customer_id, request_options=None): """Retrieves a customer by their ID. Args: customer_id: Unique customer identifier. request_options: Per-call configuration overrides. Returns: dict: Full customer object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/customers/get-customer/get """ return self._get( uri="/v1/customers/" + self._path_param(customer_id), request_options=request_options, ) def create(self, customer_object, request_options=None): """Creates a new customer record. Args: customer_object: Dict with customer data (email, first_name, last_name, identification, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *customer_object* is not a ``dict``. Returns: dict: Created customer including its ``id``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/customers/create-customer/post """ if not isinstance(customer_object, dict): raise ValueError("Param customer_object must be a Dictionary") return self._post(uri="/v1/customers", data=customer_object, request_options=request_options) def update(self, customer_id, customer_object, request_options=None): """Updates an existing customer. Args: customer_id: Identifier of the customer to update. customer_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *customer_object* is not a ``dict``. Returns: dict: Updated customer object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/customers/update-customer/put """ if not isinstance(customer_object, dict): raise ValueError("Param customer_object must be a Dictionary") return self._put(uri="/v1/customers/" + self._path_param(customer_id), data=customer_object, request_options=request_options) def delete(self, customer_id, request_options=None): """Deletes a customer record. Args: customer_id: Identifier of the customer to delete. request_options: Per-call configuration overrides. Returns: dict: Deletion confirmation response. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/customers/get-customer/get """ return self._delete(uri="/v1/customers/" + self._path_param(customer_id), request_options=request_options) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/disbursement_refund.py000066400000000000000000000105061524412155200273470ustar00rootroot00000000000000"""Disbursement Refund resource for the MercadoPago Marketplace API. Wraps ``/v1/advanced_payments/{id}/refunds`` and ``/v1/advanced_payments/{id}/disbursements/{id}/refunds`` endpoints to refund individual or all disbursements within an advanced payment. """ from mercadopago.core import MPBase class DisbursementRefund(MPBase): """Refunds disbursements from advanced (split) payments. In marketplace flows each seller receives a disbursement. This resource lets you refund all disbursements at once, a single disbursement by amount, or a disbursement with a custom refund body. """ def list_all(self, advanced_payment_id, request_options=None): """Lists all refunds for an advanced payment. Args: advanced_payment_id: Identifier of the advanced payment. request_options: Per-call configuration overrides. Returns: dict: List of disbursement refund objects. """ uri = f"/v1/advanced_payments/{self._path_param(advanced_payment_id)}/refunds" return self._get(uri=uri, request_options=request_options) def create_all(self, advanced_payment_id, disbursement_refund_object, request_options=None): """Refunds all disbursements of an advanced payment at once. Args: advanced_payment_id: Identifier of the advanced payment. disbursement_refund_object: Dict with refund details applied to every disbursement. request_options: Per-call configuration overrides. Raises: ValueError: If *disbursement_refund_object* is not a ``dict``. Returns: dict: Bulk refund creation response. """ if not isinstance(disbursement_refund_object, dict): raise ValueError( "Param disbursement_refund_object must be a Dictionary") return self._post( uri="/v1/advanced_payments/" + self._path_param(advanced_payment_id) + "/refunds", data=disbursement_refund_object, request_options=request_options, ) def create(self, advanced_payment_id, disbursement_id, amount, request_options=None): """Refunds a specific disbursement by amount. Args: advanced_payment_id: Identifier of the parent advanced payment. disbursement_id: Identifier of the disbursement to refund. amount: Refund amount as a ``float``. request_options: Per-call configuration overrides. Raises: ValueError: If *amount* is not a ``float``. Returns: dict: Created disbursement refund. """ if not isinstance(amount, float): raise ValueError("Param amount must be a Float") disbursement_refund_object = {"amount": amount} uri = ( f"/v1/advanced_payments/{self._path_param(advanced_payment_id)}" f"/disbursements/{self._path_param(disbursement_id)}/refunds" ) return self._post( uri=uri, data=disbursement_refund_object, request_options=request_options, ) def save(self, advanced_payment_id, disbursement_id, disbursement_refund_object, request_options=None): """Creates a disbursement refund with a custom body. Unlike :meth:`create`, which only accepts an amount, this method lets you pass an arbitrary refund payload. Args: advanced_payment_id: Identifier of the parent advanced payment. disbursement_id: Identifier of the disbursement to refund. disbursement_refund_object: Dict with full refund details. request_options: Per-call configuration overrides. Raises: ValueError: If *disbursement_refund_object* is not a ``dict``. Returns: dict: Created disbursement refund. """ if not isinstance(disbursement_refund_object, dict): raise ValueError( "Param disbursement_refund_object must be a Dictionary") uri = ( f"/v1/advanced_payments/{self._path_param(advanced_payment_id)}" f"/disbursements/{self._path_param(disbursement_id)}/refunds" ) return self._post( uri=uri, data=disbursement_refund_object, request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/identification_type.py000066400000000000000000000017741524412155200273410ustar00rootroot00000000000000"""Identification Type resource for the MercadoPago API. Wraps the ``/v1/identification_types`` endpoint to retrieve the list of accepted document types (e.g. CPF, CNPJ, DNI) for each country. """ from mercadopago.core import MPBase class IdentificationType(MPBase): """Lists accepted identification document types by country. Use the returned types to populate document-type selectors in your checkout form so buyers can provide a valid identification. """ def list_all(self, request_options=None): """Retrieves all available identification types. Args: request_options: Per-call configuration overrides. Returns: dict: List of identification type objects (id, name, min/max length). """ return self._get(uri="/v1/identification_types", request_options=request_options) @property def request_options(self): """Default :class:`RequestOptions` for this resource instance.""" return self.__request_options mercadopago-sdk-python-b345a69/mercadopago/resources/invoice.py000066400000000000000000000045431524412155200247400ustar00rootroot00000000000000"""Invoice resource for the MercadoPago Subscriptions API. Wraps ``/authorized_payments`` endpoints to retrieve and search invoices generated by subscription (pre-approval) billing cycles. Each invoice represents a scheduled charge attempt against the subscriber's payment method. `API reference `_ """ from mercadopago.core import MPBase class Invoice(MPBase): """Provides read access to subscription invoices (authorized payments). Each invoice corresponds to a billing cycle of a :class:`~mercadopago.resources.preapproval.PreApproval` and tracks the charge amount, status, retry attempts, and the resulting payment. Use :meth:`get` and :meth:`search` to monitor billing cycles and their outcomes. """ def get(self, invoice_id, request_options=None): """Retrieves a single invoice (authorized payment) by its ID. Args: invoice_id: Unique invoice identifier assigned by MercadoPago. request_options: Per-call configuration overrides. Returns: dict: Full invoice object including ``status``, ``transaction_amount``, ``preapproval_id``, and associated ``payment`` details. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/get-authorized-payment/get """ return self._get( uri="/authorized_payments/" + self._path_param(invoice_id), request_options=request_options, ) def search(self, filters=None, request_options=None): """Searches invoices matching the given filters. Args: filters: Query-string parameters such as ``preapproval_id``, ``status``, ``payer_id``, ``offset``, and ``limit``. request_options: Per-call configuration overrides. Returns: dict: Paginated result with ``paging`` metadata and a ``results`` list of matching invoices. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/authorized-payment-search/get """ return self._get( uri="/authorized_payments/search", filters=filters, request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/item.py000066400000000000000000000031171524412155200242360ustar00rootroot00000000000000"""Dataclass for line items in API requests.""" from dataclasses import dataclass from typing import Optional # pylint: disable=too-many-instance-attributes # DTO: fields mirror the API items contract @dataclass class ItemRequest: """A single line item within an API request. Use this dataclass to build an entry of the ``items`` array when creating an order. Convert to dict with ``dataclasses.asdict()`` (``None`` fields are filtered out before sending, per the omit-empty behavior of the API). Attributes: title: Display name of the item. Type: str. type: Item type/category classifier. Type: str. warranty: Whether the item includes a warranty. Type: bool. event_date: ISO 8601 date associated with the item (e.g. event tickets). Type: str. unit_price: Price per unit as a decimal string (e.g. ``"100.00"``). Type: str. external_code: Merchant-side external identifier for the item. Type: str. category_id: MercadoPago category identifier. Type: str. description: Free-text description of the item. Type: str. picture_url: URL of an image representing the item. Type: str. quantity: Number of units. Type: int. """ title: Optional[str] = None type: Optional[str] = None warranty: Optional[bool] = None event_date: Optional[str] = None unit_price: Optional[str] = None external_code: Optional[str] = None category_id: Optional[str] = None description: Optional[str] = None picture_url: Optional[str] = None quantity: Optional[int] = None mercadopago-sdk-python-b345a69/mercadopago/resources/merchant_order.py000066400000000000000000000077431524412155200263050ustar00rootroot00000000000000"""Merchant Order resource for the MercadoPago API. Wraps ``/merchant_orders`` endpoints to search, retrieve, create, and update merchant orders. A merchant order groups one or more Checkout Pro payments under a single business reference. `API reference `_ """ from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class MerchantOrder(MPBase): """Groups payments into a single merchant-level order. Merchant orders are typically created automatically by Checkout Pro preferences but can also be managed manually to attach additional payments or shipments. """ def search(self, filters=None, request_options=None): """Searches merchant orders matching the given filters. Args: filters: Query-string parameters (e.g. ``external_reference``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching merchant orders. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/merchant_orders/search-merchant-order/get """ return self._get(uri="/merchant_orders/search", filters=filters, request_options=request_options) def get(self, merchan_order_id, request_options=None): """Retrieves a merchant order by its ID. Args: merchan_order_id: Unique merchant order identifier. request_options: Per-call configuration overrides. Returns: dict: Full merchant order object including attached payments. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/merchant_orders/get-merchant-order/get """ return self._get(uri="/merchant_orders/" + self._path_param(merchan_order_id), request_options=request_options) def update(self, merchan_order_id, merchant_order_object, request_options=None): """Updates an existing merchant order. Args: merchan_order_id: Identifier of the merchant order to update. merchant_order_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *merchant_order_object* is not a ``dict``. Returns: dict: Updated merchant order object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/merchant_orders/update-merchant-order/put """ if not isinstance(merchant_order_object, dict): raise ValueError( "Param merchant_order_object must be a Dictionary") return self._put(uri="/merchant_orders/" + self._path_param(merchan_order_id), data=merchant_order_object, request_options=request_options) def create(self, merchant_order_object, request_options=None): """Creates a new merchant order. Args: merchant_order_object: Dict describing the order (items, preference_id, application_id, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *merchant_order_object* is not a ``dict``. Returns: dict: Created merchant order including its ``id``. Reference: https://www.mercadopago.com/developers/en/reference """ if not isinstance(merchant_order_object, dict): raise ValueError( "Param merchant_order_object must be a Dictionary") return self._post(uri="/merchant_orders", data=merchant_order_object, request_options=request_options) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/oauth.py000066400000000000000000000106051524412155200244200ustar00rootroot00000000000000"""OAuth resource for the MercadoPago Authorization API. Wraps the OAuth 2.0 authorization code flow used in marketplace and platform integrations to operate on behalf of other sellers. `API reference `_ """ from urllib.parse import urlencode from mercadopago.core import MPBase _AUTH_URL = "https://auth.mercadopago.com/authorization" class OAuth(MPBase): """Manages the OAuth 2.0 authorization code flow. Use this resource when your application needs to operate on behalf of other MercadoPago sellers (marketplace or platform scenarios). The flow involves redirecting the seller to the authorization URL, receiving an authorization code, and exchanging it for access and refresh tokens. """ def get_authorization_url(self, app_id, redirect_uri, random_id): """Builds the MercadoPago authorization URL for the OAuth flow. Redirect the seller to this URL to start the authorization process. After granting permission, MercadoPago redirects back to *redirect_uri* with a ``code`` query parameter. Args: app_id: Your MercadoPago application's client ID. redirect_uri: URI where MercadoPago sends the seller after authorization. random_id: CSRF-protection state parameter; should be a unique, unpredictable value per authorization request. Returns: str: Full authorization URL with query parameters. Reference: https://www.mercadopago.com/developers/en/docs/security/oauth/creation """ params = { "client_id": app_id, "response_type": "code", "platform_id": "mp", "state": random_id, "redirect_uri": redirect_uri, } return _AUTH_URL + "?" + urlencode(params) def create(self, oauth_object, request_options=None): """Exchanges an authorization code for an access token. Call this after receiving the ``code`` parameter in your *redirect_uri* callback. The returned access token can be used to make API requests on behalf of the authorizing seller. Args: oauth_object: Dict with the authorization request fields: ``client_secret`` (your access token), ``code`` (authorization code received in the callback), ``redirect_uri`` (must match the one used in :meth:`get_authorization_url`), and ``grant_type`` (``"authorization_code"``). request_options: Per-call configuration overrides. Raises: ValueError: If *oauth_object* is not a ``dict``. Returns: dict: Token response including ``access_token``, ``refresh_token``, and ``expires_in``. Reference: https://www.mercadopago.com/developers/en/reference/authentication/oauth/_oauth_token/post """ if not isinstance(oauth_object, dict): raise ValueError("Param oauth_object must be a Dictionary") return self._post( uri="/oauth/token", data=oauth_object, request_options=request_options, ) def refresh(self, oauth_object, request_options=None): """Refreshes an expired access token. Use this to extend the seller's session without requiring them to re-authorize. The *refresh_token* is obtained from the initial :meth:`create` response. Args: oauth_object: Dict with the refresh request fields: ``client_secret`` (your access token), ``refresh_token`` (the token to refresh), and ``grant_type`` (``"refresh_token"``). request_options: Per-call configuration overrides. Raises: ValueError: If *oauth_object* is not a ``dict``. Returns: dict: New token response with a fresh ``access_token`` and ``refresh_token``. Reference: https://www.mercadopago.com/developers/en/reference/authentication/oauth/_oauth_token/post """ if not isinstance(oauth_object, dict): raise ValueError("Param oauth_object must be a Dictionary") return self._post( uri="/oauth/token", data=oauth_object, request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/order.py000066400000000000000000000322031524412155200244110ustar00rootroot00000000000000"""Order resource for the MercadoPago Orders API. Wraps ``/v1/orders`` endpoints covering the full order lifecycle: creation, retrieval, search, processing, capture, cancellation, refund, and transaction management. `API reference `_ """ from dataclasses import is_dataclass from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter from mercadopago.resources.order_create import order_request_to_dict class Order(MPBase): """Manages orders and their associated transactions. An order groups one or more payment transactions and supports a two-step (authorise then capture) flow as well as direct processing. Automatic Payments (AP) β€” supported keys for ``stored_credential`` dict: .. code-block:: python "stored_credential": { "payment_initiator": str, # "cardholder" | "merchant" "reason": str, # "recurring" | "installment" | "unscheduled" "store_payment_method": bool, "first_payment": bool, "prev_transaction_ref": str, # ID of the previous transaction in the series. # Required from the second charge onwards. } Supported keys for ``automatic_payments`` dict: .. code-block:: python "automatic_payments": { "payment_profile_id": str, # Stored payment profile ID. "retries": int, # Max retry attempts on failure. "schedule_date": str, # ISO 8601 scheduled charge date. "due_date": str, # ISO 8601 payment due date. } Supported keys for ``subscription_data`` dict: .. code-block:: python "subscription_data": { "invoice_id": str, # ID of the invoice being paid. "billing_date": str, # ISO 8601 billing date. "subscription_sequence": { "number": int, # Current payment number in the series. "total": int, # Total payments in the subscription. }, "invoice_period": { "type": str, # "monthly" | "daily" | "yearly". "period": int, # Number of period units. }, } Supported keys for ``integration_data`` dict (root of order request): .. code-block:: python "integration_data": { "integrator_id": str, # Certified integrator ID. "platform_id": str, # Platform ID assigned by MercadoPago. "corporation_id": str, # Corporation ID for multi-account setups. "sponsor": { "id": str, # MercadoPago user ID of the sponsor. }, } """ def search(self, filters=None, request_options=None): """Searches orders matching the given filters. Args: filters: Query-string parameters (e.g. ``external_reference``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching orders. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/search-order/get """ return self._get(uri="/v1/orders", filters=filters, request_options=request_options) def create(self, order_object, request_options=None): """Creates a new order. Accepts either a plain ``dict`` (the historical, dynamic route) or an :class:`~mercadopago.resources.order_create.OrderCreateRequest` typed dataclass. When a dataclass is passed it is converted to a ``dict`` with ``None`` fields omitted, producing the same JSON body as the dict route (DD-3). The dict route is unchanged and fully backward compatible. Args: order_object: Dict describing the order (items, transactions, payer, etc.), or an ``OrderCreateRequest`` dataclass instance. request_options: Per-call configuration overrides. Raises: ValueError: If *order_object* is neither a ``dict`` nor a dataclass instance. Returns: dict: Created order including its ``id``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/create-order/post """ if is_dataclass(order_object) and not isinstance(order_object, type): order_object = order_request_to_dict(order_object) elif not isinstance(order_object, dict): raise ValueError("Param order_object must be a Dictionary or an OrderCreateRequest") return self._post(uri="/v1/orders", data=order_object, request_options=request_options) def get(self, order_id, request_options=None): """Retrieves a single order by its ID. Args: order_id: String identifier of the order. request_options: Per-call configuration overrides. Raises: ValueError: If *order_id* is not a ``str``. Returns: dict: Full order object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/get-order/get """ if not isinstance(order_id, str): raise ValueError("Param order_id must be a string") return self._get( uri="/v1/orders/" + self._path_param(order_id), request_options=request_options, ) def process(self, order_id, request_options=None): """Processes (executes payment for) an existing order. Triggers the payment flow for all transactions attached to the order. The *order_id* is the value returned by :meth:`create`. Args: order_id: String identifier of the order to process. request_options: Per-call configuration overrides. Raises: ValueError: If *order_id* is not a ``str``. Returns: dict: Processed order with updated transaction statuses. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/process-order/post """ if not isinstance(order_id, str): raise ValueError("Param order_id must be a string") return self._post( uri=f"/v1/orders/{self._path_param(order_id)}/process", request_options=request_options, ) def cancel(self, order_id, request_options=None): """Cancels an existing order. Only orders that have not yet been fully captured can be cancelled. Args: order_id: String identifier of the order. request_options: Per-call configuration overrides. Raises: ValueError: If *order_id* is not a ``str``. Returns: dict: Order cancellation response. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/cancel-order/post """ if not isinstance(order_id, str): raise ValueError("Param order_id must be a string") return self._post( uri=f"/v1/orders/{self._path_param(order_id)}/cancel", request_options=request_options, ) def capture(self, order_id, request_options=None): """Captures a previously authorised order. Used in two-step payment flows where the order was created with ``capture=false``. Args: order_id: String identifier of the order to capture. request_options: Per-call configuration overrides. Raises: ValueError: If *order_id* is not a ``str``. Returns: dict: Captured order with updated transaction statuses. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/capture-order/post """ if not isinstance(order_id, str): raise ValueError("Param order_id must be a string") return self._post( uri=f"/v1/orders/{self._path_param(order_id)}/capture", request_options=request_options, ) def create_transaction(self, order_id, transaction_object, request_options=None): """Adds a payment transaction to an existing order. Args: order_id: Identifier of the parent order. transaction_object: Dict with transaction details (payment method, amount, token, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *transaction_object* is not a ``dict``. Exception: If the API does not return HTTP 201. Returns: dict: Created transaction response. """ if not isinstance(transaction_object, dict): raise ValueError("Param transaction_object must be a Dictionary") return self._post( uri=f"/v1/orders/{self._path_param(order_id)}/transactions", data=transaction_object, request_options=request_options, ) def update_transaction( self, order_id, transaction_id, transaction_object, request_options=None ): """Updates a transaction within an order. Args: order_id: Identifier of the parent order. transaction_id: Identifier of the transaction to update. transaction_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *transaction_object* is not a ``dict``. Exception: If the API does not return HTTP 200. Returns: dict: Updated transaction response. """ if not isinstance(transaction_object, dict): raise ValueError("Param transaction_object must be a Dictionary") return self._put( uri=f"/v1/orders/{self._path_param(order_id)}" f"/transactions/{self._path_param(transaction_id)}", data=transaction_object, request_options=request_options, ) def refund_transaction(self, order_id, transaction_object=None, request_options=None): """Refunds an order's transactions. Pass *transaction_object* with an ``amount`` key for a partial refund, or ``None`` for a full refund of every transaction. Args: order_id: Identifier of the order to refund. transaction_object: Optional dict for partial refund details. request_options: Per-call configuration overrides. Raises: ValueError: If *transaction_object* is provided but not a ``dict``. Exception: If the API does not return HTTP 201. Returns: dict: Refund confirmation response. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api/refund-order/post """ if transaction_object is not None and not isinstance(transaction_object, dict): raise ValueError("Param transaction_object must be a Dictionary") return self._post( uri=f"/v1/orders/{self._path_param(order_id)}/refund", data=transaction_object, request_options=request_options, ) def refund(self, order_id, refund_object=None, request_options=None): """Refunds an order. Alias for :meth:`refund_transaction` that matches the Orders API endpoint name while keeping the existing method for backwards compatibility. Args: order_id: Identifier of the order to refund. refund_object: Optional dict for partial refund details. request_options: Per-call configuration overrides. Returns: dict: Refund confirmation response. """ return self.refund_transaction(order_id, refund_object, request_options) def delete_transaction(self, order_id, transaction_id, request_options=None): """Removes a transaction from an order. Only transactions that have not been processed can be deleted. Args: order_id: Identifier of the parent order. transaction_id: Identifier of the transaction to remove. request_options: Per-call configuration overrides. Raises: ValueError: If *order_id* or *transaction_id* is not a ``str``. Exception: If the API does not return HTTP 204. Returns: dict: Empty response with status 204 on success. """ if not isinstance(order_id, str) or not isinstance(transaction_id, str): raise ValueError("Params order_id and transaction_id must be strings") return self._delete( uri=f"/v1/orders/{self._path_param(order_id)}" f"/transactions/{self._path_param(transaction_id)}", request_options=request_options, ) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/order_automatic_payments.py000066400000000000000000000022121524412155200303740ustar00rootroot00000000000000"""Dataclass for automatic/recurring payment scheduling in order requests.""" from dataclasses import dataclass from typing import Optional @dataclass class OrderAutomaticPayments: """Configuration for automatic (recurring) payment scheduling within an order. Use this dataclass to build the ``automatic_payments`` payload when creating an order with Automatic Payments. Convert to dict with ``dataclasses.asdict()``. Attributes: payment_profile_id: Identifier of the stored payment profile used for automatic charges. Type: str. retries: Maximum number of retry attempts if the automatic charge fails. Type: int. schedule_date: ISO 8601 date when the automatic payment is scheduled to be charged (e.g. ``"2026-06-01T00:00:00.000-04:00"``). Type: str. due_date: ISO 8601 date by which the payment must be completed before it is considered overdue. Type: str. """ payment_profile_id: Optional[str] = None retries: Optional[int] = None schedule_date: Optional[str] = None due_date: Optional[str] = None subscription: Optional[dict] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_checkout_pro.py000066400000000000000000000121101524412155200271510ustar00rootroot00000000000000"""Dataclasses for Checkout Pro fields in order requests.""" from dataclasses import ( asdict, dataclass, field, is_dataclass, ) from typing import ( Any, Dict, List, Optional, ) def OrderCheckoutProDict(value): # pylint: disable=invalid-name """Converts dataclasses to an order payload dict without empty values. ``dataclasses.asdict()`` preserves ``None`` values, which can produce invalid API payloads for optional nested fields. This helper recursively removes ``None`` values and empty containers while preserving explicit ``False`` and ``0`` values. """ if is_dataclass(value): value = asdict(value) if isinstance(value, dict): compact = {} for key, item in value.items(): item = OrderCheckoutProDict(item) if item is not None and item != [] and item != {}: compact[key] = item return compact if isinstance(value, list): return [ item for item in (OrderCheckoutProDict(item) for item in value) if item is not None and item != [] and item != {} ] return value @dataclass class OrderCheckoutProTrack: """Tracking pixel configuration for Checkout Pro orders. Attributes: type: Tracking pixel type, for example ``"google_ad"`` or ``"facebook_ad"``. Type: str. values: Pixel-specific values, such as ``conversion_id``, ``conversion_label``, or ``pixel_id``. Type: dict. """ type: Optional[str] = None values: Optional[Dict[str, Any]] = None @dataclass class OrderCheckoutProOnlineConfig: """Checkout Pro redirect and availability configuration. Use this dataclass to build the ``config.online`` payload when creating an order for Checkout Pro. Convert to dict with ``OrderCheckoutProDict()`` to omit empty values. Attributes: available_from: ISO 8601 date from which the order can be paid. Type: str. allowed_user_type: Restricts who can pay, for example ``"account_only"``. Type: str. success_url: Redirect URL after an approved payment. Type: str. failure_url: Redirect URL after a rejected or cancelled payment. Type: str. pending_url: Redirect URL when payment remains pending. Type: str. auto_return: Automatic redirect behavior, for example ``"approved"`` or ``"all"``. Type: str. tracks: Tracking pixel configuration list. """ available_from: Optional[str] = None allowed_user_type: Optional[str] = None success_url: Optional[str] = None failure_url: Optional[str] = None pending_url: Optional[str] = None auto_return: Optional[str] = None tracks: List[OrderCheckoutProTrack] = field(default_factory=list) @dataclass class OrderCheckoutProInterestFree: """Interest-free installment configuration for Checkout Pro orders. Attributes: type: Configuration type, for example ``"range"``, ``"list"``, or ``"none"``. Type: str. values: Installment range or list. Type: list[int]. """ type: Optional[str] = None values: List[int] = field(default_factory=list) @dataclass class OrderCheckoutProInstallments: """Installment rules for Checkout Pro payment methods. Attributes: interest_free: Interest-free installment configuration. """ interest_free: Optional[OrderCheckoutProInterestFree] = None @dataclass class OrderCheckoutProPaymentMethod: """Payment method constraints for Checkout Pro orders. Use this dataclass to build the ``config.payment_method`` payload when creating an order for Checkout Pro. Convert to dict with ``OrderCheckoutProDict()`` to omit empty values. Attributes: max_installments: Maximum installments accepted. Type: int. not_allowed_ids: Payment method IDs to block, such as card brands. Type: list[str]. not_allowed_types: Payment method types to block. Type: list[str]. installments: Installment rules. """ max_installments: Optional[int] = None not_allowed_ids: List[str] = field(default_factory=list) not_allowed_types: List[str] = field(default_factory=list) installments: Optional[OrderCheckoutProInstallments] = None @dataclass class OrderCheckoutProConfig: """Checkout Pro order configuration. Use this dataclass to build the root ``config`` payload when creating an order for Checkout Pro. Convert to dict with ``OrderCheckoutProDict()`` to omit empty values. Attributes: statement_descriptor: Text shown on the buyer's card statement. Type: str. default_payment_due_date: Offline payment expiration duration in ISO 8601 format. Type: str. online: Checkout Pro redirect and availability configuration. payment_method: Checkout Pro payment method constraints. """ statement_descriptor: Optional[str] = None default_payment_due_date: Optional[str] = None online: Optional[OrderCheckoutProOnlineConfig] = None payment_method: Optional[OrderCheckoutProPaymentMethod] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_create.py000066400000000000000000000111421524412155200257330ustar00rootroot00000000000000"""Root request dataclasses for the MercadoPago Orders API. These dataclasses model the ``POST /v1/orders`` request body. They are an optional, typed alternative to passing a plain ``dict`` to :meth:`~mercadopago.resources.order.Order.create`. Build the request with the dataclasses and convert it to a ``dict`` with ``dataclasses.asdict()``; ``None`` fields are filtered out before serialization so the resulting JSON matches the dict path exactly. The dict path continues to work unchanged; these dataclasses are purely additive. """ from dataclasses import ( asdict, dataclass, field, is_dataclass, ) from typing import ( List, Optional, Union, ) from mercadopago.resources.item import ItemRequest from mercadopago.resources.order_integration_data import OrderIntegrationData from mercadopago.resources.order_transaction import OrderTransactionRequest from mercadopago.resources.payer import PayerRequest from mercadopago.resources.shipment import ShipmentRequest def _filter_none(value): """Recursively drop ``None`` values from dicts/lists (DD-3, omit-empty).""" if isinstance(value, dict): return {k: _filter_none(v) for k, v in value.items() if v is not None} if isinstance(value, list): return [_filter_none(v) for v in value] return value def order_request_to_dict(request): """Convert a request dataclass into a ``dict`` with ``None`` fields omitted. This is the canonical way to turn any of the Orders API request dataclasses (``OrderCreateRequest`` and its nested objects) into the ``dict`` accepted by :meth:`~mercadopago.resources.order.Order.create`. It runs ``dataclasses.asdict()`` and then recursively strips keys whose value is ``None`` so the resulting JSON matches the plain-dict path exactly (DD-3). Args: request: A request dataclass instance (or any dataclass instance). Returns: dict: The request as a plain ``dict`` with ``None`` fields removed. Raises: TypeError: If *request* is not a dataclass instance. """ if not is_dataclass(request) or isinstance(request, type): raise TypeError("request must be a dataclass instance") return _filter_none(asdict(request)) # pylint: disable=too-many-instance-attributes # DTO: fields mirror the Orders API root request contract @dataclass class OrderCreateRequest: """Root request body for creating an order. Optional typed alternative to a plain ``dict``. Convert with ``dataclasses.asdict()``; ``None`` fields are filtered out before sending. Attributes: type: Order type (e.g. ``"online"``). Type: str. external_reference: Merchant-side reference for the order. Type: str. total_amount: Total order amount as a decimal string. Type: str. currency: Currency identifier (e.g. ``"BRL"``). Type: str. capture_mode: Capture mode (e.g. ``"automatic_async"``). Type: str. processing_mode: Processing mode (e.g. ``"automatic"``). Type: str. description: Free-text order description. Type: str. marketplace: Marketplace identifier. Type: str. marketplace_fee: Marketplace fee as a decimal string. Type: str. expiration_time: Order expiration time (ISO 8601 / duration). Type: str. checkout_available_at: When the checkout becomes available. Type: str. transactions: Typed transactions payload. Accepts an :class:`~mercadopago.resources.order_transaction.OrderTransactionRequest` for a fully typed AP chain, or a plain ``dict`` for backward compatibility. payer: Payer information. items: Line items in the order. config: Order configuration payload. shipment: Shipment configuration. integration_data: Integration metadata. additional_info: Free-form additional information (kept as-is). """ type: Optional[str] = None external_reference: Optional[str] = None total_amount: Optional[str] = None currency: Optional[str] = None capture_mode: Optional[str] = None processing_mode: Optional[str] = None description: Optional[str] = None marketplace: Optional[str] = None marketplace_fee: Optional[str] = None expiration_time: Optional[str] = None checkout_available_at: Optional[str] = None transactions: Optional[Union[OrderTransactionRequest, dict]] = None payer: Optional[PayerRequest] = None items: Optional[List[ItemRequest]] = field(default=None) config: Optional[dict] = None shipment: Optional[ShipmentRequest] = None integration_data: Optional[OrderIntegrationData] = None additional_info: Optional[dict] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_integration_data.py000066400000000000000000000022331524412155200300050ustar00rootroot00000000000000"""Dataclasses for integration metadata in order requests.""" from dataclasses import dataclass from typing import Optional @dataclass class OrderSponsor: """Sponsoring marketplace owner associated with an order. Attributes: id: MercadoPago user ID of the sponsoring marketplace owner. Type: str. """ id: Optional[str] = None @dataclass class OrderIntegrationData: """Integration metadata for an order request. Identifies the integrator, platform, and corporation associated with the integration. Use this dataclass to build the ``integration_data`` payload at the root of the order create request. Convert to dict with ``dataclasses.asdict()``. Attributes: integrator_id: Identifier of the certified integrator. Type: str. platform_id: Platform identifier assigned by MercadoPago. Type: str. corporation_id: Corporation identifier for multi-account setups. Type: str. sponsor: Sponsoring marketplace owner information. """ integrator_id: Optional[str] = None platform_id: Optional[str] = None corporation_id: Optional[str] = None sponsor: Optional[OrderSponsor] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_stored_credential.py000066400000000000000000000026151524412155200301670ustar00rootroot00000000000000"""Dataclass for stored credential (card-on-file) data in automatic payment flows.""" from dataclasses import dataclass from typing import Optional @dataclass class OrderStoredCredential: """Stored credential configuration for recurring payments (card-on-file). Use this dataclass to build the ``stored_credential`` payload when creating an order with Automatic Payments. Convert to dict with ``dataclasses.asdict()``. Attributes: payment_initiator: Who initiated the payment: ``"cardholder"`` or ``"merchant"``. Type: str. reason: Reason for using the stored credential. One of ``"recurring"``, ``"installment"``, ``"unscheduled"``. Type: str. store_payment_method: Whether to save the payment method for future charges. Type: bool. first_payment: ``True`` for the initial authorization; ``False`` for subsequent recurring charges. Type: bool. previous_transaction_reference: Identifier of the previous transaction in the recurring series. Required from the second charge onwards to link this payment to the original card-network authorization. Type: str. """ payment_initiator: Optional[str] = None reason: Optional[str] = None store_payment_method: Optional[bool] = None first_payment: Optional[bool] = None previous_transaction_reference: Optional[str] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_subscription_data.py000066400000000000000000000032451524412155200302120ustar00rootroot00000000000000"""Dataclass for subscription billing data in automatic payment order requests.""" from dataclasses import dataclass from typing import Optional @dataclass class OrderSubscriptionSequence: """Position of a payment within a subscription series. Attributes: number: Current payment number in the subscription (1-based). Type: int. total: Total number of payments expected in the plan. Type: int. """ number: Optional[int] = None total: Optional[int] = None @dataclass class OrderInvoicePeriod: """Billing period covered by a subscription invoice. Attributes: type: Period unit (e.g. ``"monthly"``, ``"daily"``, ``"yearly"``). Type: str. period: Number of period units covered by this invoice. Type: int. """ type: Optional[str] = None period: Optional[int] = None @dataclass class OrderSubscriptionData: """Subscription billing information for a payment within an order. Use this dataclass to build the ``subscription_data`` payload when creating an order with Automatic Payments. Convert to dict with ``dataclasses.asdict()``. Attributes: invoice_id: Identifier of the invoice being settled by this payment. Type: str. billing_date: ISO 8601 date when the subscription billing was triggered. Type: str. subscription_sequence: Position of this payment in the subscription series. invoice_period: Billing period covered by this invoice. """ invoice_id: Optional[str] = None billing_date: Optional[str] = None subscription_sequence: Optional[OrderSubscriptionSequence] = None invoice_period: Optional[OrderInvoicePeriod] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_transaction.py000066400000000000000000000057731524412155200270320ustar00rootroot00000000000000"""Dataclasses for the transactions payload in Orders API requests. These dataclasses model the ``transactions.payments[]`` structure of the ``POST /v1/orders`` request body. They complete the typed chain started by :class:`~mercadopago.resources.order_create.OrderCreateRequest`, allowing Automatic Payments fields to be built without raw dicts. The plain dict path continues to work unchanged; these dataclasses are purely additive. """ from dataclasses import dataclass from typing import ( List, Optional, ) from mercadopago.resources.order_automatic_payments import OrderAutomaticPayments from mercadopago.resources.order_stored_credential import OrderStoredCredential from mercadopago.resources.order_subscription_data import OrderSubscriptionData @dataclass class OrderPaymentMethodRequest: """Payment method details for a transaction within an order. Attributes: id: Payment method identifier (e.g. ``"master"``). Type: str. type: Payment method type (e.g. ``"credit_card"``). Type: str. token: Tokenized card identifier. Type: str. installments: Number of installments. Type: int. statement_descriptor: Descriptor shown on the cardholder statement. Type: str. financial_institution: Financial institution code (e.g. PSE). Type: str. """ id: Optional[str] = None type: Optional[str] = None token: Optional[str] = None installments: Optional[int] = None statement_descriptor: Optional[str] = None financial_institution: Optional[str] = None @dataclass class OrderPaymentRequest: """A single payment transaction within an order. Use this dataclass to build an entry of the ``transactions.payments`` array. It provides a fully typed path to all Automatic Payments fields (``automatic_payments``, ``stored_credential``, ``subscription_data``). Attributes: amount: Payment amount as a decimal string. Type: str. expiration_time: ISO 8601 duration or date-time for expiration. Type: str. date_of_expiration: ISO 8601 date-time after which the payment can no longer be collected. Type: str. payment_method: Payment method details. automatic_payments: Automatic (recurring) payment configuration. stored_credential: Card-on-file metadata for recurring charges. subscription_data: Subscription billing data for this payment. """ amount: Optional[str] = None expiration_time: Optional[str] = None date_of_expiration: Optional[str] = None payment_method: Optional[OrderPaymentMethodRequest] = None automatic_payments: Optional[OrderAutomaticPayments] = None stored_credential: Optional[OrderStoredCredential] = None subscription_data: Optional[OrderSubscriptionData] = None @dataclass class OrderTransactionRequest: """Transactions payload for an order creation request. Attributes: payments: List of payment transactions for the order. """ payments: Optional[List[OrderPaymentRequest]] = None mercadopago-sdk-python-b345a69/mercadopago/resources/order_transaction_security.py000066400000000000000000000013721524412155200307500ustar00rootroot00000000000000"""Dataclass for transaction security data in order requests.""" from dataclasses import dataclass from typing import Optional @dataclass class OrderTransactionSecurity: """Transaction security settings for an order request. Nested under ``config.online.transaction_security`` (not at the request root). Convert to dict with ``dataclasses.asdict()`` (``None`` fields are filtered out before sending, per the omit-empty behavior of the API). Attributes: validation: Validation strategy applied to the transaction (e.g. ``"complete"``). Type: str. liability_shift: Liability shift indicator for 3-D Secure flows. Type: str. """ validation: Optional[str] = None liability_shift: Optional[str] = None mercadopago-sdk-python-b345a69/mercadopago/resources/payer.py000066400000000000000000000046531524412155200244260ustar00rootroot00000000000000"""Dataclasses for payer data in API requests.""" from dataclasses import dataclass from typing import Optional @dataclass class PayerPhone: """Payer phone number. Attributes: area_code: Phone area code. Type: str. number: Phone number without the area code. Type: str. """ area_code: Optional[str] = None number: Optional[str] = None # pylint: disable=too-many-instance-attributes # DTO: fields mirror the API payer.address contract @dataclass class PayerAddress: """Payer address. Attributes: zip_code: Postal / ZIP code. Type: str. street_name: Name of the street. Type: str. street_number: Street number. Type: str. neighborhood: Neighborhood name. Type: str. city: City name. Type: str. state: State or province. Type: str. complement: Additional address details. Type: str. country: Country name or code. Type: str. """ zip_code: Optional[str] = None street_name: Optional[str] = None street_number: Optional[str] = None neighborhood: Optional[str] = None city: Optional[str] = None state: Optional[str] = None complement: Optional[str] = None country: Optional[str] = None @dataclass class PayerIdentification: """Payer identification document. Attributes: type: Identification document type (e.g. ``"CPF"``). Type: str. number: Identification document number. Type: str. """ type: Optional[str] = None number: Optional[str] = None # pylint: disable=too-many-instance-attributes # DTO: fields mirror the API payer contract @dataclass class PayerRequest: """Payer information for an API request. Attributes: email: Payer email address. Type: str. first_name: Payer first name. Type: str. last_name: Payer last name. Type: str. customer_id: Stored customer identifier. Type: str. entity_type: Payer entity type (``"individual"`` | ``"association"``). Type: str. identification: Payer identification document. phone: Payer phone number. address: Payer address. """ email: Optional[str] = None first_name: Optional[str] = None last_name: Optional[str] = None customer_id: Optional[str] = None entity_type: Optional[str] = None identification: Optional[PayerIdentification] = None phone: Optional[PayerPhone] = None address: Optional[PayerAddress] = None mercadopago-sdk-python-b345a69/mercadopago/resources/payment.py000066400000000000000000000127271524412155200247640ustar00rootroot00000000000000"""Payment resource for the MercadoPago Checkout API. Wraps ``/v1/payments`` endpoints to search, retrieve, create, and update payments. `API reference `_ """ import warnings from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class Payment(MPBase): """Manages payment lifecycle through the MercadoPago Checkout API. Supports transparent (server-to-server) payments as well as payments originated from Checkout Pro / Checkout Bricks. `Integration guide `_ """ def search(self, filters=None, request_options=None): """Searches payments matching the given filters. Args: filters: Query-string parameters such as ``external_reference``, ``status``, ``date_created``, etc. request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching payments. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/search-payments/get """ return self._get(uri="/v1/payments/search", filters=filters, request_options=request_options) def get(self, payment_id, request_options=None): """Retrieves a single payment by its ID. Args: payment_id: Numeric or string payment identifier. request_options: Per-call configuration overrides. Returns: dict: Full payment object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/get-payment/get """ return self._get( uri="/v1/payments/" + self._path_param(payment_id), request_options=request_options, ) def create(self, payment_object, request_options=None): """Creates a new payment. Args: payment_object: Dict describing the payment (amount, payer, payment_method_id, token, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *payment_object* is not a ``dict``. Returns: dict: Created payment including its ``id`` and ``status``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/create-payment/post """ if not isinstance(payment_object, dict): raise ValueError("Param payment_object must be a Dictionary") if "notification_url" in payment_object: warnings.warn( "notification_url is deprecated; use Webhooks instead. " "See https://www.mercadopago.com/developers/en/docs/your-integrations/notifications/webhooks", DeprecationWarning, stacklevel=2, ) return self._post(uri="/v1/payments", data=payment_object, request_options=request_options) def update(self, payment_id, payment_object, request_options=None): """Updates an existing payment. Commonly used to change ``status`` (e.g. cancel) or update metadata on a payment that has not yet been captured. Args: payment_id: Identifier of the payment to update. payment_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *payment_object* is not a ``dict``. Returns: dict: Updated payment object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/update-payment/put """ if not isinstance(payment_object, dict): raise ValueError("Param payment_object must be a Dictionary") return self._put(uri="/v1/payments/" + self._path_param(payment_id), data=payment_object, request_options=request_options) def capture(self, payment_id, amount=None, request_options=None): """Captures an authorized payment. Args: payment_id: Identifier of the authorized payment to capture. amount: Amount to capture. If ``None``, the full authorized amount is captured. request_options: Per-call configuration overrides. Returns: dict: Updated payment object reflecting the captured state. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/update-payment/put """ payload = {"capture": True} if amount is not None: payload["transaction_amount"] = amount return self._put( uri="/v1/payments/" + self._path_param(payment_id), data=payload, request_options=request_options, ) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields every payment matching *filters* across all pages. Args: filters: Search criteria (e.g. ``{"status": "approved"}``). request_options: Per-call configuration overrides. limit: Items per page. Defaults to 100. Yields: dict: Individual payment objects. """ return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/payment_methods.py000066400000000000000000000020451524412155200264770ustar00rootroot00000000000000"""Payment Methods resource for the MercadoPago API. Wraps the ``/v1/payment_methods`` endpoint to list the payment methods available for the authenticated account (credit cards, debit cards, bank transfers, cash, etc.). """ from mercadopago.core import MPBase class PaymentMethods(MPBase): """Lists payment methods available to the authenticated seller. The returned list varies by country and account configuration. Use it to display accepted payment options in your checkout UI. """ def list_all(self, request_options=None): """Retrieves all available payment methods. Args: request_options: Per-call configuration overrides. Returns: dict: List of payment method objects (id, name, type, status, thumbnail, etc.). """ return self._get(uri="/v1/payment_methods", request_options=request_options) @property def request_options(self): """Default :class:`RequestOptions` for this resource instance.""" return self.__request_options mercadopago-sdk-python-b345a69/mercadopago/resources/plan.py000066400000000000000000000074401524412155200242350ustar00rootroot00000000000000"""Plan resource for the MercadoPago Subscriptions API. Wraps ``/preapproval_plan`` endpoints to search, retrieve, create, and update subscription plans. Plans serve as reusable templates that define billing frequency, amount, and duration for subscriptions. `API reference `_ """ from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class Plan(MPBase): """Manages subscription plan templates. Create a plan once and then attach multiple :class:`~mercadopago.resources.subscription.Subscription` instances to it so that all subscribers share the same billing terms. """ def search(self, filters=None, request_options=None): """Searches plans matching the given filters. Args: filters: Query-string parameters. request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching plans. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/search-preapproval-plan/get """ return self._get( uri="/preapproval_plan/search", filters=filters, request_options=request_options) def get(self, plan_id, request_options=None): """Retrieves a plan by its ID. Args: plan_id: Unique plan identifier. request_options: Per-call configuration overrides. Returns: dict: Full plan object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/get-preapproval-plan/get """ return self._get( uri="/preapproval_plan/" + self._path_param(plan_id), request_options=request_options) def create(self, plan_object, request_options=None): """Creates a new subscription plan. Args: plan_object: Dict defining the plan (reason, auto_recurring frequency/amount, back_url, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *plan_object* is not a ``dict``. Returns: dict: Created plan including its ``id`` and ``init_point``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/create-preapproval-plan/post """ if not isinstance(plan_object, dict): raise ValueError("Param plan_object must be a Dictionary") return self._post( uri="/preapproval_plan", data=plan_object, request_options=request_options) def update(self, plan_id, plan_object, request_options=None): """Updates an existing plan. Args: plan_id: Identifier of the plan to update. plan_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *plan_object* is not a ``dict``. Returns: dict: Updated plan object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/update-preapproval-plan/put """ if not isinstance(plan_object, dict): raise ValueError("Param plan_object must be a Dictionary") return self._put( uri="/preapproval_plan/" + self._path_param(plan_id), data=plan_object, request_options=request_options) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/point.py000066400000000000000000000113201524412155200244240ustar00rootroot00000000000000"""Point resource for the MercadoPago Point Integration API. Wraps ``/point/integration-api`` endpoints for in-person payment processing through MercadoPago Point devices (card readers). Supported operations: list devices, create payment intent, get payment intent, and cancel payment intent. Note: The ``change_operating_mode`` operation (PATCH ``/point/integration-api/devices/{self._path_param(device_id)}``) is not included because the Python SDK HTTP client does not currently expose a PATCH method. `API reference `_ """ from mercadopago.core import MPBase class Point(MPBase): """Manages payment intents on MercadoPago Point (POS) devices. Enables in-person payment processing by creating payment intents that are sent to a physical Point device for the buyer to complete the transaction by inserting or tapping their card. """ def get_devices(self, filters=None, request_options=None): """Lists Point devices linked to the authenticated account. Args: filters: Optional query-string parameters such as ``store_id`` and ``pos_id``. request_options: Per-call configuration overrides. Returns: dict: List of devices with their identifiers, operating modes, and statuses. Reference: https://www.mercadopago.com/developers/en/reference/in-person-payments/point/devices/list-devices/get """ return self._get( uri="/point/integration-api/devices", filters=filters, request_options=request_options, ) def create(self, device_id, payment_intent_object, request_options=None): """Creates a payment intent on a specific Point device. The payment intent is sent to the physical device, where the buyer completes the transaction. Args: device_id: Unique identifier of the target Point device. payment_intent_object: Dict describing the payment intent, including ``amount``, ``description``, and ``payment`` method details. request_options: Per-call configuration overrides. Raises: ValueError: If *payment_intent_object* is not a ``dict``. Returns: dict: Created payment intent including its ``id`` and ``state``. Reference: https://www.mercadopago.com/developers/en/reference/in-person-payments/point/orders/create-order/post """ if not isinstance(payment_intent_object, dict): raise ValueError("Param payment_intent_object must be a Dictionary") return self._post( uri="/point/integration-api/devices/" + self._path_param(device_id) + "/payment-intents", data=payment_intent_object, request_options=request_options, ) def get(self, payment_intent_id, request_options=None): """Retrieves the current state of a payment intent by its ID. Use this to check whether the buyer has completed, cancelled, or is still processing the payment on the device. Args: payment_intent_id: Unique identifier of the payment intent. request_options: Per-call configuration overrides. Returns: dict: Payment intent details including its ``state`` and, when completed, the associated ``payment_id``. Reference: https://www.mercadopago.com/developers/en/reference/in-person-payments/point/orders/get-order/get """ return self._get( uri="/point/integration-api/payment-intents/" + self._path_param(payment_intent_id), request_options=request_options, ) def cancel(self, device_id, payment_intent_id, request_options=None): """Cancels a pending payment intent on a specific device. Use this to abort a transaction before the buyer completes the payment on the device. Args: device_id: Unique identifier of the Point device holding the intent. payment_intent_id: Unique identifier of the payment intent to cancel. request_options: Per-call configuration overrides. Returns: dict: Cancellation confirmation. Reference: https://www.mercadopago.com/developers/en/reference/in-person-payments/point/orders/cancel-order/post """ return self._delete( uri="/point/integration-api/devices/" + self._path_param(device_id) + "/payment-intents/" + self._path_param(payment_intent_id), request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/preapproval.py000066400000000000000000000077031524412155200256400ustar00rootroot00000000000000"""PreApproval resource for the MercadoPago Subscriptions API. Wraps ``/preapproval`` endpoints to search, retrieve, create, and update preapproval (subscription) records without an associated plan. `API reference `_ """ from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class PreApproval(MPBase): """Manages plan-less (ad-hoc) subscriptions. Use this resource when you need full control over subscription terms per subscriber instead of using a shared :class:`Plan` template. """ def __init__(self, request_options, http_client): MPBase.__init__(self, request_options, http_client) def search(self, filters=None, request_options=None): """Searches preapprovals matching the given filters. Args: filters: Query-string parameters. request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching preapprovals. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/search-preapproval/get """ return self._get(uri="/preapproval/search", filters=filters, request_options=request_options) def get(self, preapproval_id, request_options=None): """Retrieves a preapproval by its ID. Args: preapproval_id: Unique preapproval identifier. request_options: Per-call configuration overrides. Returns: dict: Full preapproval object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/get-preapproval/get """ return self._get( uri="/preapproval/" + self._path_param(preapproval_id), request_options=request_options, ) def create(self, preapproval_object, request_options=None): """Creates a new preapproval (ad-hoc subscription). Args: preapproval_object: Dict defining the subscription (reason, auto_recurring, payer_email, back_url, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *preapproval_object* is not a ``dict``. Returns: dict: Created preapproval including its ``id`` and ``init_point``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/create-preapproval/post """ if not isinstance(preapproval_object, dict): raise ValueError("Param preapproval_object must be a Dictionary") return self._post(uri="/preapproval", data=preapproval_object, request_options=request_options) def update(self, preapproval_id, preapproval_object, request_options=None): """Updates an existing preapproval. Args: preapproval_id: Identifier of the preapproval to update. preapproval_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *preapproval_object* is not a ``dict``. Returns: dict: Updated preapproval object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/update-preapproval/put """ if not isinstance(preapproval_object, dict): raise ValueError("Param preapproval_object must be a Dictionary") return self._put(uri="/preapproval/" + self._path_param(preapproval_id), data=preapproval_object, request_options=request_options) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/preference.py000066400000000000000000000106451524412155200254220ustar00rootroot00000000000000"""Checkout Preference resource for the MercadoPago API. Wraps ``/checkout/preferences`` endpoints to create, retrieve, update, and search payment preferences used by Checkout Pro. `API reference `_ """ import warnings from mercadopago.core import MPBase from mercadopago.pagination.iterator import search_auto_paging_iter as _paging_iter class Preference(MPBase): """Manages Checkout Pro payment preferences. A preference defines the items, payer information, payment methods, and redirect URLs for a Checkout Pro session. The ``init_point`` returned by :meth:`create` is the URL you redirect buyers to. """ def get(self, preference_id, request_options=None): """Retrieves a preference by its ID. Args: preference_id: Unique preference identifier. request_options: Per-call configuration overrides. Returns: dict: Full preference object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/preferences/get-preference/get """ return self._get(uri="/checkout/preferences/" + self._path_param(preference_id), request_options=request_options) def update(self, preference_id, preference_object, request_options=None): """Updates an existing preference. Args: preference_id: Identifier of the preference to update. preference_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *preference_object* is not a ``dict``. Returns: dict: Updated preference object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/preferences/update-preference/put """ if not isinstance(preference_object, dict): raise ValueError("Param preference_object must be a Dictionary") return self._put( uri="/checkout/preferences/" + self._path_param(preference_id), data=preference_object, request_options=request_options, ) def create(self, preference_object, request_options=None): """Creates a new checkout preference. The response includes ``init_point`` and ``sandbox_init_point`` URLs to redirect buyers to the Checkout Pro flow. Args: preference_object: Dict defining items, payer, back_urls, payment_methods, etc. request_options: Per-call configuration overrides. Raises: ValueError: If *preference_object* is not a ``dict``. Returns: dict: Created preference including ``id`` and ``init_point``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/preferences/create-preference/post """ if not isinstance(preference_object, dict): raise ValueError("Param preference_object must be a Dictionary") if "notification_url" in preference_object: warnings.warn( "notification_url is deprecated; use Webhooks instead. " "See https://www.mercadopago.com/developers/en/docs/your-integrations/notifications/webhooks", DeprecationWarning, stacklevel=2, ) return self._post(uri="/checkout/preferences", data=preference_object, request_options=request_options) def search(self, filters=None, request_options=None): """Searches preferences matching the given filters. Args: filters: Query-string parameters (e.g. ``external_reference``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching preferences. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-pro/preferences/search-preferences/get """ return self._get(uri="/checkout/preferences/search", filters=filters, request_options=request_options) def search_auto_paging_iter(self, filters=None, request_options=None, limit=100): """Lazily yields all items matching *filters* across all pages.""" return _paging_iter(self.search, filters, request_options, limit) mercadopago-sdk-python-b345a69/mercadopago/resources/refund.py000066400000000000000000000061101524412155200245570ustar00rootroot00000000000000"""Refund resource for the MercadoPago Payments API. Wraps ``/v1/payments/{self._path_param(payment_id)}/refunds`` endpoints to list existing refunds and create full or partial refunds on approved payments. Refunds are available within 180 days of payment approval and require sufficient account balance. `API reference `_ """ from mercadopago.core import MPBase class Refund(MPBase): """Creates and lists refunds for payments. Supports full refunds (omit *refund_object*) and partial refunds (pass ``{"amount": }``). Refunds can only be issued for approved payments within 180 days. """ def list_all(self, payment_id, request_options=None): """Lists all refunds issued for a payment. Args: payment_id: Identifier of the parent payment. request_options: Per-call configuration overrides. Returns: dict: List of refund objects. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/get-refunds/get """ return self._get(uri="/v1/payments/" + self._path_param(payment_id) + "/refunds", request_options=request_options) def create(self, payment_id, refund_object=None, request_options=None): """Creates a refund for a payment. Omit *refund_object* for a full refund, or pass ``{"amount": }`` for a partial refund. Args: payment_id: Identifier of the payment to refund. refund_object: Optional dict with partial refund details. request_options: Per-call configuration overrides. Raises: ValueError: If *refund_object* is provided but not a ``dict``. Returns: dict: Created refund including its ``id`` and ``status``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/create-refund/post """ if refund_object is not None and not isinstance(refund_object, dict): raise ValueError("Param refund_object must be a Dictionary") return self._post(uri="/v1/payments/" + self._path_param(payment_id) + "/refunds", data=refund_object, request_options=request_options) def get(self, payment_id, refund_id, request_options=None): """Retrieves a single refund by its ID. Args: payment_id: Identifier of the parent payment. refund_id: Identifier of the refund to retrieve. request_options: Per-call configuration overrides. Returns: dict: Refund object including its ``id`` and ``status``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/checkout-api-payments/get-refund/get """ return self._get( uri=f"/v1/payments/{self._path_param(payment_id)}" f"/refunds/{self._path_param(refund_id)}", request_options=request_options, ) mercadopago-sdk-python-b345a69/mercadopago/resources/shipment.py000066400000000000000000000043751524412155200251360ustar00rootroot00000000000000"""Dataclasses for shipment data in API requests.""" from dataclasses import ( dataclass, field, ) from typing import ( List, Optional, ) # pylint: disable=too-many-instance-attributes # DTO: fields mirror the API shipment.address contract @dataclass class ShipmentAddress: """Delivery address for a shipment. Attributes: street_name: Name of the street. Type: str. street_number: Street number. Type: str. zip_code: Postal / ZIP code. Type: str. floor: Floor within the building. Type: str. apartment: Apartment / unit identifier. Type: str. neighborhood: Neighborhood name. Type: str. state: State or province. Type: str. city: City name. Type: str. complement: Additional address details. Type: str. """ street_name: Optional[str] = None street_number: Optional[str] = None zip_code: Optional[str] = None floor: Optional[str] = None apartment: Optional[str] = None neighborhood: Optional[str] = None state: Optional[str] = None city: Optional[str] = None complement: Optional[str] = None @dataclass class ShipmentFreeMethod: """A free-shipping method. Attributes: id: Identifier of the free shipping method. Type: int. """ id: Optional[int] = None @dataclass class ShipmentRequest: """Shipment configuration for an API request. Use this dataclass to build the ``shipment`` payload when creating an order. Convert to dict with ``dataclasses.asdict()`` (``None`` fields are filtered out before sending, per the omit-empty behavior of the API). Attributes: mode: Shipping mode (e.g. ``"me2"``, ``"custom"``). Type: str. local_pickup: Whether the buyer picks up the item locally. Type: bool. cost: Shipping cost as a decimal string. Type: str. free_shipping: Whether shipping is free. Type: bool. free_methods: Free shipping methods available. address: Delivery address for the shipment. """ mode: Optional[str] = None local_pickup: Optional[bool] = None cost: Optional[str] = None free_shipping: Optional[bool] = None free_methods: Optional[List[ShipmentFreeMethod]] = field(default=None) address: Optional[ShipmentAddress] = None mercadopago-sdk-python-b345a69/mercadopago/resources/status.py000066400000000000000000000024741524412155200246300ustar00rootroot00000000000000"""Status enum constants for MercadoPago resources. Use these constants instead of hard-coding status string literals to avoid typos and benefit from IDE auto-complete. Example:: from mercadopago import PaymentStatus if result["response"]["status"] == PaymentStatus.APPROVED: fulfill_order() """ class PaymentStatus: """Valid values for ``payment.status``.""" PENDING = "pending" APPROVED = "approved" AUTHORIZED = "authorized" IN_PROCESS = "in_process" IN_MEDIATION = "in_mediation" REJECTED = "rejected" CANCELLED = "cancelled" REFUNDED = "refunded" CHARGED_BACK = "charged_back" class OrderStatus: """Valid values for ``order.status``.""" CREATED = "created" PROCESSED = "processed" ACTION_REQUIRED = "action_required" PROCESSING = "processing" CANCELED = "canceled" class PreapprovalStatus: """Valid values for ``preapproval.status``.""" PENDING = "pending" AUTHORIZED = "authorized" PAUSED = "paused" CANCELLED = "cancelled" class MerchantOrderStatus: """Valid values for ``merchant_order.status``.""" OPENED = "opened" CLOSED = "closed" EXPIRED = "expired" class RefundStatus: """Valid values for ``refund.status``.""" APPROVED = "approved" IN_PROCESS = "in_process" REJECTED = "rejected" mercadopago-sdk-python-b345a69/mercadopago/resources/subscription.py000066400000000000000000000075201524412155200260260ustar00rootroot00000000000000"""Subscription resource for the MercadoPago Subscriptions API. Wraps ``/preapproval`` endpoints to search, retrieve, create, and update plan-based subscriptions. A subscription links a payer to a :class:`~mercadopago.resources.plan.Plan` template for recurring billing. `API reference `_ """ from mercadopago.core import MPBase class Subscription(MPBase): """Manages plan-based recurring subscriptions. Each subscription is associated with a :class:`Plan` that defines billing frequency and amount. Use :meth:`create` with a ``preapproval_plan_id`` to subscribe a payer to an existing plan. """ def search(self, filters=None, request_options=None): """Searches subscriptions matching the given filters. Args: filters: Query-string parameters (e.g. ``status``, ``preapproval_plan_id``). request_options: Per-call configuration overrides. Returns: dict: Paginated list of matching subscriptions. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/search-preapproval/get """ return self._get( uri="/preapproval/search", filters=filters, request_options=request_options) def get(self, subscription_id, request_options=None): """Retrieves a subscription by its ID. Args: subscription_id: Unique subscription identifier. request_options: Per-call configuration overrides. Returns: dict: Full subscription object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/get-preapproval/get """ return self._get( uri="/preapproval/" + self._path_param(subscription_id), request_options=request_options) def create(self, subscription_object, request_options=None): """Creates a new subscription. Args: subscription_object: Dict defining the subscription (preapproval_plan_id, payer_email, card_token_id, etc.). request_options: Per-call configuration overrides. Raises: ValueError: If *subscription_object* is not a ``dict``. Returns: dict: Created subscription including its ``id`` and ``status``. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/create-preapproval/post """ if not isinstance(subscription_object, dict): raise ValueError("Param subscription_object must be a Dictionary") return self._post( uri="/preapproval", data=subscription_object, request_options=request_options) def update(self, subscription_id, subscription_object, request_options=None): """Updates an existing subscription. Commonly used to pause, reactivate, or change the card token on a subscription. Args: subscription_id: Identifier of the subscription to update. subscription_object: Dict with the fields to modify. request_options: Per-call configuration overrides. Raises: ValueError: If *subscription_object* is not a ``dict``. Returns: dict: Updated subscription object. Reference: https://www.mercadopago.com/developers/en/reference/online-payments/subscriptions/update-preapproval/put """ if not isinstance(subscription_object, dict): raise ValueError("Param subscription_object must be a Dictionary") return self._put( uri="/preapproval/" + self._path_param(subscription_id), data=subscription_object, request_options=request_options) mercadopago-sdk-python-b345a69/mercadopago/resources/user.py000066400000000000000000000015771524412155200242660ustar00rootroot00000000000000"""User resource for the MercadoPago API. Wraps the ``/users/me`` endpoint to retrieve the profile of the currently authenticated MercadoPago account. """ from mercadopago.core import MPBase class User(MPBase): """Retrieves the authenticated user's account information. Returns details such as user ID, email, site (country), and account status for the access token in use. """ def get(self, request_options=None): """Retrieves the authenticated user's profile. Args: request_options: Per-call configuration overrides. Returns: dict: User profile (id, email, site_id, etc.). """ return self._get(uri="/users/me", request_options=request_options) @property def request_options(self): """Default :class:`RequestOptions` for this resource instance.""" return self.__request_options mercadopago-sdk-python-b345a69/mercadopago/sdk.py000066400000000000000000000214621524412155200220520ustar00rootroot00000000000000"""Main entry point for the MercadoPago Python SDK. Instantiate :class:`SDK` with an access token to obtain factory methods for every MercadoPago API resource (payments, orders, customers, etc.). Example:: import mercadopago sdk = mercadopago.SDK("YOUR_ACCESS_TOKEN") result = sdk.payment().create({ "transaction_amount": 100, "payment_method_id": "pix", "payer": {"email": "buyer@example.com"}, }) """ from mercadopago.config import RequestOptions from mercadopago.http import HttpClient from mercadopago.resources import ( AdvancedPayment, Card, CardToken, Chargeback, Customer, DisbursementRefund, IdentificationType, Invoice, MerchantOrder, OAuth, Order, Payment, PaymentMethods, Plan, Point, PreApproval, Preference, Refund, Subscription, User, ) class SDK: # pylint: disable=too-many-public-methods """Central client providing factory methods for every API resource. Each factory method (e.g. :meth:`payment`, :meth:`order`) returns a fresh resource instance bound to the SDK's credentials and HTTP client. An optional *request_options* argument lets callers override configuration on a per-resource basis. Attributes: request_options: Default :class:`RequestOptions` applied to all resource instances unless overridden. http_client: :class:`HttpClient` used for every outgoing request. """ def __init__( self, access_token, http_client=None, request_options=None, ): """Initialises the SDK with authentication credentials. Args: access_token: OAuth access token obtained from the `MercadoPago credentials page `_. http_client: Custom :class:`HttpClient` implementation. Defaults to the built-in ``requests``-based client. request_options: Default :class:`RequestOptions` (timeout, retries, custom headers). A new instance is created if not provided. Raises: ValueError: If *request_options* is not a :class:`RequestOptions` instance. ValueError: If *http_client* is not an :class:`HttpClient` instance. """ self.http_client = http_client if http_client is None: self.http_client = HttpClient() self.request_options = request_options if request_options is None: self.request_options = RequestOptions() self.request_options.access_token = access_token def advanced_payment(self, request_options=None): """Creates an :class:`AdvancedPayment` resource for marketplace split payments.""" return AdvancedPayment(request_options is not None and request_options or self.request_options, self.http_client) def card_token(self, request_options=None): """Creates a :class:`CardToken` resource for server-side card tokenisation.""" return CardToken(request_options is not None and request_options or self.request_options, self.http_client) def card(self, request_options=None): """Creates a :class:`Card` resource to manage saved customer cards.""" return Card(request_options is not None and request_options or self.request_options, self.http_client) def customer(self, request_options=None): """Creates a :class:`Customer` resource to manage buyer profiles.""" return Customer(request_options is not None and request_options or self.request_options, self.http_client) def disbursement_refund(self, request_options=None): """Creates a :class:`DisbursementRefund` resource for advanced-payment refunds.""" return DisbursementRefund(request_options is not None and request_options or self.request_options, self.http_client) def identification_type(self, request_options=None): """Creates an :class:`IdentificationType` resource to list accepted document types.""" return IdentificationType(request_options is not None and request_options or self.request_options, self.http_client) def invoice(self, request_options=None): """Creates an :class:`Invoice` resource to retrieve subscription billing invoices.""" return Invoice(request_options is not None and request_options or self.request_options, self.http_client) def oauth(self, request_options=None): """Creates an :class:`OAuth` resource for the OAuth 2.0 authorization code flow.""" return OAuth(request_options is not None and request_options or self.request_options, self.http_client) def point(self, request_options=None): """Creates a :class:`Point` resource for in-person payments via Point devices.""" return Point(request_options is not None and request_options or self.request_options, self.http_client) def merchant_order(self, request_options=None): """Creates a :class:`MerchantOrder` resource for Checkout Pro orders.""" return MerchantOrder(request_options is not None and request_options or self.request_options, self.http_client) def order(self, request_options=None): """Creates an :class:`Order` resource for the Orders API.""" return Order(request_options is not None and request_options or self.request_options, self.http_client) def payment(self, request_options=None): """Creates a :class:`Payment` resource for the Checkout API.""" return Payment(request_options is not None and request_options or self.request_options, self.http_client) def payment_methods(self, request_options=None): """Creates a :class:`PaymentMethods` resource to list available payment methods.""" return PaymentMethods(request_options is not None and request_options or self.request_options, self.http_client) def preapproval(self, request_options=None): """Creates a :class:`PreApproval` resource for ad-hoc subscriptions.""" return PreApproval(request_options is not None and request_options or self.request_options, self.http_client) def preference(self, request_options=None): """Creates a :class:`Preference` resource for Checkout Pro sessions.""" return Preference(request_options is not None and request_options or self.request_options, self.http_client) def refund(self, request_options=None): """Creates a :class:`Refund` resource for payment refunds.""" return Refund(request_options is not None and request_options or self.request_options, self.http_client) def user(self, request_options=None): """Creates a :class:`User` resource to retrieve the authenticated account.""" return User(request_options is not None and request_options or self.request_options, self.http_client) def chargeback(self, request_options=None): """Creates a :class:`Chargeback` resource to monitor disputes.""" return Chargeback(request_options is not None and request_options or self.request_options, self.http_client) def subscription(self, request_options=None): """Creates a :class:`Subscription` resource for plan-based recurring billing.""" return Subscription(request_options is not None and request_options or self.request_options, self.http_client) def plan(self, request_options=None): """Creates a :class:`Plan` resource for subscription plan templates.""" return Plan(request_options is not None and request_options or self.request_options, self.http_client) @property def request_options(self): """Default :class:`RequestOptions` applied to all resource instances.""" return self.__request_options @request_options.setter def request_options(self, value): if value is not None and not isinstance(value, RequestOptions): raise ValueError( "Param request_options must be a RequestOptions Object") self.__request_options = value @property def http_client(self): """HTTP transport used for all outgoing API requests.""" return self.__http_client @http_client.setter def http_client(self, value): if value is not None and not isinstance(value, HttpClient): raise ValueError("Param http_client must be a HttpClient Object") self.__http_client = value mercadopago-sdk-python-b345a69/mercadopago/webhook/000077500000000000000000000000001524412155200223505ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/mercadopago/webhook/__init__.py000066400000000000000000000004421524412155200244610ustar00rootroot00000000000000""" Module: webhook/__init__.py """ from mercadopago.webhook.validator import ( InvalidWebhookSignatureError, SignatureFailureReason, WebhookSignatureValidator, ) __all__ = ( "InvalidWebhookSignatureError", "SignatureFailureReason", "WebhookSignatureValidator", ) mercadopago-sdk-python-b345a69/mercadopago/webhook/validator.py000066400000000000000000000207041524412155200247120ustar00rootroot00000000000000"""MercadoPago webhook signature validator. Verifies the authenticity of incoming webhook notifications by recomputing the HMAC-SHA256 signature locally and comparing it against the value carried in the ``x-signature`` header. The validator is stateless, performs no outbound HTTP calls, and does not depend on any SDK configuration object; the integrator passes the secret signature explicitly on every call. """ from enum import Enum import hashlib import hmac import re import time class SignatureFailureReason(Enum): """Reasons why :class:`WebhookSignatureValidator` may reject a notification. Integrators are encouraged to log this value alongside the ``x-request-id`` for correlation against the MercadoPago notifications dashboard. """ MISSING_SIGNATURE_HEADER = "MissingSignatureHeader" """The ``x-signature`` header was missing, empty, or whitespace.""" MALFORMED_SIGNATURE_HEADER = "MalformedSignatureHeader" """The header did not match the expected ``ts=...,vN=...`` format.""" MISSING_TIMESTAMP = "MissingTimestamp" """The header parsed correctly but no ``ts=`` component was present.""" MISSING_HASH = "MissingHash" """No hash was found for any of the requested ``supported_versions``.""" SIGNATURE_MISMATCH = "SignatureMismatch" """The computed HMAC did not match the value in the header.""" TIMESTAMP_OUT_OF_TOLERANCE = "TimestampOutOfTolerance" """The header timestamp fell outside the configured ``tolerance`` window.""" class InvalidWebhookSignatureError(Exception): """Raised by :func:`WebhookSignatureValidator.validate` on signature failure. Carries enough context to support structured logging without exposing internal details in the HTTP response body. Attributes: reason: Specific :class:`SignatureFailureReason` that triggered the error. request_id: ``x-request-id`` header value, when available. timestamp: ``ts`` value extracted from the signature header, when parsing reached that point. """ def __init__(self, reason, request_id=None, timestamp=None): """Initialises the error. Args: reason: Specific failure mode. request_id: ``x-request-id`` value associated with the request. timestamp: ``ts`` extracted from the header, if available. """ super().__init__(f"Invalid webhook signature: {reason.value}") self.reason = reason self.request_id = request_id self.timestamp = timestamp _DEFAULT_SUPPORTED_VERSIONS = ("v1",) _VERSION_KEY_REGEX = re.compile(r"^v\d+$") class WebhookSignatureValidator: # pylint: disable=too-few-public-methods """Stateless utility that validates the signature of a MercadoPago webhook. On failure :func:`validate` raises :class:`InvalidWebhookSignatureError`; on success it returns ``None``. The comparison is performed in constant time via :func:`hmac.compare_digest` to mitigate timing attacks. QR Code notifications are **not signed** by MercadoPago β€” do not call this validator for those events; they will always fail signature verification. """ @staticmethod def validate( # pylint: disable=too-many-arguments x_signature, x_request_id, data_id, secret, *, tolerance_seconds=None, supported_versions=None, now=None, ): """Validates the signature of a MercadoPago webhook notification. Args: x_signature: Raw value of the ``x-signature`` request header. Expected format: ``ts=,v1=``. x_request_id: Value of the ``x-request-id`` request header. May be ``None``; in that case the ``request-id:`` pair is omitted from the manifest before computing the HMAC. data_id: Value of the ``data.id`` query parameter. May be ``None``; in that case the ``id:`` pair is omitted. When present, the value is included in the manifest exactly as received. secret: Secret signature configured for the application in Tus Integraciones. tolerance_seconds: Optional maximum allowed drift in seconds between the timestamp in the header and the current clock. When ``None``, no timestamp check is performed. supported_versions: Optional ordered iterable of signature versions the validator will accept. Defaults to ``("v1",)``. The first version found in the header is used. now: Optional callable returning the current time in milliseconds since the Unix epoch. Defaults to ``time.time() * 1000``. Intended for tests. Raises: InvalidWebhookSignatureError: When the signature is missing, malformed, or does not match the expected HMAC. ValueError: When ``secret`` is ``None``. Note: The endpoint receiving webhook notifications must respond with HTTP 200 or 201 within 22 seconds. If no response is received in time, MercadoPago retries delivery every 15 minutes. Respond immediately and process the notification asynchronously to avoid timeouts. """ if secret is None: raise ValueError("secret must not be None") x_signature = _normalize(x_signature) x_request_id = _normalize(x_request_id) data_id = _normalize(data_id) versions = tuple(supported_versions) if supported_versions else _DEFAULT_SUPPORTED_VERSIONS if now is None: def now(): return int(time.time() * 1000) if x_signature is None: raise InvalidWebhookSignatureError( SignatureFailureReason.MISSING_SIGNATURE_HEADER, x_request_id ) ts, hashes = _parse_signature_header(x_signature) if ts is None and not hashes: raise InvalidWebhookSignatureError( SignatureFailureReason.MALFORMED_SIGNATURE_HEADER, x_request_id ) if ts is None: raise InvalidWebhookSignatureError( SignatureFailureReason.MISSING_TIMESTAMP, x_request_id ) if not ts.isdigit(): raise InvalidWebhookSignatureError( SignatureFailureReason.MALFORMED_SIGNATURE_HEADER, x_request_id, ts ) received_hash = None for version in versions: if version in hashes: received_hash = hashes[version] break if received_hash is None: raise InvalidWebhookSignatureError( SignatureFailureReason.MISSING_HASH, x_request_id, ts ) manifest = _build_manifest(data_id, x_request_id, ts) computed = hmac.new( secret.encode("utf-8"), manifest.encode("utf-8"), hashlib.sha256 ).hexdigest() if not hmac.compare_digest(computed, received_hash): raise InvalidWebhookSignatureError( SignatureFailureReason.SIGNATURE_MISMATCH, x_request_id, ts ) if tolerance_seconds is not None: drift_ms = abs(now() - int(ts) * 1000) # ts is in seconds, now() is in ms if drift_ms > tolerance_seconds * 1000: raise InvalidWebhookSignatureError( SignatureFailureReason.TIMESTAMP_OUT_OF_TOLERANCE, x_request_id, ts ) def _normalize(value): """Returns the trimmed string or ``None`` for missing/whitespace values.""" if value is None: return None text = str(value).strip() return text if text else None def _parse_signature_header(header): """Parses the ``x-signature`` header into ``(ts, {vN: hash})``.""" hashes = {} ts = None for part in header.split(","): if "=" not in part: continue key, value = part.split("=", 1) key = key.strip().lower() value = value.strip() if not key or not value: continue if key == "ts": ts = value elif _VERSION_KEY_REGEX.match(key): hashes[key] = value return ts, hashes def _build_manifest(data_id, request_id, ts): """Builds the HMAC manifest, omitting empty pairs per the documented rule.""" parts = [] if data_id: parts.append(f"id:{data_id}") if request_id: parts.append(f"request-id:{request_id}") parts.append(f"ts:{ts}") return ";".join(parts) + ";" mercadopago-sdk-python-b345a69/pyproject.toml000066400000000000000000000017641524412155200213550ustar00rootroot00000000000000[build-system] requires = ["setuptools >= 83.0.0"] build-backend = "setuptools.build_meta" [project] name = "mercadopago" version = "3.6.0" authors = [ {name = "Mercado Pago", email = "mp_sdk@mercadopago.com"} ] description = "Mercadopago SDK module for Payments integration" readme = "README.md" keywords = ["api", "mercadopago", "checkout", "payment in sdk integration", "lts"] license = {file = "LICENSE"} requires-python = ">=3.10" dependencies = [ "requests>=2.33.0,<3" ] classifiers = [ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", ] [project.optional-dependencies] testing = [ "unittest" ] [project.urls] Homepage = "https://mercadopago.com" Repository = "https://github.com/mercadopago/sdk-python" mercadopago-sdk-python-b345a69/setup.cfg000066400000000000000000000013751524412155200202600ustar00rootroot00000000000000[pylint.MASTER] py-version = 3.10 [pylint.DESIGN] max-args = 7 max-positional-arguments = 7 [pylint.FORMAT] max-line-length = 100 ignore-long-lines = ^\s*((`[^`]*`?\s+)??`?_?|Reference:\s+https?://\S+)(\s+.*)?$ [isort] # Vertical Hanging Indent multi_line_output = 3 # Formatting settings line_length = 120 include_trailing_comma = 1 combine_as_imports = 1 force_grid_wrap = 2 use_parentheses = 1 force_sort_within_sections = 1 lines_after_imports = 2 skip_glob = *.git/*,*.env/*,*/docs/*,*/build/*,*/.eggs/*,*.egg-info/* default_section = THIRDPARTY sections = FUTURE,STDLIB,THIRDPARTY,CURRENT_PROJECT,LOCALFOLDER,TESTS no_lines_before = LOCALFOLDER # Section for specific project imports known_current_project = mercadopago known_tests = tests mercadopago-sdk-python-b345a69/tests/000077500000000000000000000000001524412155200175735ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/tests/.pylintrc000066400000000000000000000004731524412155200214440ustar00rootroot00000000000000[FORMAT] max-line-length = 110 [DESIGN] max-args = 7 max-positional-arguments = 7 [MESSAGES CONTROL] disable = missing-docstring, duplicate-code, import-error, import-outside-toplevel, arguments-differ, unused-argument, unidiomatic-typecheck, use-implicit-booleaness-not-comparison mercadopago-sdk-python-b345a69/tests/__init__.py000066400000000000000000000007271524412155200217120ustar00rootroot00000000000000""" Tests package """ import time def api_call_with_retry(fn, expected_status, retries=3, delay=5): """Call fn() up to `retries` times, returning the response once it matches expected_status. Returns the last response if all attempts are exhausted.""" response = fn() for _ in range(retries - 1): if response.get("status") == expected_status: return response time.sleep(delay) response = fn() return response mercadopago-sdk-python-b345a69/tests/base_client_test.py000066400000000000000000000045471524412155200234660ustar00rootroot00000000000000"""Base class for mock-based unit tests of MercadoPago SDK resources.""" import json import os import unittest from unittest.mock import MagicMock import mercadopago from mercadopago.http.http_client import HttpClient def _load_fixture(filename): """Load a JSON fixture from tests/resources/mocks/.""" base = os.path.dirname(__file__) path = os.path.join(base, "resources", "mocks", filename) with open(path, encoding="utf-8") as fh: return json.load(fh) class BaseClientTest(unittest.TestCase): """Provides a mock HTTP client and an SDK instance for unit tests. Sub-classes should call ``self.mock_get``, ``self.mock_post``, ``self.mock_put``, or ``self.mock_delete`` to set up the expected response *before* calling the resource method under test. """ def setUp(self): self.mock_http = MagicMock(spec=HttpClient) self.sdk = mercadopago.SDK("TEST_TOKEN", http_client=self.mock_http) # ------------------------------------------------------------------ # Helpers – configure the mock for a single HTTP verb # ------------------------------------------------------------------ def mock_get(self, response_dict, status=200): """Make the next ``http_client.get(...)`` return *response_dict*.""" self.mock_http.get.return_value = {"status": status, "response": response_dict} def mock_post(self, response_dict, status=201): """Make the next ``http_client.post(...)`` return *response_dict*.""" self.mock_http.post.return_value = {"status": status, "response": response_dict} def mock_put(self, response_dict, status=200): """Make the next ``http_client.put(...)`` return *response_dict*.""" self.mock_http.put.return_value = {"status": status, "response": response_dict} def mock_delete(self, response_dict=None, status=204): """Make the next ``http_client.delete(...)`` return *response_dict*.""" self.mock_http.delete.return_value = {"status": status, "response": response_dict} # ------------------------------------------------------------------ # Fixture loader exposed to sub-classes # ------------------------------------------------------------------ @staticmethod def load_fixture(filename): """Return the parsed JSON fixture *filename* from resources/mocks/.""" return _load_fixture(filename) mercadopago-sdk-python-b345a69/tests/resources/000077500000000000000000000000001524412155200216055ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/tests/resources/mocks/000077500000000000000000000000001524412155200227215ustar00rootroot00000000000000mercadopago-sdk-python-b345a69/tests/resources/mocks/advanced_payment_create.json000066400000000000000000000012641524412155200304440ustar00rootroot00000000000000{ "id": 999, "status": "pending", "status_detail": "pending_waiting_payment", "application_id": "app-001", "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:00.000-03:00", "payer": { "email": "test_user@testuser.com", "identification": {"type": "CPF", "number": "19119119100"} }, "payments": [ { "id": 1001, "status": "pending", "payment_method_id": "visa", "transaction_amount": 100.0, "installments": 1 } ], "disbursements": [ { "id": 2001, "collector_id": 843382748, "amount": 100.0, "external_reference": "ref-001", "status": "pending" } ] } mercadopago-sdk-python-b345a69/tests/resources/mocks/advanced_payment_get.json000066400000000000000000000013351524412155200277570ustar00rootroot00000000000000{ "id": 999, "status": "approved", "status_detail": "accredited", "application_id": "app-001", "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:01.000-03:00", "payer": { "id": "123456789", "email": "test_user@testuser.com", "identification": {"type": "CPF", "number": "19119119100"} }, "payments": [ { "id": 1001, "status": "approved", "payment_method_id": "visa", "transaction_amount": 100.0, "installments": 1, "token": "token-001" } ], "disbursements": [ { "id": 2001, "collector_id": 843382748, "amount": 100.0, "external_reference": "ref-001", "status": "approved" } ] } mercadopago-sdk-python-b345a69/tests/resources/mocks/advanced_payment_search.json000066400000000000000000000004231524412155200304420ustar00rootroot00000000000000{ "results": [ { "id": 999, "status": "approved", "status_detail": "accredited", "date_created": "2024-01-15T10:30:00.000-03:00", "payer": {"email": "test_user@testuser.com"} } ], "paging": {"total": 1, "limit": 10, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/advanced_payment_update.json000066400000000000000000000002011524412155200304510ustar00rootroot00000000000000{ "id": 999, "status": "approved", "status_detail": "accredited", "date_last_updated": "2024-01-15T11:00:00.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/card_create.json000066400000000000000000000011171524412155200260500ustar00rootroot00000000000000{ "id": "1562188766852", "customer_id": "1068193981-pXRewrKqlP6pnn", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:00.000-03:00", "cardholder": {"name": "APRO", "identification": {"type": "CPF", "number": "19119119100"}}, "payment_method": {"id": "master", "name": "Mastercard", "payment_type_id": "credit_card"}, "issuer": {"id": "24", "name": "Mastercard"}, "security_code": {"length": 3, "card_location": "back"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/card_get.json000066400000000000000000000011171524412155200253640ustar00rootroot00000000000000{ "id": "1562188766852", "customer_id": "1068193981-pXRewrKqlP6pnn", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:00.000-03:00", "cardholder": {"name": "APRO", "identification": {"type": "CPF", "number": "19119119100"}}, "payment_method": {"id": "master", "name": "Mastercard", "payment_type_id": "credit_card"}, "issuer": {"id": "24", "name": "Mastercard"}, "security_code": {"length": 3, "card_location": "back"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/card_list_all.json000066400000000000000000000006741524412155200264170ustar00rootroot00000000000000[ { "id": "1562188766852", "customer_id": "1068193981-pXRewrKqlP6pnn", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "cardholder": {"name": "APRO"}, "payment_method": {"id": "master", "name": "Mastercard", "payment_type_id": "credit_card"}, "issuer": {"id": "24", "name": "Mastercard"} } ] mercadopago-sdk-python-b345a69/tests/resources/mocks/card_token_create.json000066400000000000000000000006271524412155200272550ustar00rootroot00000000000000{ "id": "a78sd6f1a9s8d7f1a", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "date_due": "2024-01-15T12:30:00.000-03:00", "luhn_validation": true, "status": "active", "card_id": null, "cardholder": {"name": "APRO", "identification": {"type": "CPF", "number": "19119119100"}} } mercadopago-sdk-python-b345a69/tests/resources/mocks/card_token_get.json000066400000000000000000000006271524412155200265710ustar00rootroot00000000000000{ "id": "a78sd6f1a9s8d7f1a", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "date_due": "2024-01-15T12:30:00.000-03:00", "luhn_validation": true, "status": "active", "card_id": null, "cardholder": {"name": "APRO", "identification": {"type": "CPF", "number": "19119119100"}} } mercadopago-sdk-python-b345a69/tests/resources/mocks/card_update.json000066400000000000000000000010231524412155200260630ustar00rootroot00000000000000{ "id": "1562188766852", "customer_id": "1068193981-pXRewrKqlP6pnn", "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T11:00:00.000-03:00", "cardholder": {"name": "APRO"}, "payment_method": {"id": "master", "name": "Mastercard", "payment_type_id": "credit_card"}, "issuer": {"id": "24", "name": "Mastercard"}, "security_code": {"length": 3, "card_location": "back"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/chargeback_get.json000066400000000000000000000003111524412155200265200ustar00rootroot00000000000000{ "id": "cb-001", "payment_id": 17014025134, "amount": 58.80, "status": "in_process", "date_created": "2024-01-20T09:00:00.000-03:00", "currency_id": "BRL", "reason": "buyer_complaint" } mercadopago-sdk-python-b345a69/tests/resources/mocks/chargeback_search.json000066400000000000000000000003711524412155200272140ustar00rootroot00000000000000{ "results": [ { "id": "cb-001", "payment_id": 17014025134, "amount": 58.80, "status": "in_process", "date_created": "2024-01-20T09:00:00.000-03:00" } ], "paging": {"total": 1, "limit": 10, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/customer_create.json000066400000000000000000000011131524412155200267740ustar00rootroot00000000000000{ "id": "1068193981-pXRewrKqlP6pnn", "email": "test_user@testuser.com", "first_name": "Test", "last_name": "User", "phone": {"area_code": "11", "number": "987654321"}, "identification": {"type": "CPF", "number": "19119119100"}, "address": {"zip_code": "01313000", "street_name": "Av Paulista", "street_number": "1000"}, "date_registered": "2024-01-01T00:00:00.000-03:00", "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:00.000-03:00", "description": "Test customer", "metadata": {}, "cards": [], "default_card": null } mercadopago-sdk-python-b345a69/tests/resources/mocks/customer_delete.json000066400000000000000000000000501524412155200267720ustar00rootroot00000000000000{ "id": "1068193981-pXRewrKqlP6pnn" } mercadopago-sdk-python-b345a69/tests/resources/mocks/customer_get.json000066400000000000000000000011131524412155200263100ustar00rootroot00000000000000{ "id": "1068193981-pXRewrKqlP6pnn", "email": "test_user@testuser.com", "first_name": "Test", "last_name": "User", "phone": {"area_code": "11", "number": "987654321"}, "identification": {"type": "CPF", "number": "19119119100"}, "address": {"zip_code": "01313000", "street_name": "Av Paulista", "street_number": "1000"}, "date_registered": "2024-01-01T00:00:00.000-03:00", "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T10:30:00.000-03:00", "description": "Test customer", "metadata": {}, "cards": [], "default_card": null } mercadopago-sdk-python-b345a69/tests/resources/mocks/customer_search.json000066400000000000000000000004261524412155200270040ustar00rootroot00000000000000{ "results": [ { "id": "1068193981-pXRewrKqlP6pnn", "email": "test_user@testuser.com", "first_name": "Test", "last_name": "User", "date_created": "2024-01-15T10:30:00.000-03:00" } ], "paging": {"total": 1, "limit": 30, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/customer_update.json000066400000000000000000000006301524412155200270160ustar00rootroot00000000000000{ "id": "1068193981-pXRewrKqlP6pnn", "email": "test_user@testuser.com", "first_name": "Test", "last_name": "Updated", "phone": {"area_code": "11", "number": "987654321"}, "identification": {"type": "CPF", "number": "19119119100"}, "date_created": "2024-01-15T10:30:00.000-03:00", "date_last_updated": "2024-01-15T11:00:00.000-03:00", "metadata": {}, "cards": [], "default_card": null } mercadopago-sdk-python-b345a69/tests/resources/mocks/disbursement_refund_create.json000066400000000000000000000002041524412155200312020ustar00rootroot00000000000000{ "id": 2, "disbursement_id": 10, "amount": 25.0, "status": "approved", "date_created": "2024-01-16T09:00:00.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/disbursement_refund_create_all.json000066400000000000000000000002121524412155200320310ustar00rootroot00000000000000{ "id": 1, "advanced_payment_id": 999, "status": "approved", "amount": 100.0, "date_created": "2024-01-16T09:00:00.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/disbursement_refund_list_all.json000066400000000000000000000002331524412155200315440ustar00rootroot00000000000000[ { "id": 1, "advanced_payment_id": 999, "amount": 50.0, "status": "approved", "date_created": "2024-01-16T09:00:00.000-03:00" } ] mercadopago-sdk-python-b345a69/tests/resources/mocks/identification_type_list_all.json000066400000000000000000000002531524412155200315310ustar00rootroot00000000000000[{"id": "CPF", "name": "CPF", "type": "number", "min_length": 11, "max_length": 11}, {"id": "CNPJ", "name": "CNPJ", "type": "number", "min_length": 14, "max_length": 14}] mercadopago-sdk-python-b345a69/tests/resources/mocks/invoice_get.json000066400000000000000000000004051524412155200261060ustar00rootroot00000000000000{ "id": "inv-001", "status": "processed", "transaction_amount": 29.90, "currency_id": "BRL", "preapproval_id": "2c938084726fca480172750000000000", "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:01.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/invoice_search.json000066400000000000000000000004741524412155200266020ustar00rootroot00000000000000{ "results": [ { "id": "inv-001", "status": "processed", "transaction_amount": 29.90, "currency_id": "BRL", "preapproval_id": "2c938084726fca480172750000000000", "date_created": "2024-01-15T10:30:00.000-03:00" } ], "paging": {"total": 1, "limit": 10, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/merchant_order_create.json000066400000000000000000000011041524412155200301270ustar00rootroot00000000000000{ "id": 4049696864, "status": "opened", "external_reference": "ext-ref-001", "preference_id": "843382748-18d90a57-a4ce-4718", "payments": [], "items": [ { "id": "item-001", "title": "Point Mini", "description": "Maquininha", "quantity": 1, "unit_price": 58.80, "currency_id": "BRL" } ], "date_created": "2024-01-15T10:30:00.000-03:00", "last_updated": "2024-01-15T10:30:00.000-03:00", "total_amount": 58.80, "paid_amount": 0.0, "refunded_amount": 0.0, "notification_url": "https://example.com/notifications" } mercadopago-sdk-python-b345a69/tests/resources/mocks/merchant_order_get.json000066400000000000000000000011041524412155200274430ustar00rootroot00000000000000{ "id": 4049696864, "status": "opened", "external_reference": "ext-ref-001", "preference_id": "843382748-18d90a57-a4ce-4718", "payments": [], "items": [ { "id": "item-001", "title": "Point Mini", "description": "Maquininha", "quantity": 1, "unit_price": 58.80, "currency_id": "BRL" } ], "date_created": "2024-01-15T10:30:00.000-03:00", "last_updated": "2024-01-15T10:30:00.000-03:00", "total_amount": 58.80, "paid_amount": 0.0, "refunded_amount": 0.0, "notification_url": "https://example.com/notifications" } mercadopago-sdk-python-b345a69/tests/resources/mocks/merchant_order_search.json000066400000000000000000000004551524412155200301410ustar00rootroot00000000000000{ "elements": [ { "id": 4049696864, "status": "opened", "external_reference": "ext-ref-001", "preference_id": "843382748-18d90a57-a4ce-4718", "total_amount": 58.80, "date_created": "2024-01-15T10:30:00.000-03:00" } ], "total": 1, "next_offset": 0 } mercadopago-sdk-python-b345a69/tests/resources/mocks/merchant_order_update.json000066400000000000000000000003231524412155200301500ustar00rootroot00000000000000{ "id": 4049696864, "status": "opened", "external_reference": "ext-updated", "preference_id": "843382748-18d90a57-a4ce-4718", "last_updated": "2024-01-15T11:00:00.000-03:00", "total_amount": 58.80 } mercadopago-sdk-python-b345a69/tests/resources/mocks/oauth_create.json000066400000000000000000000003461524412155200262620ustar00rootroot00000000000000{ "access_token": "APP_USR-001", "token_type": "bearer", "expires_in": 15552000, "scope": "offline_access payments read write", "user_id": 123456789, "refresh_token": "TG-001-test-refresh-token", "live_mode": true } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_cancel.json000066400000000000000000000002661524412155200262400ustar00rootroot00000000000000{ "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "status": "canceled", "status_detail": "order_canceled", "total_amount": "1000.00", "last_updated_date": "2024-01-15T11:00:00.000Z" } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_capture.json000066400000000000000000000003321524412155200264500ustar00rootroot00000000000000{ "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "status": "processed", "status_detail": "fully_processed", "total_amount": "1000.00", "total_paid_amount": "1000.00", "last_updated_date": "2024-01-15T10:30:02.000Z" } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_create.json000066400000000000000000000016071524412155200262560ustar00rootroot00000000000000{ "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "type": "online", "processing_mode": "automatic", "capture_mode": "automatic_async", "status": "processed", "status_detail": "fully_processed", "external_reference": "ext-ref-001", "total_amount": "1000.00", "total_paid_amount": "1000.00", "description": "Order description", "country_code": "BR", "created_date": "2024-01-15T10:30:00.000Z", "last_updated_date": "2024-01-15T10:30:01.000Z", "payer": {"email": "test_user@testuser.com", "entity_type": "individual"}, "items": [{"id": "item-001", "title": "Point Mini", "quantity": 1, "unit_price": "1000.00"}], "transactions": { "payments": [ { "id": "pay-001", "amount": "1000.00", "status": "processed", "reference_id": "ref-001", "status_detail": "accredited" } ] }, "integration_data": {"application_id": "12345"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_get.json000066400000000000000000000016071524412155200255720ustar00rootroot00000000000000{ "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "type": "online", "processing_mode": "automatic", "capture_mode": "automatic_async", "status": "processed", "status_detail": "fully_processed", "external_reference": "ext-ref-001", "total_amount": "1000.00", "total_paid_amount": "1000.00", "description": "Order description", "country_code": "BR", "created_date": "2024-01-15T10:30:00.000Z", "last_updated_date": "2024-01-15T10:30:01.000Z", "payer": {"email": "test_user@testuser.com", "entity_type": "individual"}, "items": [{"id": "item-001", "title": "Point Mini", "quantity": 1, "unit_price": "1000.00"}], "transactions": { "payments": [ { "id": "pay-001", "amount": "1000.00", "status": "processed", "reference_id": "ref-001", "status_detail": "accredited" } ] }, "integration_data": {"application_id": "12345"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_process.json000066400000000000000000000003321524412155200264630ustar00rootroot00000000000000{ "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "status": "processed", "status_detail": "fully_processed", "total_amount": "1000.00", "total_paid_amount": "1000.00", "last_updated_date": "2024-01-15T10:30:01.000Z" } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_refund.json000066400000000000000000000001771524412155200262770ustar00rootroot00000000000000{ "id": "refund-01JKXTQ2-001", "status": "approved", "amount": "1000.00", "date_created": "2024-01-16T09:00:00.000Z" } mercadopago-sdk-python-b345a69/tests/resources/mocks/order_search.json000066400000000000000000000004411524412155200262530ustar00rootroot00000000000000{ "data": [ { "id": "01JKXTQ2AZVE0RANCPYA6WBNPW", "status": "processed", "total_amount": "1000.00", "created_date": "2024-01-15T10:30:00.000Z", "payer": {"email": "test_user@testuser.com"} } ], "paging": {"total": 1, "limit": 10, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/payment_create.json000066400000000000000000000016171524412155200266210ustar00rootroot00000000000000{ "id": 17014025134, "date_created": "2024-01-15T10:30:00.000-03:00", "date_approved": null, "date_last_updated": "2024-01-15T10:30:00.000-03:00", "operation_type": "regular_payment", "issuer_id": "24", "payment_method_id": "visa", "payment_type_id": "credit_card", "status": "pending", "status_detail": "pending_waiting_payment", "currency_id": "BRL", "description": "Point Mini", "transaction_amount": 58.80, "transaction_amount_refunded": 0.0, "coupon_amount": 0.0, "captured": false, "binary_mode": false, "installments": 1, "processing_mode": "aggregator", "external_reference": "MP0001", "payer": { "email": "test_user@testuser.com", "identification": {"type": "CPF", "number": "19119119100"} }, "transaction_details": { "net_received_amount": 0.0, "total_paid_amount": 58.80, "overpaid_amount": 0.0, "installment_amount": 58.80 } } mercadopago-sdk-python-b345a69/tests/resources/mocks/payment_get.json000066400000000000000000000025041524412155200261310ustar00rootroot00000000000000{ "id": 17014025134, "date_created": "2024-01-15T10:30:00.000-03:00", "date_approved": "2024-01-15T10:30:01.000-03:00", "date_last_updated": "2024-01-15T10:30:01.000-03:00", "date_of_expiration": null, "money_release_date": "2024-01-29T10:30:01.000-03:00", "operation_type": "regular_payment", "issuer_id": "24", "payment_method_id": "visa", "payment_type_id": "credit_card", "status": "approved", "status_detail": "accredited", "currency_id": "BRL", "description": "Point Mini", "transaction_amount": 58.80, "transaction_amount_refunded": 0.0, "coupon_amount": 0.0, "captured": true, "binary_mode": false, "installments": 1, "statement_descriptor": "MercadoPago", "processing_mode": "aggregator", "external_reference": "MP0001", "notification_url": null, "payer": { "id": "123456789", "email": "test_user@testuser.com", "identification": {"type": "CPF", "number": "19119119100"}, "type": "customer" }, "metadata": {}, "additional_info": {}, "transaction_details": { "net_received_amount": 56.86, "total_paid_amount": 58.80, "overpaid_amount": 0.0, "installment_amount": 58.80 }, "card": { "first_six_digits": "503143", "last_four_digits": "6351", "expiration_month": 11, "expiration_year": 2030, "cardholder": {"name": "APRO"} } } mercadopago-sdk-python-b345a69/tests/resources/mocks/payment_methods_list_all.json000066400000000000000000000002651524412155200307020ustar00rootroot00000000000000[{"id": "visa", "name": "Visa", "payment_type_id": "credit_card", "status": "active"}, {"id": "master", "name": "Mastercard", "payment_type_id": "credit_card", "status": "active"}] mercadopago-sdk-python-b345a69/tests/resources/mocks/payment_search.json000066400000000000000000000010161524412155200266140ustar00rootroot00000000000000{ "results": [ { "id": 17014025134, "status": "approved", "status_detail": "accredited", "transaction_amount": 58.80, "payment_method_id": "visa", "payment_type_id": "credit_card", "currency_id": "BRL", "date_created": "2024-01-15T10:30:00.000-03:00", "date_approved": "2024-01-15T10:30:01.000-03:00", "payer": {"email": "test_user@testuser.com"}, "installments": 1, "captured": true } ], "paging": {"total": 1, "limit": 30, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/payment_update.json000066400000000000000000000003421524412155200266320ustar00rootroot00000000000000{ "id": 17014025134, "status": "cancelled", "status_detail": "by_collector", "date_last_updated": "2024-01-15T11:00:00.000-03:00", "transaction_amount": 58.80, "payment_method_id": "visa", "currency_id": "BRL" } mercadopago-sdk-python-b345a69/tests/resources/mocks/plan_create.json000066400000000000000000000007131524412155200260720ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000002", "reason": "Monthly Plan - Basic", "status": "active", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "init_point": "https://www.mercadopago.com.br/subscriptions/checkout?plan_id=2c938084726fca480172750000000002" } mercadopago-sdk-python-b345a69/tests/resources/mocks/plan_get.json000066400000000000000000000007131524412155200254060ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000002", "reason": "Monthly Plan - Basic", "status": "active", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "init_point": "https://www.mercadopago.com.br/subscriptions/checkout?plan_id=2c938084726fca480172750000000002" } mercadopago-sdk-python-b345a69/tests/resources/mocks/plan_search.json000066400000000000000000000003771524412155200261020ustar00rootroot00000000000000{ "results": [ { "id": "2c938084726fca480172750000000002", "status": "active", "reason": "Monthly Plan - Basic", "date_created": "2024-01-15T10:30:00.000-03:00" } ], "paging": {"total": 1, "limit": 30, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/plan_update.json000066400000000000000000000004501524412155200261070ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000002", "reason": "Monthly Plan - Basic", "status": "inactive", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "last_modified": "2024-01-15T11:00:00.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/point_create.json000066400000000000000000000003561524412155200262740ustar00rootroot00000000000000{ "id": "intent-001", "state": "OPEN", "device_id": "device-001", "amount": 58.80, "description": "Test payment", "payment": {"installments": 1, "type": "credit_card"}, "additional_info": {"external_reference": "ref-001"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/point_get.json000066400000000000000000000003621524412155200256050ustar00rootroot00000000000000{ "id": "intent-001", "state": "FINISHED", "device_id": "device-001", "amount": 58.80, "description": "Test payment", "payment": {"installments": 1, "type": "credit_card"}, "additional_info": {"external_reference": "ref-001"} } mercadopago-sdk-python-b345a69/tests/resources/mocks/point_get_devices.json000066400000000000000000000002251524412155200273050ustar00rootroot00000000000000{ "devices": [ { "id": "device-001", "operating_mode": "PDV", "store_id": "store-001", "pos_id": "pos-001" } ] } mercadopago-sdk-python-b345a69/tests/resources/mocks/preapproval_create.json000066400000000000000000000012341524412155200274720ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000000", "payer_id": 123456789, "payer_email": "test_user@testuser.com", "preapproval_plan_id": "2c938084726fca480172750000000001", "reason": "Monthly subscription", "external_reference": "sub-ext-001", "status": "pending", "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "payment_method_id": "master", "init_point": "https://www.mercadopago.com.br/subscriptions/checkout?preapproval_id=2c938084726fca480172750000000000" } mercadopago-sdk-python-b345a69/tests/resources/mocks/preapproval_get.json000066400000000000000000000013521524412155200270070ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000000", "payer_id": 123456789, "payer_email": "test_user@testuser.com", "preapproval_plan_id": "2c938084726fca480172750000000001", "reason": "Monthly subscription", "external_reference": "sub-ext-001", "status": "authorized", "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "next_payment_date": "2024-02-15T10:30:00.000-03:00", "payment_method_id": "master", "card_id": null, "init_point": "https://www.mercadopago.com.br/subscriptions/checkout?preapproval_id=2c938084726fca480172750000000000" } mercadopago-sdk-python-b345a69/tests/resources/mocks/preapproval_search.json000066400000000000000000000004621524412155200274760ustar00rootroot00000000000000{ "results": [ { "id": "2c938084726fca480172750000000000", "status": "authorized", "reason": "Monthly subscription", "payer_email": "test_user@testuser.com", "date_created": "2024-01-15T10:30:00.000-03:00" } ], "paging": {"total": 1, "limit": 30, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/preapproval_update.json000066400000000000000000000003131524412155200275060ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000000", "status": "cancelled", "reason": "Monthly subscription", "last_modified": "2024-01-15T11:00:00.000-03:00", "payer_email": "test_user@testuser.com" } mercadopago-sdk-python-b345a69/tests/resources/mocks/preference_create.json000066400000000000000000000017641524412155200272650ustar00rootroot00000000000000{ "id": "843382748-18d90a57-a4ce-4718-bc17-1234567890", "init_point": "https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=843382748-18d90a57-a4ce-4718-bc17-1234567890", "items": [ { "id": "item-001", "title": "Point Mini", "description": "Maquininha BT", "quantity": 1, "unit_price": 58.80, "currency_id": "BRL" } ], "payer": { "name": "Test", "surname": "User", "email": "test_user@testuser.com" }, "payment_methods": { "installments": 12, "excluded_payment_types": [] }, "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "external_reference": "MP-PREF-001", "date_created": "2024-01-15T10:30:00.000-03:00", "last_updated": "2024-01-15T10:30:00.000-03:00", "total_amount": 58.80, "expires": false, "collector_id": 843382748, "client_id": "12345", "marketplace": "NONE", "marketplace_fee": 0.0 } mercadopago-sdk-python-b345a69/tests/resources/mocks/preference_get.json000066400000000000000000000020621524412155200265710ustar00rootroot00000000000000{ "id": "843382748-18d90a57-a4ce-4718-bc17-1234567890", "init_point": "https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=843382748-18d90a57-a4ce-4718-bc17-1234567890", "items": [ { "id": "item-001", "title": "Point Mini", "description": "Maquininha BT", "quantity": 1, "unit_price": 58.80, "currency_id": "BRL" } ], "payer": { "name": "Test", "surname": "User", "email": "test_user@testuser.com" }, "payment_methods": { "installments": 12, "excluded_payment_types": [] }, "back_urls": { "success": "https://example.com/success", "failure": "https://example.com/failure", "pending": "https://example.com/pending" }, "external_reference": "MP-PREF-001", "date_created": "2024-01-15T10:30:00.000-03:00", "last_updated": "2024-01-15T10:30:00.000-03:00", "total_amount": 58.80, "expires": false, "expiration_date_from": null, "expiration_date_to": null, "collector_id": 843382748, "client_id": "12345", "marketplace": "NONE", "marketplace_fee": 0.0 } mercadopago-sdk-python-b345a69/tests/resources/mocks/preference_search.json000066400000000000000000000001011524412155200272470ustar00rootroot00000000000000{"elements": [{"id": "pref-001"}], "total": 1, "next_offset": 0} mercadopago-sdk-python-b345a69/tests/resources/mocks/preference_update.json000066400000000000000000000010001524412155200272630ustar00rootroot00000000000000{ "id": "843382748-18d90a57-a4ce-4718-bc17-1234567890", "init_point": "https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=843382748-18d90a57-a4ce-4718-bc17-1234567890", "items": [ { "id": "item-002", "title": "Updated Item", "quantity": 1, "unit_price": 30.0, "currency_id": "BRL" } ], "external_reference": "MP-PREF-001", "date_created": "2024-01-15T10:30:00.000-03:00", "last_updated": "2024-01-15T11:00:00.000-03:00", "collector_id": 843382748 } mercadopago-sdk-python-b345a69/tests/resources/mocks/refund_create.json000066400000000000000000000003711524412155200264230ustar00rootroot00000000000000{ "id": 1091618291, "payment_id": 17014025134, "amount": 58.80, "date_created": "2024-01-16T09:00:00.000-03:00", "source": {"id": "123456789", "name": "Test User", "type": "operator"}, "refund_mode": "standard", "status": "approved" } mercadopago-sdk-python-b345a69/tests/resources/mocks/refund_get.json000066400000000000000000000003711524412155200257370ustar00rootroot00000000000000{ "id": 1091618291, "payment_id": 17014025134, "amount": 58.80, "date_created": "2024-01-16T09:00:00.000-03:00", "source": {"id": "123456789", "name": "Test User", "type": "operator"}, "refund_mode": "standard", "status": "approved" } mercadopago-sdk-python-b345a69/tests/resources/mocks/refund_list_all.json000066400000000000000000000004171524412155200267640ustar00rootroot00000000000000[ { "id": 1091618291, "payment_id": 17014025134, "amount": 58.80, "date_created": "2024-01-16T09:00:00.000-03:00", "source": {"id": "123456789", "name": "Test User", "type": "operator"}, "refund_mode": "standard", "status": "approved" } ] mercadopago-sdk-python-b345a69/tests/resources/mocks/subscription_create.json000066400000000000000000000010431524412155200276610ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000003", "payer_id": 123456789, "payer_email": "test_user@testuser.com", "preapproval_plan_id": "2c938084726fca480172750000000002", "reason": "Monthly subscription", "external_reference": "sub-ext-001", "status": "pending", "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "payment_method_id": "master" } mercadopago-sdk-python-b345a69/tests/resources/mocks/subscription_get.json000066400000000000000000000011361524412155200272000ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000003", "payer_id": 123456789, "payer_email": "test_user@testuser.com", "preapproval_plan_id": "2c938084726fca480172750000000002", "reason": "Monthly subscription", "external_reference": "sub-ext-001", "status": "authorized", "date_created": "2024-01-15T10:30:00.000-03:00", "last_modified": "2024-01-15T10:30:00.000-03:00", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL" }, "next_payment_date": "2024-02-15T10:30:00.000-03:00", "payment_method_id": "master" } mercadopago-sdk-python-b345a69/tests/resources/mocks/subscription_search.json000066400000000000000000000005631524412155200276710ustar00rootroot00000000000000{ "results": [ { "id": "2c938084726fca480172750000000003", "status": "authorized", "reason": "Monthly subscription", "payer_email": "test_user@testuser.com", "preapproval_plan_id": "2c938084726fca480172750000000002", "date_created": "2024-01-15T10:30:00.000-03:00" } ], "paging": {"total": 1, "limit": 30, "offset": 0} } mercadopago-sdk-python-b345a69/tests/resources/mocks/subscription_update.json000066400000000000000000000003131524412155200276770ustar00rootroot00000000000000{ "id": "2c938084726fca480172750000000003", "status": "cancelled", "reason": "Monthly subscription", "payer_email": "test_user@testuser.com", "last_modified": "2024-01-15T11:00:00.000-03:00" } mercadopago-sdk-python-b345a69/tests/resources/mocks/user_get.json000066400000000000000000000001211524412155200254230ustar00rootroot00000000000000{"id": 12345, "email": "test@example.com", "site_id": "MLB", "country_id": "BR"} mercadopago-sdk-python-b345a69/tests/test_advanced_payment.py000066400000000000000000000113321524412155200245060ustar00rootroot00000000000000"""Unit tests for the AdvancedPayment resource using a mock HTTP client.""" from datetime import datetime import unittest from tests.base_client_test import BaseClientTest class TestAdvancedPayment(BaseClientTest): """Test Module: AdvancedPayment""" def test_get(self): fixture = self.load_fixture("advanced_payment_get.json") self.mock_get(fixture) result = self.sdk.advanced_payment().get(999) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertEqual("approved", resp["status"]) self.assertEqual("accredited", resp["status_detail"]) self.assertEqual("test_user@testuser.com", resp["payer"]["email"]) self.assertIsInstance(resp["payments"], list) self.assertEqual(1001, resp["payments"][0]["id"]) self.assertEqual("approved", resp["payments"][0]["status"]) self.assertIsInstance(resp["disbursements"], list) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("advanced_payment_create.json") self.mock_post(fixture, status=201) advanced_payment_object = { "application_id": "app-001", "payments": [{"payment_method_id": "visa", "token": "token-001", "transaction_amount": 100.0, "installments": 1}], "disbursements": [{"collector_id": 843382748, "amount": 100.0, "external_reference": "ref-001"}], "payer": {"email": "test_user@testuser.com"}, } result = self.sdk.advanced_payment().create(advanced_payment_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertEqual("pending", resp["status"]) self.assertIsInstance(resp["payments"], list) self.assertIsInstance(resp["disbursements"], list) self.mock_http.post.assert_called_once() def test_search(self): fixture = self.load_fixture("advanced_payment_search.json") self.mock_get(fixture) result = self.sdk.advanced_payment().search({"status": "approved"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertIn("paging", resp) self.assertEqual(999, resp["results"][0]["id"]) self.assertEqual("approved", resp["results"][0]["status"]) self.mock_http.get.assert_called_once() def test_update(self): fixture = self.load_fixture("advanced_payment_update.json") self.mock_put(fixture) result = self.sdk.advanced_payment().update(999, {"status": "approved"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertEqual("approved", resp["status"]) self.mock_http.put.assert_called_once() def test_capture(self): fixture = self.load_fixture("advanced_payment_update.json") self.mock_put(fixture) result = self.sdk.advanced_payment().capture(999) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertEqual("approved", resp["status"]) self.mock_http.put.assert_called_once() def test_cancel(self): self.mock_put({"id": 999, "status": "cancelled"}) result = self.sdk.advanced_payment().cancel(999) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertEqual("cancelled", resp["status"]) self.mock_http.put.assert_called_once() def test_update_release_date(self): self.mock_post({"id": 999, "money_release_date": "2026-09-01 00:00:00.000000"}, status=201) release_date = datetime(2026, 9, 1) result = self.sdk.advanced_payment().update_release_date(999, release_date) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(999, resp["id"]) self.assertIn("money_release_date", resp) self.mock_http.post.assert_called_once() def test_update_release_date_raises_for_non_datetime(self): with self.assertRaises(ValueError): self.sdk.advanced_payment().update_release_date(999, "2026-09-01") def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.advanced_payment().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.advanced_payment().update(999, "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_card.py000066400000000000000000000074701524412155200221250ustar00rootroot00000000000000"""Unit tests for the Card resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestCard(BaseClientTest): """Test Module: Card""" def test_list_all(self): fixture = self.load_fixture("card_list_all.json") self.mock_get(fixture) result = self.sdk.card().list_all("1068193981-pXRewrKqlP6pnn") self.assertEqual(200, result["status"]) resp = result["response"] self.assertIsInstance(resp, list) self.assertEqual("1562188766852", resp[0]["id"]) self.assertEqual("503143", resp[0]["first_six_digits"]) self.assertEqual("6351", resp[0]["last_four_digits"]) self.assertIn("payment_method", resp[0]) self.mock_http.get.assert_called_once() def test_get(self): fixture = self.load_fixture("card_get.json") self.mock_get(fixture) result = self.sdk.card().get("1068193981-pXRewrKqlP6pnn", "1562188766852") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("1562188766852", resp["id"]) self.assertEqual("1068193981-pXRewrKqlP6pnn", resp["customer_id"]) self.assertEqual("503143", resp["first_six_digits"]) self.assertEqual("6351", resp["last_four_digits"]) self.assertEqual(11, resp["expiration_month"]) self.assertEqual(2030, resp["expiration_year"]) self.assertIn("cardholder", resp) self.assertEqual("APRO", resp["cardholder"]["name"]) self.assertIn("payment_method", resp) self.assertEqual("master", resp["payment_method"]["id"]) self.assertEqual("credit_card", resp["payment_method"]["payment_type_id"]) self.assertIn("issuer", resp) self.assertIn("security_code", resp) self.assertIn("date_created", resp) self.assertIn("date_last_updated", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("card_create.json") self.mock_post(fixture, status=201) card_object = {"token": "token-001"} result = self.sdk.card().create("1068193981-pXRewrKqlP6pnn", card_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("1562188766852", resp["id"]) self.assertEqual("503143", resp["first_six_digits"]) self.assertEqual("6351", resp["last_four_digits"]) self.assertEqual(2030, resp["expiration_year"]) self.assertIn("cardholder", resp) self.assertIn("payment_method", resp) self.assertIn("issuer", resp) self.mock_http.post.assert_called_once() def test_update(self): fixture = self.load_fixture("card_update.json") self.mock_put(fixture) result = self.sdk.card().update( "1068193981-pXRewrKqlP6pnn", "1562188766852", {"expiration_year": 2030}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("1562188766852", resp["id"]) self.assertEqual(2030, resp["expiration_year"]) self.assertIn("date_last_updated", resp) self.mock_http.put.assert_called_once() def test_delete(self): self.mock_delete({"id": "1562188766852"}, status=200) result = self.sdk.card().delete("1068193981-pXRewrKqlP6pnn", "1562188766852") self.assertEqual(200, result["status"]) self.mock_http.delete.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.card().create("1068193981-pXRewrKqlP6pnn", "not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.card().update("1068193981-pXRewrKqlP6pnn", "1562188766852", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_card_token.py000066400000000000000000000042061524412155200233170ustar00rootroot00000000000000"""Unit tests for the CardToken resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestCardToken(BaseClientTest): """Test Module: CardToken""" def test_get(self): fixture = self.load_fixture("card_token_get.json") self.mock_get(fixture) result = self.sdk.card_token().get("a78sd6f1a9s8d7f1a") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("a78sd6f1a9s8d7f1a", resp["id"]) self.assertEqual("503143", resp["first_six_digits"]) self.assertEqual("6351", resp["last_four_digits"]) self.assertEqual(11, resp["expiration_month"]) self.assertEqual(2030, resp["expiration_year"]) self.assertTrue(resp["luhn_validation"]) self.assertEqual("active", resp["status"]) self.assertIn("date_created", resp) self.assertIn("date_due", resp) self.assertIn("cardholder", resp) self.assertEqual("APRO", resp["cardholder"]["name"]) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("card_token_create.json") self.mock_post(fixture, status=201) card_token_object = { "card_number": "5031433215406351", "security_code": "123", "expiration_year": "2030", "expiration_month": "11", "cardholder": {"name": "APRO"}, } result = self.sdk.card_token().create(card_token_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("a78sd6f1a9s8d7f1a", resp["id"]) self.assertEqual("503143", resp["first_six_digits"]) self.assertEqual("6351", resp["last_four_digits"]) self.assertTrue(resp["luhn_validation"]) self.assertEqual("active", resp["status"]) self.assertIn("date_due", resp) self.mock_http.post.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.card_token().create("not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_chargeback.py000066400000000000000000000025221524412155200232570ustar00rootroot00000000000000"""Unit tests for the Chargeback resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestChargeback(BaseClientTest): """Test Module: Chargeback""" def test_get(self): fixture = self.load_fixture("chargeback_get.json") self.mock_get(fixture) result = self.sdk.chargeback().get("cb-001") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("cb-001", resp["id"]) self.assertEqual(17014025134, resp["payment_id"]) self.assertEqual(58.80, resp["amount"]) self.assertEqual("in_process", resp["status"]) self.assertEqual("BRL", resp["currency_id"]) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_search(self): fixture = self.load_fixture("chargeback_search.json") self.mock_get(fixture) result = self.sdk.chargeback().search({"payment_id": 17014025134}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertEqual("cb-001", resp["results"][0]["id"]) self.assertEqual(17014025134, resp["results"][0]["payment_id"]) self.mock_http.get.assert_called_once() if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_customer.py000066400000000000000000000075161524412155200230560ustar00rootroot00000000000000"""Unit tests for the Customer resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestCustomer(BaseClientTest): """Test Module: Customer""" def test_create(self): fixture = self.load_fixture("customer_create.json") self.mock_post(fixture, status=201) customer_object = { "email": "test_user@testuser.com", "first_name": "Test", "last_name": "User", "phone": {"area_code": "11", "number": "987654321"}, "identification": {"type": "CPF", "number": "19119119100"}, } result = self.sdk.customer().create(customer_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("1068193981-pXRewrKqlP6pnn", resp["id"]) self.assertEqual("test_user@testuser.com", resp["email"]) self.assertEqual("Test", resp["first_name"]) self.assertEqual("User", resp["last_name"]) self.assertIn("phone", resp) self.assertIn("identification", resp) self.assertEqual("CPF", resp["identification"]["type"]) self.assertIn("date_created", resp) self.mock_http.post.assert_called_once() def test_get(self): fixture = self.load_fixture("customer_get.json") self.mock_get(fixture) result = self.sdk.customer().get("1068193981-pXRewrKqlP6pnn") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("1068193981-pXRewrKqlP6pnn", resp["id"]) self.assertEqual("test_user@testuser.com", resp["email"]) self.assertEqual("Test", resp["first_name"]) self.assertEqual("User", resp["last_name"]) self.assertIn("phone", resp) self.assertEqual("11", resp["phone"]["area_code"]) self.assertIn("identification", resp) self.assertEqual("CPF", resp["identification"]["type"]) self.assertIn("address", resp) self.assertIn("date_created", resp) self.assertIn("date_last_updated", resp) self.assertIsInstance(resp["cards"], list) self.mock_http.get.assert_called_once() def test_update(self): fixture = self.load_fixture("customer_update.json") self.mock_put(fixture) result = self.sdk.customer().update("1068193981-pXRewrKqlP6pnn", {"last_name": "Updated"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("1068193981-pXRewrKqlP6pnn", resp["id"]) self.assertEqual("Updated", resp["last_name"]) self.assertIn("date_last_updated", resp) self.mock_http.put.assert_called_once() def test_delete(self): fixture = self.load_fixture("customer_delete.json") self.mock_delete(fixture, status=200) result = self.sdk.customer().delete("1068193981-pXRewrKqlP6pnn") self.assertEqual(200, result["status"]) self.mock_http.delete.assert_called_once() def test_search(self): fixture = self.load_fixture("customer_search.json") self.mock_get(fixture) result = self.sdk.customer().search({"email": "test_user@testuser.com"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertIn("paging", resp) self.assertEqual(1, resp["paging"]["total"]) self.assertEqual("test_user@testuser.com", resp["results"][0]["email"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.customer().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.customer().update("1068193981-pXRewrKqlP6pnn", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_disbursement_refund.py000066400000000000000000000055001524412155200252530ustar00rootroot00000000000000"""Unit tests for the DisbursementRefund resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestDisbursementRefund(BaseClientTest): """Test Module: DisbursementRefund""" def test_list_all(self): fixture = self.load_fixture("disbursement_refund_list_all.json") self.mock_get(fixture) result = self.sdk.disbursement_refund().list_all(999) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIsInstance(resp, list) self.assertEqual(1, resp[0]["id"]) self.assertEqual(999, resp[0]["advanced_payment_id"]) self.assertEqual(50.0, resp[0]["amount"]) self.assertEqual("approved", resp[0]["status"]) self.mock_http.get.assert_called_once() def test_create_all(self): fixture = self.load_fixture("disbursement_refund_create_all.json") self.mock_post(fixture, status=201) disbursement_refund_object = {"metadata": {"reason": "Full refund"}} result = self.sdk.disbursement_refund().create_all(999, disbursement_refund_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(1, resp["id"]) self.assertEqual(999, resp["advanced_payment_id"]) self.assertEqual("approved", resp["status"]) self.mock_http.post.assert_called_once() def test_create(self): fixture = self.load_fixture("disbursement_refund_create.json") self.mock_post(fixture, status=201) result = self.sdk.disbursement_refund().create(999, 10, 25.0) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(2, resp["id"]) self.assertEqual(10, resp["disbursement_id"]) self.assertEqual(25.0, resp["amount"]) self.assertEqual("approved", resp["status"]) self.mock_http.post.assert_called_once() def test_create_raises_for_non_float_amount(self): with self.assertRaises(ValueError): self.sdk.disbursement_refund().create(999, 10, 25) def test_create_all_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.disbursement_refund().create_all(999, "not-a-dict") def test_save(self): fixture = self.load_fixture("disbursement_refund_create.json") self.mock_post(fixture, status=201) disbursement_refund_object = {"amount": 25.0} result = self.sdk.disbursement_refund().save(999, 10, disbursement_refund_object) self.assertEqual(201, result["status"]) self.mock_http.post.assert_called_once() def test_save_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.disbursement_refund().save(999, 10, "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_ergonomia_unit.py000066400000000000000000000337371524412155200242400ustar00rootroot00000000000000"""Unit tests for Python SDK ergonomia features (TASK-013..018, TASK-046..049). Tests cover: - Typed exception hierarchy (TASK-013 / TASK-046) - MPResponse dict-compat wrapper (TASK-013) - build_error() factory (TASK-013 / TASK-046) - DEFAULT constants (TASK-049) - RequestOptions retry params + validation (TASK-015 / TASK-049) - Auto-pagination iterator (TASK-016) - Status enum constants (TASK-047) - Error string constants (TASK-046) - DeprecationWarning for notification_url (TASK-047) - Idempotency-key length validation (TASK-047) - Backward compatibility: result["status"] still works (TASK-018) """ import unittest import uuid import warnings import mercadopago from mercadopago.config.defaults import ( DEFAULT_MAX_RETRIES, DEFAULT_RETRY_ON, DEFAULT_TIMEOUT_SECONDS, ) from mercadopago.config.request_options import RequestOptions from mercadopago.errors.constants import ( MPOrderErrors, MPPaymentErrors, ) from mercadopago.errors.exceptions import ( MercadoPagoError, MPAuthenticationError, MPBadRequestError, MPConnectionError, MPDependencyError, MPForbiddenError, MPIdempotencyError, MPNotFoundError, MPPaymentError, MPRateLimitError, MPResourceLockedError, MPServerError, MPValidationError, build_error, ) from mercadopago.errors.response import MPResponse from mercadopago.pagination.iterator import search_auto_paging_iter from mercadopago.resources.status import ( MerchantOrderStatus, OrderStatus, PaymentStatus, PreapprovalStatus, RefundStatus, ) # ─── Exception hierarchy ────────────────────────────────────────────────────── class TestExceptionHierarchy(unittest.TestCase): def test_all_subtypes_inherit_mercadopago_error(self): classes = [ MPBadRequestError, MPAuthenticationError, MPPaymentError, MPForbiddenError, MPNotFoundError, MPIdempotencyError, MPValidationError, MPResourceLockedError, MPDependencyError, MPRateLimitError, MPServerError, ] for cls in classes: err = cls(400, {"message": "test"}) self.assertIsInstance(err, MercadoPagoError, f"{cls} not subtype of MercadoPagoError") def test_rate_limit_stores_retry_after(self): err = MPRateLimitError(429, {"message": "rate limited"}, retry_after=45) self.assertEqual(err.retry_after, 45) def test_rate_limit_null_retry_after(self): err = MPRateLimitError(429, {}) self.assertIsNone(err.retry_after) def test_connection_error_wraps_cause(self): err = MPConnectionError(ConnectionError("timeout")) self.assertIsInstance(err, MercadoPagoError) self.assertEqual(err.status_code, 0) def test_catch_by_base_catches_subtype(self): err = MPNotFoundError(404, {"message": "not found"}) caught = False try: raise err except MercadoPagoError: caught = True self.assertTrue(caught) # ─── build_error() factory ──────────────────────────────────────────────────── class TestBuildError(unittest.TestCase): def test_factory_maps_status_to_subtype(self): cases = [ (400, MPBadRequestError), (401, MPAuthenticationError), (402, MPPaymentError), (403, MPForbiddenError), (404, MPNotFoundError), (409, MPIdempotencyError), (422, MPValidationError), (423, MPResourceLockedError), (424, MPDependencyError), (429, MPRateLimitError), (500, MPServerError), (503, MPServerError), (418, MercadoPagoError), ] for status, expected_cls in cases: with self.subTest(status=status): err = build_error(status, {}) self.assertEqual(type(err), expected_cls) def test_factory_429_with_retry_after(self): err = build_error(429, {}, retry_after=30) self.assertIsInstance(err, MPRateLimitError) self.assertEqual(err.retry_after, 30) # ─── MPResponse ─────────────────────────────────────────────────────────────── class TestMPResponse(unittest.TestCase): def test_is_dict_subclass(self): r = MPResponse({"status": 200, "response": {"id": 1}}) self.assertIsInstance(r, dict) self.assertEqual(r["status"], 200) def test_status_code_property(self): r = MPResponse({"status": 404, "response": None}) self.assertEqual(r.status_code, 404) def test_is_success_true_for_2xx(self): self.assertTrue(MPResponse({"status": 200, "response": {}}).is_success) self.assertTrue(MPResponse({"status": 201, "response": {}}).is_success) def test_is_success_false_for_4xx(self): self.assertFalse(MPResponse({"status": 400, "response": {}}).is_success) def test_raise_for_status_ok_does_nothing(self): MPResponse({"status": 200, "response": {}}).raise_for_status() def test_raise_for_status_4xx_raises_typed(self): r = MPResponse({"status": 401, "response": {"message": "unauthorized"}}) with self.assertRaises(MPAuthenticationError): r.raise_for_status() def test_raise_for_status_5xx_raises_server_error(self): r = MPResponse({"status": 500, "response": {}}) with self.assertRaises(MPServerError): r.raise_for_status() def test_backward_compat_dict_access(self): raw = {"status": 200, "response": {"id": 42, "status": "approved"}} r = MPResponse(raw) self.assertEqual(r["status"], 200) self.assertEqual(r["response"]["id"], 42) # ─── DEFAULT constants ──────────────────────────────────────────────────────── class TestDefaultConstants(unittest.TestCase): def test_default_timeout(self): self.assertEqual(DEFAULT_TIMEOUT_SECONDS, 60.0) def test_default_max_retries(self): self.assertEqual(DEFAULT_MAX_RETRIES, 3) def test_default_retry_on_includes_429(self): self.assertIn(429, DEFAULT_RETRY_ON) def test_default_retry_on_includes_5xx(self): self.assertIn(500, DEFAULT_RETRY_ON) self.assertIn(502, DEFAULT_RETRY_ON) self.assertIn(503, DEFAULT_RETRY_ON) self.assertIn(504, DEFAULT_RETRY_ON) # ─── RequestOptions retry params ───────────────────────────────────────────── class TestRequestOptionsRetry(unittest.TestCase): def test_defaults_preserved(self): opts = RequestOptions(access_token="TEST-token") self.assertEqual(opts.connection_timeout, DEFAULT_TIMEOUT_SECONDS) self.assertEqual(opts.max_retries, DEFAULT_MAX_RETRIES) def test_set_valid_retry_on(self): opts = RequestOptions(access_token="t") opts.retry_on = [429, 503] self.assertEqual(opts.retry_on, [429, 503]) def test_set_invalid_retry_on_raises(self): opts = RequestOptions(access_token="t") with self.assertRaises(ValueError): opts.retry_on = [999] def test_set_jitter(self): opts = RequestOptions(access_token="t") opts.jitter = True self.assertTrue(opts.jitter) def test_on_retry_callable(self): called = [] opts = RequestOptions(access_token="t") opts.on_retry = lambda a, e: called.append(a) self.assertIsNotNone(opts.on_retry) def test_on_retry_non_callable_raises(self): opts = RequestOptions(access_token="t") with self.assertRaises(ValueError): opts.on_retry = "not_callable" # ─── Idempotency key validation (TASK-047) ──────────────────────────────────── class TestIdempotencyKeyValidation(unittest.TestCase): def test_valid_uuid_36_chars_accepted(self): opts = RequestOptions(access_token="t") opts.custom_headers = {"x-idempotency-key": str(uuid.uuid4())} def test_key_too_long_raises(self): opts = RequestOptions(access_token="t") with self.assertRaisesRegex(ValueError, "x-idempotency-key"): opts.custom_headers = {"x-idempotency-key": "a" * 65} def test_empty_key_raises(self): opts = RequestOptions(access_token="t") with self.assertRaisesRegex(ValueError, "x-idempotency-key"): opts.custom_headers = {"x-idempotency-key": ""} def test_key_64_chars_accepted(self): opts = RequestOptions(access_token="t") opts.custom_headers = {"x-idempotency-key": "a" * 64} # ─── Status constants (TASK-047) ───────────────────────────────────────────── class TestStatusConstants(unittest.TestCase): def test_payment_status_approved(self): self.assertEqual(PaymentStatus.APPROVED, "approved") def test_order_status_processed(self): self.assertEqual(OrderStatus.PROCESSED, "processed") def test_preapproval_status_authorized(self): self.assertEqual(PreapprovalStatus.AUTHORIZED, "authorized") def test_merchant_order_status_closed(self): self.assertEqual(MerchantOrderStatus.CLOSED, "closed") def test_refund_status_in_process(self): self.assertEqual(RefundStatus.IN_PROCESS, "in_process") def test_accessible_from_module_root(self): self.assertEqual(mercadopago.PaymentStatus.APPROVED, "approved") self.assertEqual(mercadopago.OrderStatus.CANCELED, "canceled") # ─── Error string constants (TASK-046) ─────────────────────────────────────── class TestErrorConstants(unittest.TestCase): def test_order_errors_cannot_refund(self): self.assertEqual(MPOrderErrors.CANNOT_REFUND, "cannot_refund_order") def test_payment_errors_failed(self): self.assertEqual(MPPaymentErrors.FAILED, "failed") def test_constants_accessible_from_module_root(self): self.assertEqual(mercadopago.MPOrderErrors.CANNOT_CANCEL, "cannot_cancel_order") # ─── DeprecationWarning (TASK-047) ─────────────────────────────────────────── class TestDeprecationWarning(unittest.TestCase): def test_payment_create_no_warning_without_notification_url(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") payment_object = {"transaction_amount": 100} if "notification_url" in payment_object: warnings.warn("notification_url is deprecated", DeprecationWarning, stacklevel=2) self.assertFalse(any(issubclass(x.category, DeprecationWarning) for x in w)) def test_notification_url_triggers_deprecation_warning(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") payment_object = {"notification_url": "https://example.com/hook", "amount": 100} if "notification_url" in payment_object: warnings.warn( "notification_url is deprecated; use Webhooks instead.", DeprecationWarning, stacklevel=2, ) dep_warnings = [x for x in w if issubclass(x.category, DeprecationWarning)] self.assertEqual(len(dep_warnings), 1) self.assertIn("notification_url", str(dep_warnings[0].message)) # ─── Auto-pagination iterator (TASK-016) ───────────────────────────────────── class TestAutoPaginationIterator(unittest.TestCase): def _make_page(self, items, total, offset): return MPResponse({ "status": 200, "response": { "paging": {"total": total, "limit": len(items), "offset": offset}, "results": items, } }) def test_single_page_yields_all_items(self): page = self._make_page([{"id": 1}, {"id": 2}], total=2, offset=0) call_count = [0] def search_fn(filters, opts): call_count[0] += 1 return page items = list(search_auto_paging_iter(search_fn)) self.assertEqual(items, [{"id": 1}, {"id": 2}]) self.assertEqual(call_count[0], 1) def test_multi_page_fetches_until_exhausted(self): pages = [ self._make_page([{"id": 1}], total=2, offset=0), self._make_page([{"id": 2}], total=2, offset=1), self._make_page([], total=2, offset=2), ] call_count = [0] def search_fn(filters, opts): idx = call_count[0] call_count[0] += 1 return pages[idx] items = list(search_auto_paging_iter(search_fn, limit=1)) self.assertEqual([i["id"] for i in items], [1, 2]) def test_empty_results_stops_immediately(self): empty = self._make_page([], total=0, offset=0) items = list(search_auto_paging_iter(lambda f, o: empty)) self.assertEqual(items, []) def test_offset_advances_per_page(self): offsets_seen = [] def search_fn(filters, opts): offsets_seen.append(filters.get("offset", 0)) if filters.get("offset", 0) >= 2: return self._make_page([], total=2, offset=filters["offset"]) return self._make_page([{"id": filters["offset"]}], total=2, offset=filters["offset"]) list(search_auto_paging_iter(search_fn, limit=1)) self.assertEqual(offsets_seen[0], 0) self.assertEqual(offsets_seen[1], 1) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_identification_type.py000066400000000000000000000012551524412155200252410ustar00rootroot00000000000000"""Unit tests for the IdentificationType resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestIdentificationType(BaseClientTest): """Test Module: IdentificationType""" def test_list_all(self): fixture = self.load_fixture("identification_type_list_all.json") self.mock_get(fixture) result = self.sdk.identification_type().list_all() self.assertEqual(200, result["status"]) self.assertIsInstance(result["response"], list) self.assertGreater(len(result["response"]), 0) self.mock_http.get.assert_called_once() if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_invoice.py000066400000000000000000000025751524412155200226510ustar00rootroot00000000000000"""Unit tests for the Invoice resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestInvoice(BaseClientTest): """Test Module: Invoice""" def test_get(self): fixture = self.load_fixture("invoice_get.json") self.mock_get(fixture) result = self.sdk.invoice().get("inv-001") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("inv-001", resp["id"]) self.assertEqual("processed", resp["status"]) self.assertEqual(29.90, resp["transaction_amount"]) self.assertEqual("BRL", resp["currency_id"]) self.assertEqual("2c938084726fca480172750000000000", resp["preapproval_id"]) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_search(self): fixture = self.load_fixture("invoice_search.json") self.mock_get(fixture) result = self.sdk.invoice().search({"preapproval_id": "2c938084726fca480172750000000000"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertEqual("inv-001", resp["results"][0]["id"]) self.assertEqual("processed", resp["results"][0]["status"]) self.mock_http.get.assert_called_once() if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_merchant_order.py000066400000000000000000000062131524412155200242020ustar00rootroot00000000000000"""Unit tests for the MerchantOrder resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestMerchantOrder(BaseClientTest): """Test Module: MerchantOrder""" def test_get(self): fixture = self.load_fixture("merchant_order_get.json") self.mock_get(fixture) result = self.sdk.merchant_order().get(4049696864) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(4049696864, resp["id"]) self.assertEqual("opened", resp["status"]) self.assertEqual("ext-ref-001", resp["external_reference"]) self.assertEqual("843382748-18d90a57-a4ce-4718", resp["preference_id"]) self.assertIsInstance(resp["payments"], list) self.assertIsInstance(resp["items"], list) self.assertEqual("Point Mini", resp["items"][0]["title"]) self.assertEqual(58.80, resp["total_amount"]) self.assertEqual(0.0, resp["paid_amount"]) self.assertIn("date_created", resp) self.assertIn("notification_url", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("merchant_order_create.json") self.mock_post(fixture, status=201) merchant_order_object = { "preference_id": "843382748-18d90a57-a4ce-4718", "site_id": "MLB", } result = self.sdk.merchant_order().create(merchant_order_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(4049696864, resp["id"]) self.assertEqual("opened", resp["status"]) self.assertEqual(58.80, resp["total_amount"]) self.assertIsInstance(resp["items"], list) self.assertIn("date_created", resp) self.mock_http.post.assert_called_once() def test_update(self): fixture = self.load_fixture("merchant_order_update.json") self.mock_put(fixture) result = self.sdk.merchant_order().update(4049696864, {"external_reference": "ext-updated"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(4049696864, resp["id"]) self.assertEqual("ext-updated", resp["external_reference"]) self.assertIn("last_updated", resp) self.mock_http.put.assert_called_once() def test_search(self): fixture = self.load_fixture("merchant_order_search.json") self.mock_get(fixture) result = self.sdk.merchant_order().search({"preference_id": "843382748-18d90a57-a4ce-4718"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("elements", resp) self.assertEqual(4049696864, resp["elements"][0]["id"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.merchant_order().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.merchant_order().update(4049696864, "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_oauth.py000066400000000000000000000051331524412155200223260ustar00rootroot00000000000000"""Unit tests for the OAuth resource using a mock HTTP client.""" import unittest from urllib.parse import ( parse_qs, urlparse, ) from tests.base_client_test import BaseClientTest class TestOAuth(BaseClientTest): """Test Module: OAuth""" def test_get_authorization_url(self): url = self.sdk.oauth().get_authorization_url( app_id="my-app-id", redirect_uri="https://example.com/callback", random_id="csrf-state-123", ) self.assertIn("https://auth.mercadopago.com/authorization", url) parsed = urlparse(url) params = parse_qs(parsed.query) self.assertEqual(["my-app-id"], params["client_id"]) self.assertEqual(["code"], params["response_type"]) self.assertEqual(["csrf-state-123"], params["state"]) self.assertEqual(["https://example.com/callback"], params["redirect_uri"]) def test_create(self): fixture = self.load_fixture("oauth_create.json") self.mock_post(fixture, status=200) oauth_object = { "client_secret": "TEST_TOKEN", "code": "auth-code-123", "redirect_uri": "https://example.com/callback", "grant_type": "authorization_code", } result = self.sdk.oauth().create(oauth_object) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("APP_USR-001", resp["access_token"]) self.assertEqual("bearer", resp["token_type"]) self.assertEqual(15552000, resp["expires_in"]) self.assertIn("refresh_token", resp) self.assertIn("scope", resp) self.mock_http.post.assert_called_once() def test_refresh(self): fixture = self.load_fixture("oauth_create.json") self.mock_post(fixture, status=200) oauth_object = { "client_secret": "TEST_TOKEN", "refresh_token": "TG-001-test-refresh-token", "grant_type": "refresh_token", } result = self.sdk.oauth().refresh(oauth_object) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("access_token", resp) self.assertIn("token_type", resp) self.assertIn("expires_in", resp) self.mock_http.post.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.oauth().create("not-a-dict") def test_refresh_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.oauth().refresh("not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_order.py000066400000000000000000000162221524412155200223220ustar00rootroot00000000000000"""Unit tests for the Order resource using a mock HTTP client.""" from dataclasses import asdict import unittest from mercadopago.resources.order_automatic_payments import OrderAutomaticPayments from tests.base_client_test import BaseClientTest class TestOrder(BaseClientTest): """Test Module: Order""" def test_create(self): fixture = self.load_fixture("order_create.json") self.mock_post(fixture, status=201) order_object = { "type": "online", "processing_mode": "automatic", "total_amount": "1000.00", "payer": {"email": "test_user@testuser.com"}, } result = self.sdk.order().create(order_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["id"]) self.assertEqual("online", resp["type"]) self.assertEqual("automatic", resp["processing_mode"]) self.assertEqual("processed", resp["status"]) self.assertEqual("1000.00", resp["total_amount"]) self.assertIsInstance(resp["items"], list) self.assertEqual("Point Mini", resp["items"][0]["title"]) self.assertIn("transactions", resp) self.assertIn("payments", resp["transactions"]) self.assertEqual("BR", resp["country_code"]) self.mock_http.post.assert_called_once() def test_get(self): fixture = self.load_fixture("order_get.json") self.mock_get(fixture) result = self.sdk.order().get("01JKXTQ2AZVE0RANCPYA6WBNPW") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["id"]) self.assertEqual("processed", resp["status"]) self.assertEqual("fully_processed", resp["status_detail"]) self.assertEqual("1000.00", resp["total_amount"]) self.assertEqual("1000.00", resp["total_paid_amount"]) self.assertIn("payer", resp) self.assertEqual("test_user@testuser.com", resp["payer"]["email"]) self.assertIsInstance(resp["items"], list) self.assertIn("transactions", resp) self.assertIn("payments", resp["transactions"]) self.assertEqual("pay-001", resp["transactions"]["payments"][0]["id"]) self.assertIn("created_date", resp) self.assertIn("last_updated_date", resp) self.mock_http.get.assert_called_once() def test_get_raises_for_non_string(self): with self.assertRaises(ValueError): self.sdk.order().get(123) def test_process(self): fixture = self.load_fixture("order_process.json") self.mock_post(fixture, status=200) result = self.sdk.order().process("01JKXTQ2AZVE0RANCPYA6WBNPW") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["id"]) self.assertEqual("processed", resp["status"]) self.mock_http.post.assert_called_once() def test_process_raises_for_non_string(self): with self.assertRaises(ValueError): self.sdk.order().process(123) def test_cancel(self): fixture = self.load_fixture("order_cancel.json") self.mock_post(fixture, status=200) result = self.sdk.order().cancel("01JKXTQ2AZVE0RANCPYA6WBNPW") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["id"]) self.assertEqual("canceled", resp["status"]) self.mock_http.post.assert_called_once() def test_capture(self): fixture = self.load_fixture("order_capture.json") self.mock_post(fixture, status=200) result = self.sdk.order().capture("01JKXTQ2AZVE0RANCPYA6WBNPW") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["id"]) self.assertEqual("processed", resp["status"]) self.mock_http.post.assert_called_once() def test_refund(self): fixture = self.load_fixture("order_refund.json") self.mock_post(fixture, status=201) result = self.sdk.order().refund("01JKXTQ2AZVE0RANCPYA6WBNPW") self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("approved", resp["status"]) self.assertIn("date_created", resp) self.mock_http.post.assert_called_once() def test_refund_with_object(self): fixture = self.load_fixture("order_refund.json") self.mock_post(fixture, status=201) refund_object = {"transactions": [{"id": "tx-001", "amount": "25.00"}]} result = self.sdk.order().refund("01JKXTQ2AZVE0RANCPYA6WBNPW", refund_object) self.assertEqual(201, result["status"]) self.mock_http.post.assert_called_once() def test_search(self): fixture = self.load_fixture("order_search.json") self.mock_get(fixture) result = self.sdk.order().search() self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("data", resp) self.assertIsInstance(resp["data"], list) self.assertEqual("01JKXTQ2AZVE0RANCPYA6WBNPW", resp["data"][0]["id"]) self.mock_http.get.assert_called_once() def test_create_transaction(self): self.mock_post({"id": "tx-001"}, status=201) transaction_object = { "payments": [{"amount": "1000.00", "payment_method": {"id": "visa"}}] } result = self.sdk.order().create_transaction("01JKXTQ2AZVE0RANCPYA6WBNPW", transaction_object) self.assertEqual(201, result["status"]) self.mock_http.post.assert_called_once() def test_update_transaction(self): self.mock_put({"id": "tx-001"}) result = self.sdk.order().update_transaction( "01JKXTQ2AZVE0RANCPYA6WBNPW", "tx-001", {"payment_method": {"id": "master"}} ) self.assertEqual(200, result["status"]) self.mock_http.put.assert_called_once() def test_delete_transaction(self): self.mock_delete(None, status=204) result = self.sdk.order().delete_transaction("01JKXTQ2AZVE0RANCPYA6WBNPW", "tx-001") self.assertEqual(204, result["status"]) self.mock_http.delete.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.order().create("not-a-dict") def test_automatic_payments_subscription_payload(self): automatic_payments = OrderAutomaticPayments( subscription={ "id": "subscription-1", "sequence": {"number": 1, "total": 12}, "invoice": { "id": "invoice-1", "billing_date": "2026-08-26", "period": {"interval": 1, "type": "month"}, }, } ) payload = asdict(automatic_payments) self.assertEqual("subscription-1", payload["subscription"]["id"]) self.assertEqual(12, payload["subscription"]["sequence"]["total"]) self.assertEqual("month", payload["subscription"]["invoice"]["period"]["type"]) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_order_checkout_pro.py000066400000000000000000000034271524412155200250720ustar00rootroot00000000000000"""Unit tests for the Order resource β€” Checkout Pro scenarios. Checkout Pro uses the same Order resource but exercises the ``processing_mode: manual`` (builder) flow and multi-transaction orders. """ import unittest from tests.base_client_test import BaseClientTest class TestOrderCheckoutPro(BaseClientTest): """Test Module: Order (Checkout Pro scenarios)""" def test_create_builder_mode(self): self.mock_post({"id": "order-cp-001", "status": "open"}, status=201) order_object = { "type": "online", "processing_mode": "manual", "total_amount": "500.00", "payer": {"email": "buyer@example.com"}, } result = self.sdk.order().create(order_object) self.assertEqual(201, result["status"]) self.assertEqual("order-cp-001", result["response"]["id"]) def test_process_builder_order(self): self.mock_post({"id": "order-cp-001", "status": "processed"}, status=200) result = self.sdk.order().process("order-cp-001") self.assertEqual(200, result["status"]) self.assertEqual("processed", result["response"]["status"]) def test_refund_transaction_partial(self): self.mock_post({"id": "refund-cp-001", "status": "approved"}, status=201) refund_object = { "transactions": [{"id": "tx-cp-001", "amount": "100.00"}] } result = self.sdk.order().refund_transaction("order-cp-001", refund_object) self.assertEqual(201, result["status"]) def test_refund_transaction_full(self): self.mock_post({"id": "refund-cp-002", "status": "approved"}, status=201) result = self.sdk.order().refund_transaction("order-cp-001") self.assertEqual(201, result["status"]) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_order_request_dataclasses.py000066400000000000000000000464211524412155200264450ustar00rootroot00000000000000"""Offline unit + integration tests for the typed Order request dataclasses. These tests do not hit the live API. They verify: * new dataclasses produce the correct snake_case keys, * None filtering (DD-3) removes unset fields, * the existing dict path still works (backward compatibility), * the typed Automatic Payments flow serializes correctly. """ import dataclasses import json import unittest import mercadopago from mercadopago.http import HttpClient from mercadopago.resources.item import ItemRequest from mercadopago.resources.order_automatic_payments import OrderAutomaticPayments from mercadopago.resources.order_create import ( OrderCreateRequest, order_request_to_dict, ) from mercadopago.resources.order_integration_data import ( OrderIntegrationData, OrderSponsor, ) from mercadopago.resources.order_stored_credential import OrderStoredCredential from mercadopago.resources.order_subscription_data import ( OrderInvoicePeriod, OrderSubscriptionData, OrderSubscriptionSequence, ) from mercadopago.resources.order_transaction import ( OrderPaymentMethodRequest, OrderPaymentRequest, OrderTransactionRequest, ) from mercadopago.resources.order_transaction_security import OrderTransactionSecurity from mercadopago.resources.payer import ( PayerAddress, PayerIdentification, PayerPhone, PayerRequest, ) from mercadopago.resources.shipment import ( ShipmentAddress, ShipmentFreeMethod, ShipmentRequest, ) class _CapturingHttpClient(HttpClient): """HttpClient stub that captures the request body instead of sending it.""" def __init__(self): self.last_url = None self.last_data = None def post(self, url, headers, # noqa: D401 # pylint: disable=too-many-arguments,too-many-positional-arguments data=None, params=None, timeout=None, maxretries=None, retry_on=None, backoff_factor=None): self.last_url = url self.last_data = data return {"status": 201, "response": {"id": "ORDER_ID", "status": "processed"}} def _make_sdk(): http = _CapturingHttpClient() sdk = mercadopago.SDK("TEST_TOKEN", http_client=http) return sdk, http class TestItemRequest(unittest.TestCase): def test_snake_case_keys(self): item = ItemRequest( title="A book", type="physical", warranty=True, event_date="2026-07-01", unit_price="100.00", external_code="EXT-1", category_id="books", description="A nice book", picture_url="https://example.com/p.png", quantity=2, ) as_dict = order_request_to_dict(item) self.assertEqual( set(as_dict.keys()), { "title", "type", "warranty", "event_date", "unit_price", "external_code", "category_id", "description", "picture_url", "quantity", }, ) self.assertEqual(as_dict["unit_price"], "100.00") self.assertEqual(as_dict["quantity"], 2) def test_none_fields_filtered(self): item = ItemRequest(title="Only title", quantity=1) as_dict = order_request_to_dict(item) self.assertEqual(as_dict, {"title": "Only title", "quantity": 1}) class TestShipmentRequest(unittest.TestCase): def test_full_shipment_snake_case(self): shipment = ShipmentRequest( mode="me2", local_pickup=False, cost="10.00", free_shipping=True, free_methods=[ShipmentFreeMethod(id=1), ShipmentFreeMethod(id=2)], address=ShipmentAddress( street_name="Main", street_number="123", zip_code="0000", floor="2", apartment="B", neighborhood="Centro", state="SP", city="Sao Paulo", complement="near park", ), ) as_dict = order_request_to_dict(shipment) self.assertEqual(as_dict["free_methods"], [{"id": 1}, {"id": 2}]) self.assertEqual(as_dict["address"]["street_name"], "Main") self.assertIn("free_shipping", as_dict) self.assertIn("local_pickup", as_dict) def test_partial_shipment_filters_none(self): shipment = ShipmentRequest(mode="custom", cost="5.00") as_dict = order_request_to_dict(shipment) self.assertEqual(as_dict, {"mode": "custom", "cost": "5.00"}) class TestOrderPayer(unittest.TestCase): def test_payer_phone_and_address(self): payer = PayerRequest( email="buyer@example.com", first_name="Jane", last_name="Doe", customer_id="CUST-1", entity_type="individual", identification=PayerIdentification(type="CPF", number="12345678909"), phone=PayerPhone(area_code="11", number="999999999"), address=PayerAddress( zip_code="0000", street_name="Main", street_number="123", neighborhood="Centro", city="Sao Paulo", state="SP", complement="apt 1", country="BR", ), ) as_dict = order_request_to_dict(payer) self.assertEqual(as_dict["phone"], {"area_code": "11", "number": "999999999"}) self.assertEqual(as_dict["address"]["zip_code"], "0000") self.assertEqual(as_dict["identification"], {"type": "CPF", "number": "12345678909"}) def test_payer_email_only_filters_none(self): payer = PayerRequest(email="buyer@example.com") self.assertEqual(order_request_to_dict(payer), {"email": "buyer@example.com"}) class TestOrderTransactionSecurity(unittest.TestCase): def test_snake_case_keys(self): sec = OrderTransactionSecurity(validation="complete", liability_shift="yes") self.assertEqual( order_request_to_dict(sec), {"validation": "complete", "liability_shift": "yes"}, ) class TestOrderCreateRequestRootFields(unittest.TestCase): def test_all_root_fields_present(self): req = OrderCreateRequest( type="online", external_reference="ext_ref_1234", total_amount="200.00", currency="BRL", capture_mode="automatic_async", processing_mode="automatic", description="An order", marketplace="NONE", marketplace_fee="1.00", expiration_time="P3D", checkout_available_at="2026-07-22T00:00:00.000-03:00", ) as_dict = order_request_to_dict(req) for key in ( "description", "marketplace", "marketplace_fee", "expiration_time", "checkout_available_at", "currency", ): self.assertIn(key, as_dict) self.assertEqual(as_dict["marketplace_fee"], "1.00") def test_none_root_fields_filtered(self): req = OrderCreateRequest(type="online", total_amount="10.00") as_dict = order_request_to_dict(req) self.assertEqual(as_dict, {"type": "online", "total_amount": "10.00"}) self.assertNotIn("marketplace", as_dict) def test_config_online_transaction_security_nesting(self): # transaction_security lives under config.online (not root). req = OrderCreateRequest( type="online", config={ "online": { "transaction_security": order_request_to_dict( OrderTransactionSecurity(validation="complete") ) } }, ) as_dict = order_request_to_dict(req) self.assertEqual( as_dict["config"]["online"]["transaction_security"], {"validation": "complete"}, ) self.assertNotIn("transaction_security", as_dict) def test_helper_rejects_non_dataclass(self): with self.assertRaises(TypeError): order_request_to_dict({"type": "online"}) class TestOrderCreateDualPath(unittest.TestCase): def test_dict_path_backward_compat(self): sdk, http = _make_sdk() order_object = { "type": "online", "total_amount": "200.00", "external_reference": "ext_ref_1234", "payer": {"email": "buyer@example.com"}, } result = sdk.order().create(order_object) self.assertEqual(result["status"], 201) sent = json.loads(http.last_data) self.assertEqual(sent, order_object) def test_dataclass_path_matches_dict_path(self): sdk, http = _make_sdk() typed = OrderCreateRequest( type="online", total_amount="200.00", external_reference="ext_ref_1234", payer=PayerRequest(email="buyer@example.com"), items=[ItemRequest(title="A book", unit_price="200.00", quantity=1)], ) sdk.order().create(typed) sent_typed = json.loads(http.last_data) equivalent_dict = { "type": "online", "total_amount": "200.00", "external_reference": "ext_ref_1234", "payer": {"email": "buyer@example.com"}, "items": [{"title": "A book", "unit_price": "200.00", "quantity": 1}], } sdk2, http2 = _make_sdk() sdk2.order().create(equivalent_dict) sent_dict = json.loads(http2.last_data) self.assertEqual(sent_typed, sent_dict) def test_invalid_type_raises(self): sdk, _ = _make_sdk() with self.assertRaises(ValueError): sdk.order().create("not-a-dict") class TestAutomaticPaymentsTypedFlow(unittest.TestCase): def test_ap_flow_snake_case(self): sdk, http = _make_sdk() order_object = { "type": "online", "total_amount": "100.00", "external_reference": "subscription-001-payment-2", "payer": {"email": "customer@example.com", "customer_id": "CUSTOMER_ID"}, "transactions": { "payments": [ { "amount": "100.00", "payment_method": { "id": "master", "type": "credit_card", "token": "CARD_TOKEN", "installments": 1, }, "automatic_payments": dataclasses.asdict( OrderAutomaticPayments( payment_profile_id="PROFILE", schedule_date="2026-08-01T00:00:00.000-04:00", due_date="2026-08-05T00:00:00.000-04:00", retries=3, ) ), "stored_credential": dataclasses.asdict( OrderStoredCredential( payment_initiator="merchant", reason="recurring", store_payment_method=False, first_payment=False, previous_transaction_reference="PREV_TX", ) ), "subscription_data": dataclasses.asdict( OrderSubscriptionData( invoice_id="INVOICE_002", billing_date="2026-07-01", subscription_sequence=OrderSubscriptionSequence(number=2, total=12), invoice_period=OrderInvoicePeriod(type="monthly", period=1), ) ), } ] }, "integration_data": dataclasses.asdict( OrderIntegrationData( integrator_id="INT-1", platform_id="PLAT-1", corporation_id="CORP-1", sponsor=OrderSponsor(id="SPONSOR-1"), ) ), } result = sdk.order().create(order_object) self.assertEqual(result["status"], 201) sent = json.loads(http.last_data) payment = sent["transactions"]["payments"][0] self.assertEqual(payment["stored_credential"]["previous_transaction_reference"], "PREV_TX") self.assertEqual(payment["automatic_payments"]["payment_profile_id"], "PROFILE") self.assertEqual( payment["subscription_data"]["subscription_sequence"], {"number": 2, "total": 12}, ) self.assertEqual(sent["integration_data"]["sponsor"], {"id": "SPONSOR-1"}) def test_ap_typed_via_dataclass_root(self): # AP nested dicts inside a typed OrderCreateRequest (transactions kept as dict). sdk, http = _make_sdk() typed = OrderCreateRequest( type="online", total_amount="100.00", payer=PayerRequest(email="customer@example.com", customer_id="CUSTOMER_ID"), transactions={ "payments": [ { "amount": "100.00", "stored_credential": dataclasses.asdict( OrderStoredCredential( payment_initiator="merchant", first_payment=True, ) ), } ] }, ) sdk.order().create(typed) sent = json.loads(http.last_data) sc = sent["transactions"]["payments"][0]["stored_credential"] # first_payment stays; None fields (reason, prev_transaction_ref) are dropped. self.assertEqual(sc, {"payment_initiator": "merchant", "first_payment": True}) class TestFullyTypedAPChain(unittest.TestCase): """Verify the typed chain OrderCreateRequest β†’ OrderTransactionRequest β†’ OrderPaymentRequest β†’ AP dataclasses produces the correct JSON body.""" def test_fully_typed_ap_chain_serializes_correctly(self): sdk, http = _make_sdk() typed = OrderCreateRequest( type="online", total_amount="100.00", external_reference="ap-typed-chain-001", payer=PayerRequest( email="customer@example.com", customer_id="CUSTOMER_ID", ), transactions=OrderTransactionRequest( payments=[ OrderPaymentRequest( amount="100.00", payment_method=OrderPaymentMethodRequest( id="master", type="credit_card", token="CARD_TOKEN", installments=1, ), automatic_payments=OrderAutomaticPayments( payment_profile_id="PROFILE_ID", retries=3, schedule_date="2026-08-01T00:00:00.000-04:00", due_date="2026-08-05T00:00:00.000-04:00", ), stored_credential=OrderStoredCredential( payment_initiator="merchant", reason="recurring", store_payment_method=False, first_payment=False, previous_transaction_reference="PREV_TX_ID", ), subscription_data=OrderSubscriptionData( invoice_id="INV-002", billing_date="2026-07-27", subscription_sequence=OrderSubscriptionSequence( number=2, total=12 ), invoice_period=OrderInvoicePeriod( type="monthly", period=1 ), ), ) ] ), integration_data=OrderIntegrationData( integrator_id="INTEGRATOR_ID", sponsor=OrderSponsor(id="SPONSOR_ID"), ), ) result = sdk.order().create(typed) self.assertEqual(result["status"], 201) sent = json.loads(http.last_data) payment = sent["transactions"]["payments"][0] # payment_method self.assertEqual(payment["payment_method"]["id"], "master") self.assertEqual(payment["payment_method"]["token"], "CARD_TOKEN") # automatic_payments ap = payment["automatic_payments"] self.assertEqual(ap["payment_profile_id"], "PROFILE_ID") self.assertEqual(ap["retries"], 3) self.assertEqual(ap["schedule_date"], "2026-08-01T00:00:00.000-04:00") self.assertEqual(ap["due_date"], "2026-08-05T00:00:00.000-04:00") # stored_credential sc = payment["stored_credential"] self.assertEqual(sc["payment_initiator"], "merchant") self.assertEqual(sc["reason"], "recurring") self.assertFalse(sc["store_payment_method"]) self.assertFalse(sc["first_payment"]) self.assertEqual(sc["previous_transaction_reference"], "PREV_TX_ID") # subscription_data sub = payment["subscription_data"] self.assertEqual(sub["invoice_id"], "INV-002") self.assertEqual(sub["billing_date"], "2026-07-27") self.assertEqual(sub["subscription_sequence"], {"number": 2, "total": 12}) self.assertEqual(sub["invoice_period"], {"type": "monthly", "period": 1}) # integration_data integ = sent["integration_data"] self.assertEqual(integ["integrator_id"], "INTEGRATOR_ID") self.assertEqual(integ["sponsor"], {"id": "SPONSOR_ID"}) def test_typed_transactions_and_dict_transactions_produce_same_json(self): """Typed OrderTransactionRequest and equivalent dict produce identical JSON.""" sdk_typed, http_typed = _make_sdk() sdk_dict, http_dict = _make_sdk() typed_request = OrderCreateRequest( type="online", total_amount="50.00", transactions=OrderTransactionRequest( payments=[ OrderPaymentRequest( amount="50.00", payment_method=OrderPaymentMethodRequest( id="visa", type="credit_card", installments=1 ), automatic_payments=OrderAutomaticPayments( payment_profile_id="PROF-1", ), ) ] ), ) dict_request = { "type": "online", "total_amount": "50.00", "transactions": { "payments": [{ "amount": "50.00", "payment_method": { "id": "visa", "type": "credit_card", "installments": 1 }, "automatic_payments": {"payment_profile_id": "PROF-1"}, }] }, } sdk_typed.order().create(typed_request) sdk_dict.order().create(dict_request) self.assertEqual( json.loads(http_typed.last_data), json.loads(http_dict.last_data), ) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_path_param.py000066400000000000000000000007631524412155200233260ustar00rootroot00000000000000import unittest from mercadopago.config.request_options import RequestOptions from mercadopago.core import MPBase class TestPathParam(unittest.TestCase): def test_path_param_escapes_path_traversal(self): base = MPBase(RequestOptions(access_token="token"), None) self.assertEqual( "..%2F..%2Fapplications%2F123", base._path_param("../../applications/123"), # pylint: disable=protected-access ) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_payment.py000066400000000000000000000143641524412155200226710ustar00rootroot00000000000000"""Unit tests for the Payment resource using a mock HTTP client.""" import unittest import warnings from tests.base_client_test import BaseClientTest class TestPayment(BaseClientTest): """Test Module: Payment""" def test_get(self): fixture = self.load_fixture("payment_get.json") self.mock_get(fixture) result = self.sdk.payment().get(17014025134) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(17014025134, resp["id"]) self.assertEqual("approved", resp["status"]) self.assertEqual("accredited", resp["status_detail"]) self.assertEqual("visa", resp["payment_method_id"]) self.assertEqual("credit_card", resp["payment_type_id"]) self.assertEqual("BRL", resp["currency_id"]) self.assertEqual(58.80, resp["transaction_amount"]) self.assertTrue(resp["captured"]) self.assertFalse(resp["binary_mode"]) self.assertEqual(1, resp["installments"]) self.assertEqual("aggregator", resp["processing_mode"]) self.assertEqual("test_user@testuser.com", resp["payer"]["email"]) self.assertIn("transaction_details", resp) self.assertIn("card", resp) self.assertEqual("503143", resp["card"]["first_six_digits"]) self.assertEqual("6351", resp["card"]["last_four_digits"]) self.mock_http.get.assert_called_once() def test_get_preserves_expanded_gateway_network_data(self): self.mock_get( { "expanded": { "gateway": { "reference": { "network_data": { "transaction_id": "ABC123", "transaction_link_id": "550e8400", } } } } } ) result = self.sdk.payment().get(17014025134) network_data = result["response"]["expanded"]["gateway"]["reference"]["network_data"] self.assertEqual("ABC123", network_data["transaction_id"]) self.assertEqual("550e8400", network_data["transaction_link_id"]) def test_search(self): fixture = self.load_fixture("payment_search.json") self.mock_get(fixture) result = self.sdk.payment().search({"status": "approved"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertIn("paging", resp) self.assertEqual(1, resp["paging"]["total"]) self.assertEqual(30, resp["paging"]["limit"]) results = resp["results"] self.assertIsInstance(results, list) self.assertEqual(17014025134, results[0]["id"]) self.assertEqual("approved", results[0]["status"]) self.assertEqual("BRL", results[0]["currency_id"]) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("payment_create.json") self.mock_post(fixture, status=201) payment_object = { "transaction_amount": 58.80, "payment_method_id": "visa", "token": "token-001", "installments": 1, "payer": {"email": "test_user@testuser.com"}, } result = self.sdk.payment().create(payment_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(17014025134, resp["id"]) self.assertEqual("pending", resp["status"]) self.assertEqual("pending_waiting_payment", resp["status_detail"]) self.assertEqual(58.80, resp["transaction_amount"]) self.assertEqual("visa", resp["payment_method_id"]) self.assertEqual("BRL", resp["currency_id"]) self.assertFalse(resp["captured"]) self.mock_http.post.assert_called_once() def test_create_with_notification_url_warns(self): fixture = self.load_fixture("payment_create.json") self.mock_post(fixture, status=201) payment_object = { "transaction_amount": 58.80, "payment_method_id": "visa", "token": "token-001", "installments": 1, "payer": {"email": "test_user@testuser.com"}, "notification_url": "https://example.com/notifications", } with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") self.sdk.payment().create(payment_object) self.assertTrue(any(issubclass(w.category, DeprecationWarning) for w in caught)) def test_update(self): fixture = self.load_fixture("payment_update.json") self.mock_put(fixture) result = self.sdk.payment().update(17014025134, {"status": "cancelled"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(17014025134, resp["id"]) self.assertEqual("cancelled", resp["status"]) self.assertIn("date_last_updated", resp) self.mock_http.put.assert_called_once() def test_cancel(self): fixture = self.load_fixture("payment_update.json") self.mock_put(fixture) result = self.sdk.payment().update(17014025134, {"status": "cancelled"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("cancelled", resp["status"]) self.mock_http.put.assert_called_once() def test_capture(self): fixture = self.load_fixture("payment_get.json") self.mock_put(fixture) result = self.sdk.payment().capture(17014025134) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(17014025134, resp["id"]) self.assertEqual("approved", resp["status"]) self.mock_http.put.assert_called_once() def test_capture_with_amount(self): fixture = self.load_fixture("payment_get.json") self.mock_put(fixture) result = self.sdk.payment().capture(17014025134, amount=50.0) self.assertEqual(200, result["status"]) self.mock_http.put.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.payment().create("not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_payment_capture.py000066400000000000000000000042651524412155200244130ustar00rootroot00000000000000""" Module: test_payment_capture """ import json import unittest from unittest.mock import MagicMock import mercadopago from mercadopago.http.http_client import HttpClient PAYMENT_ID = 123456789 CAPTURED_PAYMENT_RESPONSE = { "id": PAYMENT_ID, "status": "approved", "captured": True, "transaction_amount": 100.0, } class TestPaymentCapture(unittest.TestCase): """ Test Module: Payment.capture """ def _make_sdk_with_mock_put(self, return_value): mock_http = MagicMock(spec=HttpClient) mock_http.put.return_value = return_value return mercadopago.SDK("TEST_ACCESS_TOKEN", http_client=mock_http), mock_http def test_capture_full(self): """Captures the full authorized amount when no amount is given.""" sdk, mock_http = self._make_sdk_with_mock_put( {"status": 200, "response": CAPTURED_PAYMENT_RESPONSE} ) result = sdk.payment().capture(PAYMENT_ID) self.assertEqual(result["status"], 200) self.assertTrue(result["response"]["captured"]) mock_http.put.assert_called_once() call_kwargs = mock_http.put.call_args url = call_kwargs[1]["url"] if "url" in call_kwargs[1] else call_kwargs[0][0] self.assertIn(str(PAYMENT_ID), url) body = json.loads(call_kwargs[1]["data"]) self.assertTrue(body["capture"]) self.assertNotIn("transaction_amount", body) def test_capture_partial(self): """Captures a specific amount and includes transaction_amount in the request body.""" partial_amount = 50.0 response_body = dict(CAPTURED_PAYMENT_RESPONSE, transaction_amount=partial_amount) sdk, mock_http = self._make_sdk_with_mock_put( {"status": 200, "response": response_body} ) result = sdk.payment().capture(PAYMENT_ID, amount=partial_amount) self.assertEqual(result["status"], 200) mock_http.put.assert_called_once() call_kwargs = mock_http.put.call_args body = json.loads(call_kwargs[1]["data"]) self.assertTrue(body["capture"]) self.assertEqual(body["transaction_amount"], partial_amount) if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_payment_methods.py000066400000000000000000000015001524412155200244000ustar00rootroot00000000000000"""Unit tests for the PaymentMethods resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestPaymentMethods(BaseClientTest): """Test Module: PaymentMethods""" def test_list_all(self): fixture = self.load_fixture("payment_methods_list_all.json") self.mock_get(fixture) result = self.sdk.payment_methods().list_all() self.assertEqual(200, result["status"]) self.assertIsInstance(result["response"], list) self.assertGreater(len(result["response"]), 0) # Ensure at least one method has expected fields first = result["response"][0] self.assertIn("id", first) self.assertIn("name", first) self.mock_http.get.assert_called_once() if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_plan.py000066400000000000000000000064721524412155200221470ustar00rootroot00000000000000"""Unit tests for the Plan resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestPlan(BaseClientTest): """Test Module: Plan""" def test_get(self): fixture = self.load_fixture("plan_get.json") self.mock_get(fixture) result = self.sdk.plan().get("2c938084726fca480172750000000002") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000002", resp["id"]) self.assertEqual("active", resp["status"]) self.assertEqual("Monthly Plan - Basic", resp["reason"]) self.assertIn("auto_recurring", resp) self.assertEqual(1, resp["auto_recurring"]["frequency"]) self.assertEqual("months", resp["auto_recurring"]["frequency_type"]) self.assertEqual(29.90, resp["auto_recurring"]["transaction_amount"]) self.assertEqual("BRL", resp["auto_recurring"]["currency_id"]) self.assertIn("init_point", resp) self.assertIn("date_created", resp) self.assertIn("last_modified", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("plan_create.json") self.mock_post(fixture, status=201) plan_object = { "reason": "Monthly Plan - Basic", "auto_recurring": { "frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL", }, "back_url": "https://example.com/back", } result = self.sdk.plan().create(plan_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000002", resp["id"]) self.assertEqual("active", resp["status"]) self.assertIn("auto_recurring", resp) self.assertIn("init_point", resp) self.mock_http.post.assert_called_once() def test_update(self): fixture = self.load_fixture("plan_update.json") self.mock_put(fixture) result = self.sdk.plan().update("2c938084726fca480172750000000002", {"status": "inactive"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000002", resp["id"]) self.assertEqual("inactive", resp["status"]) self.assertIn("last_modified", resp) self.mock_http.put.assert_called_once() def test_search(self): fixture = self.load_fixture("plan_search.json") self.mock_get(fixture) result = self.sdk.plan().search() self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertEqual("2c938084726fca480172750000000002", resp["results"][0]["id"]) self.assertEqual("active", resp["results"][0]["status"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.plan().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.plan().update("2c938084726fca480172750000000002", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_point.py000066400000000000000000000055501524412155200223420ustar00rootroot00000000000000"""Unit tests for the Point resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestPoint(BaseClientTest): """Test Module: Point""" def test_get_devices(self): fixture = self.load_fixture("point_get_devices.json") self.mock_get(fixture) result = self.sdk.point().get_devices() self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("devices", resp) self.assertIsInstance(resp["devices"], list) self.assertEqual("device-001", resp["devices"][0]["id"]) self.assertEqual("PDV", resp["devices"][0]["operating_mode"]) self.assertEqual("store-001", resp["devices"][0]["store_id"]) self.mock_http.get.assert_called_once() def test_get_devices_with_filters(self): fixture = self.load_fixture("point_get_devices.json") self.mock_get(fixture) result = self.sdk.point().get_devices(filters={"store_id": "store-001"}) self.assertEqual(200, result["status"]) self.assertIn("devices", result["response"]) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("point_create.json") self.mock_post(fixture, status=201) payment_intent_object = { "amount": 58.80, "additional_info": {"external_reference": "ref-001"}, "description": "Test payment", "payment": {"installments": 1, "type": "credit_card"}, } result = self.sdk.point().create("device-001", payment_intent_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("intent-001", resp["id"]) self.assertEqual("OPEN", resp["state"]) self.assertEqual("device-001", resp["device_id"]) self.assertEqual(58.80, resp["amount"]) self.mock_http.post.assert_called_once() def test_get(self): fixture = self.load_fixture("point_get.json") self.mock_get(fixture) result = self.sdk.point().get("intent-001") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("intent-001", resp["id"]) self.assertEqual("FINISHED", resp["state"]) self.assertEqual("device-001", resp["device_id"]) self.assertEqual(58.80, resp["amount"]) self.mock_http.get.assert_called_once() def test_cancel(self): self.mock_delete({"id": "intent-001"}, status=200) result = self.sdk.point().cancel("device-001", "intent-001") self.assertEqual(200, result["status"]) self.mock_http.delete.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.point().create("device-001", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_preapproval.py000066400000000000000000000073601524412155200235450ustar00rootroot00000000000000"""Unit tests for the PreApproval resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestPreApproval(BaseClientTest): """Test Module: PreApproval""" def test_get(self): fixture = self.load_fixture("preapproval_get.json") self.mock_get(fixture) result = self.sdk.preapproval().get("2c938084726fca480172750000000000") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000000", resp["id"]) self.assertEqual("authorized", resp["status"]) self.assertEqual("Monthly subscription", resp["reason"]) self.assertEqual("test_user@testuser.com", resp["payer_email"]) self.assertEqual(123456789, resp["payer_id"]) self.assertIn("auto_recurring", resp) self.assertEqual(1, resp["auto_recurring"]["frequency"]) self.assertEqual("months", resp["auto_recurring"]["frequency_type"]) self.assertEqual(29.90, resp["auto_recurring"]["transaction_amount"]) self.assertEqual("BRL", resp["auto_recurring"]["currency_id"]) self.assertIn("next_payment_date", resp) self.assertIn("init_point", resp) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("preapproval_create.json") self.mock_post(fixture, status=201) preapproval_object = { "reason": "Monthly subscription", "auto_recurring": {"frequency": 1, "frequency_type": "months", "transaction_amount": 29.90, "currency_id": "BRL"}, "payer_email": "test_user@testuser.com", "back_url": "https://example.com/back", } result = self.sdk.preapproval().create(preapproval_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000000", resp["id"]) self.assertEqual("pending", resp["status"]) self.assertIn("auto_recurring", resp) self.assertIn("init_point", resp) self.assertEqual("test_user@testuser.com", resp["payer_email"]) self.mock_http.post.assert_called_once() def test_update(self): fixture = self.load_fixture("preapproval_update.json") self.mock_put(fixture) result = self.sdk.preapproval().update("2c938084726fca480172750000000000", {"status": "cancelled"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000000", resp["id"]) self.assertEqual("cancelled", resp["status"]) self.assertIn("last_modified", resp) self.mock_http.put.assert_called_once() def test_search(self): fixture = self.load_fixture("preapproval_search.json") self.mock_get(fixture) result = self.sdk.preapproval().search({"status": "authorized"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertIn("paging", resp) self.assertEqual(1, resp["paging"]["total"]) self.assertEqual("2c938084726fca480172750000000000", resp["results"][0]["id"]) self.assertEqual("authorized", resp["results"][0]["status"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.preapproval().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.preapproval().update("2c938084726fca480172750000000000", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_preference.py000066400000000000000000000074521524412155200233320ustar00rootroot00000000000000"""Unit tests for the Preference resource using a mock HTTP client.""" import unittest import warnings from tests.base_client_test import BaseClientTest class TestPreference(BaseClientTest): """Test Module: Preference""" def test_create(self): fixture = self.load_fixture("preference_create.json") self.mock_post(fixture, status=201) preference_object = { "items": [{"title": "Point Mini", "quantity": 1, "unit_price": 58.80}] } result = self.sdk.preference().create(preference_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("843382748-18d90a57-a4ce-4718-bc17-1234567890", resp["id"]) self.assertIn("init_point", resp) self.assertIsInstance(resp["items"], list) self.assertEqual("Point Mini", resp["items"][0]["title"]) self.assertEqual(843382748, resp["collector_id"]) self.assertIn("back_urls", resp) self.assertIn("payment_methods", resp) self.assertEqual(12, resp["payment_methods"]["installments"]) self.mock_http.post.assert_called_once() def test_create_with_notification_url_warns(self): fixture = self.load_fixture("preference_create.json") self.mock_post(fixture, status=201) preference_object = { "items": [{"title": "Point Mini", "quantity": 1, "unit_price": 58.80}], "notification_url": "https://example.com/notify", } with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") self.sdk.preference().create(preference_object) self.assertTrue(any(issubclass(w.category, DeprecationWarning) for w in caught)) def test_get(self): fixture = self.load_fixture("preference_get.json") self.mock_get(fixture) result = self.sdk.preference().get("843382748-18d90a57-a4ce-4718-bc17-1234567890") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("843382748-18d90a57-a4ce-4718-bc17-1234567890", resp["id"]) self.assertIn("init_point", resp) self.assertIsInstance(resp["items"], list) self.assertEqual("Point Mini", resp["items"][0]["title"]) self.assertEqual(58.80, resp["items"][0]["unit_price"]) self.assertEqual(843382748, resp["collector_id"]) self.assertIn("back_urls", resp) self.assertEqual("https://example.com/success", resp["back_urls"]["success"]) self.assertEqual("MP-PREF-001", resp["external_reference"]) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_update(self): fixture = self.load_fixture("preference_update.json") self.mock_put(fixture) result = self.sdk.preference().update( "843382748-18d90a57-a4ce-4718-bc17-1234567890", {"items": [{"title": "Updated Item"}]}, ) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("843382748-18d90a57-a4ce-4718-bc17-1234567890", resp["id"]) self.assertIn("items", resp) self.mock_http.put.assert_called_once() def test_search(self): fixture = self.load_fixture("preference_search.json") self.mock_get(fixture) result = self.sdk.preference().search() self.assertEqual(200, result["status"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.preference().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.preference().update("843382748-18d90a57-a4ce-4718-bc17-1234567890", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_refund_get.py000066400000000000000000000052541524412155200233340ustar00rootroot00000000000000"""Unit tests for the Refund resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestRefund(BaseClientTest): """Test Module: Refund""" def test_list_all(self): fixture = self.load_fixture("refund_list_all.json") self.mock_get(fixture) result = self.sdk.refund().list_all(17014025134) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIsInstance(resp, list) self.assertEqual(1091618291, resp[0]["id"]) self.assertEqual(17014025134, resp[0]["payment_id"]) self.assertEqual(58.80, resp[0]["amount"]) self.assertEqual("approved", resp[0]["status"]) self.mock_http.get.assert_called_once() def test_get(self): fixture = self.load_fixture("refund_get.json") self.mock_get(fixture) result = self.sdk.refund().get(17014025134, 1091618291) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual(1091618291, resp["id"]) self.assertEqual(17014025134, resp["payment_id"]) self.assertEqual(58.80, resp["amount"]) self.assertEqual("approved", resp["status"]) self.assertEqual("standard", resp["refund_mode"]) self.assertIn("date_created", resp) self.assertIn("source", resp) self.assertEqual("Test User", resp["source"]["name"]) self.assertEqual("operator", resp["source"]["type"]) self.mock_http.get.assert_called_once() def test_create_full_refund(self): fixture = self.load_fixture("refund_create.json") self.mock_post(fixture, status=201) result = self.sdk.refund().create(17014025134) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual(1091618291, resp["id"]) self.assertEqual(17014025134, resp["payment_id"]) self.assertEqual(58.80, resp["amount"]) self.assertEqual("approved", resp["status"]) self.assertEqual("standard", resp["refund_mode"]) self.mock_http.post.assert_called_once() def test_create_partial_refund(self): fixture = self.load_fixture("refund_create.json") self.mock_post(fixture, status=201) result = self.sdk.refund().create(17014025134, {"amount": 50.0}) self.assertEqual(201, result["status"]) self.assertIn("date_created", result["response"]) self.mock_http.post.assert_called_once() def test_create_raises_for_non_dict_refund_object(self): with self.assertRaises(ValueError): self.sdk.refund().create(17014025134, "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_subscription.py000066400000000000000000000067501524412155200237400ustar00rootroot00000000000000"""Unit tests for the Subscription resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestSubscription(BaseClientTest): """Test Module: Subscription""" def test_get(self): fixture = self.load_fixture("subscription_get.json") self.mock_get(fixture) result = self.sdk.subscription().get("2c938084726fca480172750000000003") self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000003", resp["id"]) self.assertEqual("authorized", resp["status"]) self.assertEqual("2c938084726fca480172750000000002", resp["preapproval_plan_id"]) self.assertEqual("test_user@testuser.com", resp["payer_email"]) self.assertEqual(123456789, resp["payer_id"]) self.assertIn("auto_recurring", resp) self.assertEqual(29.90, resp["auto_recurring"]["transaction_amount"]) self.assertEqual("BRL", resp["auto_recurring"]["currency_id"]) self.assertIn("next_payment_date", resp) self.assertIn("date_created", resp) self.mock_http.get.assert_called_once() def test_create(self): fixture = self.load_fixture("subscription_create.json") self.mock_post(fixture, status=201) subscription_object = { "preapproval_plan_id": "2c938084726fca480172750000000002", "payer_email": "test_user@testuser.com", "card_token_id": "a78sd6f1a9s8d7f1a", } result = self.sdk.subscription().create(subscription_object) self.assertEqual(201, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000003", resp["id"]) self.assertEqual("pending", resp["status"]) self.assertEqual("2c938084726fca480172750000000002", resp["preapproval_plan_id"]) self.assertIn("auto_recurring", resp) self.assertIn("date_created", resp) self.mock_http.post.assert_called_once() def test_update(self): fixture = self.load_fixture("subscription_update.json") self.mock_put(fixture) result = self.sdk.subscription().update("2c938084726fca480172750000000003", {"status": "cancelled"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertEqual("2c938084726fca480172750000000003", resp["id"]) self.assertEqual("cancelled", resp["status"]) self.assertIn("last_modified", resp) self.mock_http.put.assert_called_once() def test_search(self): fixture = self.load_fixture("subscription_search.json") self.mock_get(fixture) result = self.sdk.subscription().search({"status": "authorized"}) self.assertEqual(200, result["status"]) resp = result["response"] self.assertIn("results", resp) self.assertEqual("2c938084726fca480172750000000003", resp["results"][0]["id"]) self.assertEqual("authorized", resp["results"][0]["status"]) self.assertEqual("test_user@testuser.com", resp["results"][0]["payer_email"]) self.mock_http.get.assert_called_once() def test_create_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.subscription().create("not-a-dict") def test_update_raises_for_non_dict(self): with self.assertRaises(ValueError): self.sdk.subscription().update("2c938084726fca480172750000000003", "not-a-dict") if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_user.py000066400000000000000000000011531524412155200221620ustar00rootroot00000000000000"""Unit tests for the User resource using a mock HTTP client.""" import unittest from tests.base_client_test import BaseClientTest class TestUser(BaseClientTest): """Test Module: User""" def test_get(self): fixture = self.load_fixture("user_get.json") self.mock_get(fixture) result = self.sdk.user().get() self.assertEqual(200, result["status"]) self.assertEqual(12345, result["response"]["id"]) self.assertEqual("test@example.com", result["response"]["email"]) self.mock_http.get.assert_called_once() if __name__ == "__main__": unittest.main() mercadopago-sdk-python-b345a69/tests/test_webhook_signature_validator.py000066400000000000000000000154121524412155200267730ustar00rootroot00000000000000""" Module: test_webhook_signature_validator Unit tests for :class:`mercadopago.webhook.WebhookSignatureValidator`. These tests are self-contained and do not require any environment variables or network access. """ import hashlib import hmac import time import unittest from mercadopago.webhook import ( InvalidWebhookSignatureError, SignatureFailureReason, WebhookSignatureValidator, ) SECRET = "your_secret_key_here" REQUEST_ID = "2066ca19-c6f1-498a-be75-1923005edd06" DATA_ID_RAW = "ORD01JQ4S4KY8HWQ6NA5PXB65B3D3" DATA_ID_LOWER = "ord01jq4s4ky8hwq6na5pxb65b3d3" TS = "1742505638683" TS_NUM = int(TS) def compute_hash(data_id, request_id, ts, secret): parts = [] if data_id: parts.append(f"id:{data_id}") if request_id: parts.append(f"request-id:{request_id}") parts.append(f"ts:{ts}") manifest = ";".join(parts) + ";" return hmac.new(secret.encode("utf-8"), manifest.encode("utf-8"), hashlib.sha256).hexdigest() def build_header(h, ts=TS, version="v1"): return f"ts={ts},{version}={h}" VALID_HASH = compute_hash(DATA_ID_LOWER, REQUEST_ID, TS, SECRET) VALID_HEADER = build_header(VALID_HASH) class TestWebhookSignatureValidator(unittest.TestCase): """Covers the 12 canonical cases plus supportedVersions and arg validation.""" # --- case 1 --- def test_happy_path_lowercase(self): WebhookSignatureValidator.validate(VALID_HEADER, REQUEST_ID, DATA_ID_LOWER, SECRET) # --- case 2 --- def test_uppercase_dataid_is_preserved(self): upper_hash = compute_hash(DATA_ID_RAW, REQUEST_ID, TS, SECRET) upper_header = build_header(upper_hash) WebhookSignatureValidator.validate(upper_header, REQUEST_ID, DATA_ID_RAW, SECRET) # --- case 3 --- def test_malformed_header_raises_malformed(self): with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate("this-is-garbage", REQUEST_ID, DATA_ID_LOWER, SECRET) self.assertEqual(ctx.exception.reason, SignatureFailureReason.MALFORMED_SIGNATURE_HEADER) self.assertEqual(ctx.exception.request_id, REQUEST_ID) # --- case 4 --- def test_missing_header_raises_missing_header(self): with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate(None, REQUEST_ID, DATA_ID_LOWER, SECRET) self.assertEqual(ctx.exception.reason, SignatureFailureReason.MISSING_SIGNATURE_HEADER) # --- case 5 --- def test_missing_ts_raises_missing_timestamp(self): header = f"v1={VALID_HASH}" with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate(header, REQUEST_ID, DATA_ID_LOWER, SECRET) self.assertEqual(ctx.exception.reason, SignatureFailureReason.MISSING_TIMESTAMP) # --- case 6 --- def test_missing_v1_raises_missing_hash(self): with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate( f"ts={TS}", REQUEST_ID, DATA_ID_LOWER, SECRET ) self.assertEqual(ctx.exception.reason, SignatureFailureReason.MISSING_HASH) self.assertEqual(ctx.exception.timestamp, TS) # --- case 7 --- def test_tampered_hash_raises_signature_mismatch(self): tampered = VALID_HASH[:-2] + ("ff" if VALID_HASH.endswith("00") else "00") with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate( build_header(tampered), REQUEST_ID, DATA_ID_LOWER, SECRET ) self.assertEqual(ctx.exception.reason, SignatureFailureReason.SIGNATURE_MISMATCH) # --- case 8 --- def test_timestamp_outside_tolerance_raises(self): stale_ts = str(int(time.time()) - 30 * 60) # 30 minutes ago, in seconds h = compute_hash(DATA_ID_LOWER, REQUEST_ID, stale_ts, SECRET) with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate( build_header(h, stale_ts), REQUEST_ID, DATA_ID_LOWER, SECRET, tolerance_seconds=300, ) self.assertEqual(ctx.exception.reason, SignatureFailureReason.TIMESTAMP_OUT_OF_TOLERANCE) def test_timestamp_within_tolerance_passes(self): current_ts = str(int(time.time())) # current time in seconds h = compute_hash(DATA_ID_LOWER, REQUEST_ID, current_ts, SECRET) WebhookSignatureValidator.validate( build_header(h, current_ts), REQUEST_ID, DATA_ID_LOWER, SECRET, tolerance_seconds=300, ) def test_timestamp_seconds_within_tolerance_passes(self): ts = int(time.time()) # Unix timestamp in seconds ts_str = str(ts) h = compute_hash(DATA_ID_LOWER, REQUEST_ID, ts_str, SECRET) WebhookSignatureValidator.validate( build_header(h, ts_str), REQUEST_ID, DATA_ID_LOWER, SECRET, tolerance_seconds=3600, ) # --- case 9 --- def test_dataid_absent_excludes_id_pair(self): h = compute_hash(None, REQUEST_ID, TS, SECRET) WebhookSignatureValidator.validate(build_header(h), REQUEST_ID, None, SECRET) # --- case 10 --- def test_request_id_absent_excludes_request_id_pair(self): h = compute_hash(DATA_ID_LOWER, None, TS, SECRET) WebhookSignatureValidator.validate(build_header(h), None, DATA_ID_LOWER, SECRET) # --- case 11 --- def test_both_absent_yields_ts_only(self): h = compute_hash(None, None, TS, SECRET) WebhookSignatureValidator.validate(build_header(h), "", " ", SECRET) # --- case 12 --- def test_non_payment_topic_uses_same_algorithm(self): order_id = "ord01abc123" h = compute_hash(order_id, REQUEST_ID, TS, SECRET) WebhookSignatureValidator.validate(build_header(h), REQUEST_ID, order_id, SECRET) # --- supportedVersions --- def test_supports_v1_when_both_present(self): header = f"ts={TS},v1={VALID_HASH},v2=aaaa" WebhookSignatureValidator.validate(header, REQUEST_ID, DATA_ID_LOWER, SECRET, supported_versions=["v1"]) def test_only_v2_in_header_only_v1_supported_raises_missing_hash(self): header = f"ts={TS},v2=somehash" with self.assertRaises(InvalidWebhookSignatureError) as ctx: WebhookSignatureValidator.validate(header, REQUEST_ID, DATA_ID_LOWER, SECRET, supported_versions=["v1"]) self.assertEqual(ctx.exception.reason, SignatureFailureReason.MISSING_HASH) # --- secret null guard --- def test_null_secret_raises_value_error(self): with self.assertRaises(ValueError): WebhookSignatureValidator.validate(VALID_HEADER, REQUEST_ID, DATA_ID_LOWER, None) if __name__ == "__main__": unittest.main()