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);
相关推荐
熬了夜的程序员13 分钟前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
轻口味20 分钟前
Rokid Glasses 移动端控制应用开发初体验-助力业务创新
android·操作系统·app
草莓熊Lotso29 分钟前
C++ 手写 List 容器实战:从双向链表原理到完整功能落地,附源码与测试验证
开发语言·c++·链表·list
无限进步_31 分钟前
【C语言】杨辉三角:数学之美与编程实现的完美结合
c语言·开发语言
Cg1362691597432 分钟前
封装的实现和定义
java·开发语言
wxin_VXbishe32 分钟前
基于SpringBoot的天天商城管理系统的设计与现-计算机毕业设计源码79506
java·c++·spring boot·python·spring·django·php
武子康37 分钟前
Java-146 深入浅出 MongoDB 数据插入、批量写入、BSON 格式与逻辑查询and or not操作指南
java·开发语言·数据库·sql·mongodb·性能优化·nosql
初圣魔门首席弟子41 分钟前
const string getWord() ;和 string getWord() const ;是一样的效果吗
开发语言·c++
lly2024061 小时前
Docker 安装 Node.js
开发语言
明天会有多晴朗1 小时前
C语言入门教程(第6讲):函数——让程序学会“分工合作”的魔法
c语言·开发语言·算法