Mercado Pago PHP SDK

repository·master·Indexed 19 days ago

https://github.com/mercadopago/sdk-php

PHP bindings for integrating Mercado Pago payment APIs, supporting custom form integrations and hosted Checkout Pro flows. Requires PHP 8.2 or higher. Features include the PreferenceClient for hosted checkouts, OrderClient for custom forms, and MPApiException for detailed API error handling. Version 3 introduces a client-based request pattern and updated configuration via MercadoPagoConfig.

Tokens
13.1K
Snippets
16
Records
36
Agent score
61%

What's inside mercadopago-sdk-php

  1. Guidelines for writing code comments

    master

    Comments should improve the reading experience without obfuscating the code.

    When to comment:

    • When a decision departs from common wisdom or convention (explain the why).
    • When a code fragment took significant thought to produce (e.g., >1 hour of thinking for a small implementation).
    • When you need to preserve implementation properties (e.g., performance-sensitive code, security primitives, or congestion control).

    When NOT to comment:

    • On program structures that are already part of a standard convention.
    • To provide pedantic explanations of behavior that is immediately obvious from the surrounding code.
    • On behavior you cannot personally attest to.
  2. Security guidelines for reporting issues

    master

    ⚠️ NEVER Share Sensitive Data in Public Issues

    To protect your security, never include the following in a GitHub issue:

    • Access tokens or production credentials
    • Client IDs / Client Secrets
    • Customer or card data
    • Personally Identifiable Information (PII)

    Note: Issues containing real sensitive data will be closed and reported immediately.

  3. Integrate payments via Checkout Pro

    master

    Checkout Pro allows you to redirect users to a Mercado Pago hosted checkout page. The workflow involves:

    1. Authentication: Set the access token via MercadoPagoConfig.
    2. Preference Creation: Define a request array containing items, payer, payment_methods, and back_urls (success, failure, etc.).
    3. Preference Client: Use PreferenceClient to send the request to the API.
    4. Redirect: Use the init_point property from the returned Preference object to redirect the user to the checkout URL.

    You can also retrieve an existing preference using $client->get("PREFERENCE_ID").

    use MercadoPago\MercadoPagoConfig;
    use MercadoPago\Client\Preference\PreferenceClient;
    use MercadoPago\Exceptions\MPApiException;
    
    // 1. Authenticate
    MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
    
    // 2. Prepare items and payer
    $items = [
        [
            "id" => "1234567890",
            "title" => "Product 1",
            "description" => "Description",
            "currency_id" => "BRL",
            "quantity" => 1,
            "unit_price" => 9.90
        ]
    ];
    
    $payer = [
        "name" => "John",
        "surname" => "Doe",
        "email" => "john.doe@example.com",
    ];
    
    // 3. Create the preference request
    $request = [
        "items" => $items,
        "payer" => $payer,
        "back_urls" => [
            'success' => 'https://your-site.com/success',
            'failure' => 'https://your-site.com/failed'
        ],
        "external_reference" => "1234567890",
        "auto_return" => 'approved',
    ];
    
    // 4. Execute via PreferenceClient
    $client = new PreferenceClient();
    try {
        $preference = $client->create($request);
        // Use $preference->init_point to redirect the user
        echo "Redirect to: " . $preference->init_point;
    } catch (MPApiException $error) {
        // Handle error
    }
  4. Update Imports and Configuration for v3

    master

    Namespaces have changed. You must update your use statements and the way you set the access token.

    Version 2 (Old):

    require_once './vendor/autoload.php';
    
    MercadoPago\SDK::setAccessToken("<ACCESS_TOKEN>");
    
    $payment = new MercadoPago\Payment();

    Version 3 (New):

    require_once './vendor/autoload.php';
    
    use MercadoPago\Client\Payment\PaymentClient;
    use MercadoPago\MercadoPagoConfig;
    
    MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
    
    $client = new PaymentClient();
  5. How to report a bug in the SDK

    master

    If you encounter errors, unexpected behavior, or crashes, follow these steps to report a bug on GitHub:

    1. Verify Version: Ensure you are using the latest version of the SDK.
    2. Search Existing Issues: Check existing bugs to see if it has already been reported.
    3. Report Bug: Create a new bug report.
    4. Required Information: To get help quickly, you must include:
      • Reproducible steps
      • Logs
      • Environment details
      • SDK version
  6. Determine where to report your issue

    master

    Use the following guide to decide whether to use GitHub Issues or Official Mercado Pago Support:

    Use GitHub Issues for SDK Technical Support:

    • Questions: Doubts about SDK usage, configuration, or best practices.
    • Bugs: Errors, unexpected behavior, or crashes within the SDK.
    • Features: Proposing improvements or new features for the SDK.
    • Contributions: Wanting to help improve the SDK code.

    Use Official Mercado Pago Support for Account and Transactional Issues:

    • Account Problems: Access issues, credentials, or account-specific settings.
    • Transactions: Problems with specific payments, transactions, or billing.
    • Commercial/Legal: Commercial topics or certification/homologation.
    • Webhooks: Configuration of webhooks within your Mercado Pago account.
    • Data: Reports and statistics.
  7. Install the Mercado Pago PHP SDK via Composer

    master

    To install the Mercado Pago PHP SDK, use Composer. The SDK requires PHP 8.2 or higher.

    If you are migrating from version 2, consult the MIGRATION_GUIDE.md file.

    Run the following command to install the latest stable version (3.13.0):

    composer require "mercadopago/dx-php:3.13.0"
  8. Handle Exceptions in v3

    master

    Version 3 introduces MPApiException to specifically handle errors returned by the Mercado Pago API. You can access the status code and response content through this exception. Standard PHP Exception should be used for non-API related errors.

    try {
        $payment = $client->create($request);
    } catch (MPApiException $e) {
        // Handle API-specific errors
        echo $e->getApiResponse()->getStatusCode();
        echo $e->getApiResponse()->getContent();
    } catch (Exception $e) {
        // Handle general errors
        echo $e->getMessage();
    }
    try {
        $payment = $client->create($request);
    } catch (MPApiException $e) {
        echo $e->getApiResponse()->getStatusCode();
        echo $e->getApiResponse()->getContent();
    } catch (Exception $e) {
        echo $e->getMessage();
    }
  9. Process payments via custom website forms

    master

    To process a payment directly through your own form, follow these steps:

    1. Initialize the Client: Instantiate the appropriate client (e.g., OrderClient).
    2. Prepare the Request: Create an associative array containing payment details like total_amount, payer, and transactions.
    3. Set Idempotency: Use RequestOptions to set a unique X-Idempotency-Key in the custom headers to prevent duplicate processing.
    4. Execute: Call the create() method on the client.
    5. Handle Errors: Wrap the call in a try-catch block to handle MPApiException (for API-specific errors) and general ext{Exception}.
    <?php
    require_once 'vendor/autoload.php';
    
    use MercadoPago\Client\Common\RequestOptions;
    use MercadoPago\Client\Order\OrderClient;
    use MercadoPago\Exceptions\MPApiException;
    use MercadoPago\MercadoPagoConfig;
    
    MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
    
    $client = new OrderClient();
    
    try {
        $request = [
            "type" => "online",
            "processing_mode" => "automatic",
            "total_amount" => "1000.00",
            "external_reference" => "ext_ref_1234",
            "capture_mode" => "automatic_async",
            "payer" => [
                "email" => "<PAYER_EMAIL>",
            ],
            "transactions" => [
                "payments" => [
                    [
                        "amount" => "1000.00",
                        "payment_method" => [
                            "id" => "master",
                            "type" => "credit_card",
                            "token" => "<CARD_TOKEN>",
                            "installments" => 1,
                            "statement_descriptor" => "Store name",
                        ]
                    ]
                ]
            ]
        ];
    
        $request_options = new RequestOptions();
        $request_options->setCustomHeaders(["X-Idempotency-Key: <SOME_UNIQUE_VALUE>"]);
    
        $order = $client->create($request, $request_options);
        echo "Order ID:" . $order->id;
    
    } catch (MPApiException $e) {
        echo "Status code: " . $e->getApiResponse()->getStatusCode() . "\n";
        echo "Content: ";
        var_dump($e->getApiResponse()->getContent());
    } catch (\Exception $e) {
        echo $e->getMessage();
    }
  10. Follow Git commit message guidelines

    master

    All commits should follow professional Git standards to maintain a readable history. Specifically, follow these seven rules:

    1. Separate the subject from the 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 (e.g., "Add feature" instead of "Added feature").
    6. Wrap the body at 72 characters.
    7. Use the body to explain what and why, rather than how.

    Avoid vague messages like "fix tests" or "now it's working".

  11. Set up pre-commit for code style and formatting

    master

    To ensure contributions follow the SDK's code style and formatting, the project uses the pre-commit tool. You must install pre-commit on your machine and then initialize the project's git hooks. These hooks run automatically before every commit. Note that pull requests will be automatically rejected if these checks fail.

    # 1. Verify pre-commit is installed
    pre-commit --version
    
    # 2. Inside the SDK project folder, set up the git hooks
    pre-commit install