mercadopago/dx-php

Mercado Pago PHP SDK

安装次数: 3,991,965

依赖: 30

建议者: 0

安全: 0

星标: 319

关注者: 54

分支: 194


README

image

Mercado Pago PHP SDK

Latest Stable Version Total Downloads License

此库为开发者提供了一套简单的绑定,帮助您将 Mercado Pago API 集成到网站中,并开始接收支付。

💡 要求

SDK 支持 PHP 8.2 或更高版本。

💻 安装

如果您已经使用另一个版本的 Mercado Pago PHP SDK,请查看我们从版本 2 到版本 3 的 迁移指南

第一次使用 Mercado Pago?如果您还没有,请创建您的 Mercado Pago 账户

  1. 如果尚未安装,请下载 Composer

  2. 在命令行中安装 Mercado Pago PHP SDK

composer require "mercadopago/dx-php:3.0.8"

您还可以运行 composer require "mercadopago/dx-php:2.6.2" 以支持 PHP7.1 或 composer require "mercadopago/dx-php:1.12.6" 以支持 PHP5.6。

  1. 将访问令牌复制到页面上的 凭证 部分,并用它替换 YOUR_ACCESS_TOKEN。

这就完成了!Mercado Pago SDK 已成功安装。

有用的链接

在这里,您可以检查 SDK 为每个类使用的每个参数的数据结构。

🌟 通过您的网站表单开始支付

简单用法如下

<?php
    // Step 1: Require the library from your Composer vendor folder
    require_once 'vendor/autoload.php';

    use MercadoPago\Client\Common\RequestOptions;
    use MercadoPago\Client\Payment\PaymentClient;
    use MercadoPago\Exceptions\MPApiException;
    use MercadoPago\MercadoPagoConfig;

    // Step 2: Set production or sandbox access token
    MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");
    // Step 2.1 (optional - default is SERVER): Set your runtime enviroment from MercadoPagoConfig::RUNTIME_ENVIROMENTS
    // In case you want to test in your local machine first, set runtime enviroment to LOCAL
    MercadoPagoConfig::setRuntimeEnviroment(MercadoPagoConfig::LOCAL);

    // Step 3: Initialize the API client
    $client = new PaymentClient();

    try {

        // Step 4: Create the request array
        $request = [
            "transaction_amount" => 100,
            "token" => "YOUR_CARD_TOKEN",
            "description" => "description",
            "installments" => 1,
            "payment_method_id" => "visa",
            "payer" => [
                "email" => "user@test.com",
            ]
        ];

        // Step 5: Create the request options, setting X-Idempotency-Key
        $request_options = new RequestOptions();
        $request_options->setCustomHeaders(["X-Idempotency-Key: <SOME_UNIQUE_VALUE>"]);

        // Step 6: Make the request
        $payment = $client->create($request, $request_options);
        echo $payment->id;

    // Step 7: Handle exceptions
    } catch (MPApiException $e) {
        echo "Status code: " . $e->getApiResponse()->getStatusCode() . "\n";
        echo "Content: ";
        var_dump($e->getApiResponse()->getContent());
        echo "\n";
    } catch (\Exception $e) {
        echo $e->getMessage();
    }

步骤 1:从您的 Composer 供应商文件夹中引入库

require_once 'vendor/autoload.php';

use MercadoPago\Client\Common\RequestOptions;
use MercadoPago\Client\Payment\PaymentClient;
use MercadoPago\Exceptions\MPApiException;
use MercadoPago\MercadoPagoConfig;

步骤 2:设置生产或沙盒访问令牌

MercadoPagoConfig::setAccessToken("<ACCESS_TOKEN>");

您还可以设置其他属性,例如重试次数、跟踪头、超时和自定义 HTTP 客户端。

步骤 3:初始化 API 客户端

$client = new PaymentClient();

步骤 4:创建请求数组

$request = [
    "transaction_amount" => 100,
    "token" => "YOUR_CARD_TOKEN",
    "description" => "description",
    "installments" => 1,
    "payment_method_id" => "visa",
    "payer" => [
        "email" => "user@test.com",
    ]
];

步骤 5:创建请求选项,设置 X-Idempotency-Key

$request_options = new RequestOptions();
$request_options->setCustomHeaders(["X-Idempotency-Key: <SOME_UNIQUE_VALUE>"]);

步骤 6:发出请求

$payment = $client->create($request, $request_options);

