-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.php
More file actions
114 lines (99 loc) · 4.26 KB
/
Copy pathrouter.php
File metadata and controls
114 lines (99 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
require __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;
use PaypalServerSdkLib\Authentication\ClientCredentialsAuthCredentialsBuilder;
use PaypalServerSdkLib\Environment;
use PaypalServerSdkLib\Models\Builders\AmountWithBreakdownBuilder;
use PaypalServerSdkLib\Models\Builders\OrderRequestBuilder;
use PaypalServerSdkLib\Models\Builders\PurchaseUnitRequestBuilder;
use PaypalServerSdkLib\Models\CheckoutPaymentIntent;
use PaypalServerSdkLib\PaypalServerSdkClientBuilder;
Dotenv::createImmutable(__DIR__)->safeLoad();
// Create a configuration object for PayPal settings, using environment variables for sensitive information.
$paypalSettings = [
'clientId' => $_ENV['PAYPAL_CLIENT_ID'] ?? null,
'clientSecret' => $_ENV['PAYPAL_CLIENT_SECRET'] ?? null,
'env' => $_ENV['PAYPAL_ENV'] ?? 'sandbox',
];
// A simple in-memory catalogue of items that can be purchased.
// In a real application, you would look this up from a database.
// Prices are held server-side so they can't be tampered with from the browser.
$items = [
'demo-product' => ['currencyCode' => 'USD', 'value' => '9.99'],
];
// Create a PayPal client, configured with client credentials and environment settings,
// then get an OrdersController to handle order creation and capture.
$client = PaypalServerSdkClientBuilder::init()
->clientCredentialsAuthCredentials(
ClientCredentialsAuthCredentialsBuilder::init(
$paypalSettings['clientId'],
$paypalSettings['clientSecret'],
),
)
->environment($paypalSettings['env'] === 'live' ? Environment::PRODUCTION : Environment::SANDBOX)
->build();
$ordersController = $client->getOrdersController();
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// Hands the front-end the public clientId, env, and the correct sdkUrl.
// Loading the SDK URL from the server lets you switch between sandbox and live
// without touching client code.
if ($method === 'GET' && $path === '/api/config') {
header('Content-Type: application/json');
echo json_encode([
'clientId' => $paypalSettings['clientId'],
'env' => $paypalSettings['env'],
'sdkUrl' => $paypalSettings['env'] === 'live'
? 'https://www.paypal.com/web-sdk/v6/core'
: 'https://www.sandbox.paypal.com/web-sdk/v6/core',
]);
exit;
}
// Looks up the item by itemId, asks PayPal to create an order, and returns the order id.
if ($method === 'POST' && $path === '/api/orders') {
$body = json_decode(file_get_contents('php://input'), true) ?? [];
$item = $items[$body['itemId'] ?? ''] ?? null;
if (!$item) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid item ID']);
exit;
}
try {
$apiResponse = $ordersController->createOrder([
'body' => OrderRequestBuilder::init(
CheckoutPaymentIntent::CAPTURE,
[
PurchaseUnitRequestBuilder::init(
AmountWithBreakdownBuilder::init($item['currencyCode'], $item['value'])->build(),
)->build(),
],
)->build(),
]);
header('Content-Type: application/json');
echo json_encode(['orderId' => $apiResponse->getResult()->getId()]);
} catch (\Throwable $e) {
error_log($e->getMessage());
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Failed to create order']);
}
exit;
}
// Captures a previously approved order. Approving an order doesn't move any
// money on its own — capturing it does.
if ($method === 'POST' && preg_match('#^/api/orders/([^/]+)/capture$#', $path, $matches)) {
try {
$apiResponse = $ordersController->captureOrder(['id' => $matches[1]]);
header('Content-Type: application/json');
echo json_encode($apiResponse->getResult());
} catch (\Throwable $e) {
error_log($e->getMessage());
http_response_code(500);
header('Content-Type: application/json');
echo json_encode(['error' => 'Failed to capture order']);
}
exit;
}
// Anything else falls through to the built-in server's static file handling in public/.
return false;