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

第一步:获取access_token:

php 复制代码
<?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 复制代码
<?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);
相关推荐
佛系打工仔4 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
LawrenceLan5 小时前
Flutter 零基础入门(十一):空安全(Null Safety)基础
开发语言·flutter·dart
txinyu的博客6 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
码不停蹄Zzz6 小时前
C语言第1章
c语言·开发语言
行者966 小时前
Flutter跨平台开发在OpenHarmony上的评分组件实现与优化
开发语言·flutter·harmonyos·鸿蒙
阿蒙Amon7 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
SmartRadio7 小时前
ESP32添加修改蓝牙名称和获取蓝牙连接状态的AT命令-完整UART BLE服务功能后的完整`main.c`代码
c语言·开发语言·c++·esp32·ble
且去填词7 小时前
Go 语言的“反叛”——为什么少即是多?
开发语言·后端·面试·go
my_power5207 小时前
车载安卓面试题汇总
android
csj507 小时前
安卓基础之《(15)—内容提供者(1)在应用之间共享数据》
android