步骤 7:处理异常

try{
    // Do your stuff here
} catch (MPApiException $e) {
    // Handle API exceptions
    echo "Status code: " . $e->getApiResponse()->getStatusCode() . "\n";
    echo "Content: ";
    var_dump($e->getApiResponse()->getContent());
    echo "\n";
} catch (\Exception $e) {
    // Handle all other exceptions
    echo $e->getMessage();
}

🌟 通过 Checkout Pro 开始支付

步骤 1:引入库

use MercadoPago\MercadoPagoConfig;
use MercadoPago\Client\Preference\PreferenceClient;
use MercadoPago\Exceptions\MPApiException;

步骤 2:创建身份验证函数

protected function authenticate()
{
    // Getting the access token from .env file (create your own function)
    $mpAccessToken = getVariableFromEnv('mercado_pago_access_token');
    // Set the token the SDK's config
    MercadoPagoConfig::setAccessToken($mpAccessToken);
    // (Optional) Set the runtime enviroment to LOCAL if you want to test on localhost
    // Default value is set to SERVER
    MercadoPagoConfig::setRuntimeEnviroment(MercadoPagoConfig::LOCAL);
}

步骤 3:在转到 Checkout Pro 页面前创建客户的偏好设置

// Function that will return a request object to be sent to Mercado Pago API
function createPreferenceRequest($items, $payer): array
{
    $paymentMethods = [
        "excluded_payment_methods" => [],
        "installments" => 12,
        "default_installments" => 1
    ];

    $backUrls = array(
        'success' => route('mercadopago.success'),
        'failure' => route('mercadopago.failed')
    );

    $request = [
        "items" => $items,
        "payer" => $payer,
        "payment_methods" => $paymentMethods,
        "back_urls" => $backUrls,
        "statement_descriptor" => "NAME_DISPLAYED_IN_USER_BILLING",
        "external_reference" => "1234567890",
        "expires" => false,
        "auto_return" => 'approved',
    ];

    return $request;
}

步骤 4:在 Mercado Pago 上创建偏好设置(文档

public function createPaymentPreference(): ?Preference
{
    // Fill the data about the product(s) being pruchased
    $product1 = array(
        "id" => "1234567890",
        "title" => "Product 1 Title",
        "description" => "Product 1 Description",
        "currency_id" => "BRL",
        "quantity" => 12,
        "unit_price" => 9.90
    );

    $product2 = array(
        "id" => "9012345678",
        "title" => "Product 2 Title",
        "description" => "Product 2 Description",
        "currency_id" => "BRL",
        "quantity" => 5,
        "unit_price" => 19.90
    );

    // Mount the array of products that will integrate the purchase amount
    $items = array($product1, $product2);

    // Retrieve information about the user (use your own function)
    $user = getSessionUser();

    $payer = array(
        "name" => $user->name,
        "surname" => $user->surname,
        "email" => $user->email,
    );

    // Create the request object to be sent to the API when the preference is created
    $request = createPreferenceRequest($item, $payer);

    // Instantiate a new Preference Client
    $client = new PreferenceClient();

    try {
        // Send the request that will create the new preference for user's checkout flow
        $preference = $client->create($request);

        // Useful props you could use from this object is 'init_point' (URL to Checkout Pro) or the 'id'
        return $preference;
    } catch (MPApiException $error) {
        // Here you might return whatever your app needs.
        // We are returning null here as an example.
        return null;
    }
}

如果您需要通过 ID 检索偏好设置

    $client = new PreferenceClient();
    $client->get("123456789");

📚 文档

请参阅我们的文档以获取更多详细信息。

🤝 贡献

我们欢迎所有贡献,包括想要处理问题的人,想要编写文档的人,以及想要贡献代码的人。

请阅读并遵循我们的 贡献指南。不符合这些指南的贡献将被忽略。这些指南旨在使我们的生活更加轻松,并使贡献过程对每个人来说都是一致的。

针对 2.x.x 版本的补丁

自3.0.0版本发布以来,版本2已弃用,将不会接收新功能,仅修复bug。如果您需要为该版本提交PR,请使用master-v2作为您的基准分支。

❤️ 支持

如果您需要技术支持,请通过我们的开发者网站联系我们的支持团队: 英文 / 葡萄牙语 / 西班牙语

🏻 许可证

MIT license. Copyright (c) 2023 - Mercado Pago / Mercado Libre
For more information, see the LICENSE file.