paypal支付v2.0(php)支付代码

发布于:2024-10-09 ⋅ 阅读:(26) ⋅ 点赞:(0)

第一步:获取access_token:

<?php

$clientId = '';     // 替换为你的 PayPal Client ID
$clientSecret = ''; // 替换为你的 PayPal Client Secret

// PayPal API 请求的 URL
$url = "https://api-m.sandbox.paypal.com/v1/oauth2/token";

// 初始化 cURL
$ch = curl_init();

// 设置 cURL 请求的参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

// 执行请求
$response = curl_exec($ch);

// 检查请求是否出错
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // 打印响应结果
    echo $response;
}

// 关闭 cURL
curl_close($ch);

第二步:创建订单:

<?php

$accessToken = ''; // 替换为你的访问令牌
$paypalRequestId = '7b92603e-77ed-4896-8e78-5dea2050476a'; // 替换为你的 PayPal 请求 ID

// API URL
$url = "https://api-m.sandbox.paypal.com/v2/checkout/orders";

// 创建订单的数据
$data = [
    "intent" => "CAPTURE",
    "purchase_units" => [
        [
            "reference_id" => "d9f80740-38f0-11e8-b467-0ed5f89f718b",
            "amount" => [
                "currency_code" => "USD",
                "value" => "1.00"
            ]
        ]
    ],
    "payment_source" => [
        "paypal" => [
            "experience_context" => [
                "return_url" => "https://example.com/returnUrl",
                "cancel_url" => "https://example.com/cancelUrl"
            ]
        ]
    ]
];

// 初始化 cURL
$ch = curl_init();

// 设置 cURL 参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'PayPal-Request-Id: ' . $paypalRequestId,
    'Authorization: Bearer ' . $accessToken,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// 执行请求并获取响应
$response = curl_exec($ch);

// 检查是否有错误
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // 输出响应
    echo $response;
}

// 关闭 cURL
curl_close($ch);