File: /www/wwwroot/www.ydrbh.com/3.php
<?php
// PayPal认证信息
$client_id = 'AZ5q35RRvAI9oU9ss-E4yRYVELSIaIcLpv_mmd4oPgv7WmvwJupJmzQaQXN2RTsEZgPNQhXmwzGx-D0z'; // 在PayPal开发者平台上获取
$client_secret = 'EOsd5viKcp8D9nd6JewX7tuqFLc6m-0wl4tmHNeHFu8Giwbw1Hf06rxLuDVRH1QJyJTtmg2VXH9-VEcO'; // 在PayPal开发者平台上获取
$api_url = 'https://api.sandbox.paypal.com'; // PayPal 沙箱环境 API 地址
// 获取 OAuth 令牌
function getAccessToken($client_id, $client_secret, $api_url) {
$url = $api_url . '/v1/oauth2/token';
$headers = [
'Accept: application/json',
'Accept-Language: en_US',
];
$data = [
'grant_type' => 'client_credentials',
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $client_id . ":" . $client_secret);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result['access_token'];
}
// 创建支付请求
function createPayment($access_token, $api_url) {
$url = $api_url . '/v1/payments/payment';
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $access_token,
];
// 设置支付信息
$paymentData = [
'intent' => 'sale',
'payer' => [
'payment_method' => 'paypal',
],
'transactions' => [
[
'amount' => [
'total' => '10.00', // 这里设置支付金额
'currency' => 'USD', // 设置币种
],
'description' => '支付示例',
]
],
'redirect_urls' => [
'return_url' => 'http://www.ydrbh.com/3.php?success=true', // 支付成功后的回调URL
'cancel_url' => 'http://www.ydrbh.com/3.php?cancel=true', // 支付取消后的回调URL
],
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 获取 Access Token
$access_token = getAccessToken($client_id, $client_secret, $api_url);
// 创建支付
$paymentResponse = createPayment($access_token, $api_url);
// 检查支付请求是否成功,并重定向用户到 PayPal
if (isset($paymentResponse['links'])) {
foreach ($paymentResponse['links'] as $link) {
if ($link['rel'] == 'approval_url') {
// 重定向到 PayPal 的支付页面
header('Location: ' . $link['href']);
exit;
}
}
}
// 如果没有找到 approval_url,则显示错误信息
echo '支付创建失败,请稍后再试。';
?>