This repository has been archived by the owner on Apr 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 546
/
index.php
218 lines (188 loc) Β· 8.42 KB
/
index.php
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<?php
use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;
use Store\Inventory;
use Store\Shipping;
// Due to a bug in the PHP embedded server, URLs containing a dot don't work
// This will fix the missing variable in that case
if (PHP_SAPI == 'cli-server') {
$_SERVER['SCRIPT_NAME'] = 'index.php';
}
require __DIR__ . '/vendor/autoload.php';
// Instantiate the app
$settings = require __DIR__ . '/settings.php';
$app = new \Slim\App($settings);
// Instantiate the logger as a dependency
$container = $app->getContainer();
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};
// Middleware
$app->add(function ($request, $response, $next) {
Stripe::setApiKey($this->get('settings')['stripe']['secretKey']);
$request = $request->withAttribute('staticDir', $this->get('settings')['stripe']['staticDir']);
return $next($request, $response);
});
// Serve the store
$app->get('/', function (Request $request, Response $response, array $args) {
return $response->write(file_get_contents($request->getAttribute('staticDir') . 'index.html'));
});
// Serve static assets and images for index.html
$paths = [
'javascripts' => 'text/javascript', 'stylesheets' => 'text/css',
'images' => FILEINFO_MIME_TYPE,
'images/products' => FILEINFO_MIME_TYPE,
'images/screenshots' => FILEINFO_MIME_TYPE
];
$app->get('/{path:' . implode('|', array_keys($paths)) . '}/{file:[^/]+}',
function (Request $request, Response $response, array $args) use ($paths) {
$resource = $request->getAttribute('staticDir') . $args['path'] . '/' . $args['file'];
if (!is_file($resource)) {
$notFoundHandler = $this->get('notFoundHandler');
return $notFoundHandler($request, $response);
}
return $response->write(file_get_contents($resource))
->withHeader('Content-Type', $paths[$args['path']]);
}
);
// General config
$app->get('/config', function (Request $request, Response $response, array $args) {
$config = $this->get('settings')['stripe'];
return $response->withJson([
'stripePublishableKey' => $config['publishableKey'],
'stripeCountry' => $config['accountCountry'],
'country' => $config['defaultCountry'],
'currency' => $config['shopCurrency'],
'paymentMethods' => implode($config['paymentMethods'], ', '),
'shippingOptions' => Shipping::getShippingOptions()
]);
});
// List of fake products on our fake shop
// Used to display the user's cart and calculate the total price
$app->get('/products', function (Request $request, Response $response, array $args) {
return $response->withJson(Inventory::listProducts());
});
// List of fake products on our fake shop
// Used to display the user's cart and calculate the total price
$app->get('/products/{id}', function (Request $request, Response $response, array $args) {
return $response->withJson(Inventory::getProduct($args['id']));
});
// Create the payment intent
// Used when the user starts the checkout flow
$app->post('/payment_intents', function (Request $request, Response $response, array $args) {
$data = $request->getParsedBody();
try {
//build initial payment methods which should exclude currency specific ones
$initPaymentMethods = array_diff($this->get('settings')['stripe']['paymentMethods'],['au_becs_debit']);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => Inventory::calculatePaymentAmount($data['items']),
'currency' => $data['currency'],
'payment_method_types' => $initPaymentMethods
]);
return $response->withJson([ 'paymentIntent' => $paymentIntent ]);
} catch (\Exception $e) {
return $response->withJson([ 'error' => $e->getMessage() ])->withStatus(403);
}
});
// Update the total when selected a different shipping option via the payment request API
$app->post('/payment_intents/{id}/shipping_change', function (Request $request, Response $response, array $args) {
$data = $request->getParsedBody();
$amount = Inventory::calculatePaymentAmount($data['items']);
$amount += Shipping::getShippingCost($data['shippingOption']['id']);
try {
$paymentIntent = \Stripe\PaymentIntent::update($args['id'], [ 'amount' => $amount ]);
return $response->withJson([ 'paymentIntent' => $paymentIntent ]);
} catch (\Exception $e) {
return $response->withJson([ 'error' => $e->getMessage() ])->withStatus(403);
}
});
// Update PaymentIntent with currency and paymentMethod.
$app->post('/payment_intents/{id}/update_currency', function (Request $request, Response $response, array $args) {
$data = $request->getParsedBody();
$currency = $data['currency'];
$paymentMethods = $data['payment_methods'];
try {
$paymentIntent = \Stripe\PaymentIntent::update($args['id'], [ 'currency' => $currency, 'payment_method_types:' => $paymentMethods ]);
return $response->withJson([ 'paymentIntent' => $paymentIntent ]);
} catch (\Exception $e) {
return $response->withJson([ 'error' => $e->getMessage() ])->withStatus(403);
}
});
// Fetch the payment intent status
// Used for redirect sources when coming back to the return URL
$app->get('/payment_intents/{id}/status', function (Request $request, Response $response, array $args) {
$paymentIntent = \Stripe\PaymentIntent::retrieve($args['id']);
$data = [ 'paymentIntent' => [ 'status' => $paymentIntent->status ] ];
if ($paymentIntent->last_payment_error) {
$data['paymentIntent']['last_payment_error'] = $paymentIntent->last_payment_error->message;
}
return $response->withJson($data);
});
// Events receiver for payment intents and sources
$app->post('/webhook', function (Request $request, Response $response, array $args) {
$logger = $this->get('logger');
// Parse the message body (and check the signature if possible)
$webhookSecret = $this->get('settings')['stripe']['webhookSecret'];
if ($webhookSecret) {
try {
$event = \Stripe\Webhook::constructEvent(
$request->getBody(),
$request->getHeaderLine('stripe-signature'),
$webhookSecret
);
} catch (\Exception $e) {
return $response->withJson([ 'error' => $e->getMessage() ])->withStatus(403);
}
} else {
$event = $request->getParsedBody();
}
$type = $event['type'];
$object = $event['data']['object'];
switch ($object['object']) {
case 'payment_intent':
$paymentIntent = $object;
if ($type == 'payment_intent.succeeded') {
// Payment intent successfully completed
$logger->info('π Webhook received! Payment for PaymentIntent ' .
$paymentIntent['id'] . ' succeeded');
} elseif ($type == 'payment_intent.payment_failed') {
// Payment intent completed with failure
$logger->info('π Webhook received! Payment for PaymentIntent ' . $paymentIntent['id'] . ' failed');
}
break;
case 'source':
$source = $object;
if (!isset($source['metadata']['paymentIntent'])) {
// Could be a source from another integration
$logger->info('π Webhook received! Source ' . $source['id'] .
' did not contain any payment intent in its metadata, ignoring it...');
continue;
}
// Retrieve the payment intent this source was created for
$paymentIntent = \Stripe\PaymentIntent::retrieve($source['metadata']['paymentIntent']);
// Check the source status
if ($source['status'] == 'chargeable') {
// Source is chargeable, use it to confirm the payment intent if possible
if (!in_array($paymentIntent->status, [ 'requires_source', 'requires_payment_method' ])) {
$info = "PaymentIntent {$paymentIntent->id} already has a status of {$paymentIntent->status}";
$logger->info($info);
return $response->withJson([ 'info' => $info ])->withStatus(200);
}
$paymentIntent->confirm([ 'source' => $source['id'] ]);
} elseif (in_array($source['status'], [ 'failed', 'canceled' ])) {
// Source failed or has been canceled, cancel the payment intent to let the polling know
$logger->info('π Webhook received! Source ' . $source['id'] .
' failed or has been canceled, canceling PaymentIntent ' . $paymentIntent->id);
$paymentIntent->cancel();
}
break;
}
return $response->withJson([ 'status' => 'success' ])->withStatus(200);
});
// Run app
$app->run();