-
Notifications
You must be signed in to change notification settings - Fork 0
/
_routes.php
executable file
·478 lines (426 loc) · 18.6 KB
/
_routes.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Stripe routes
*
* Copyright © 2021 The Galette Team
*
* This file is part of Galette (http://galette.tuxfamily.org).
*
* Galette is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Galette is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Galette. If not, see <http://www.gnu.org/licenses/>.
*
* @category Plugins
* @package GaletteStripe
*
* @author Mathieu PELLEGRIN <dev@pingveno.net>
* @copyright 2021 The Galette Team
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
* @link http://galette.tuxfamily.org
*/
use Analog\Analog;
use GaletteStripe\Stripe;
use GaletteStripe\StripeHistory;
use Galette\Entity\Contribution;
use Galette\Entity\ContributionsTypes;
use Galette\Filters\HistoryList;
use Galette\Entity\PaymentType;
use Galette\Entity\Adherent;
//Constants and classes from plugin
require_once $module['root'] . '/_config.inc.php';
$this->get(
'/preferences',
function ($request, $response, $args) use ($module, $module_id) {
if ($this->session->stripe !== null) {
$stripe = $this->session->stripe;
$this->session->stripe = null;
} else {
$stripe = new Stripe($this->zdb);
}
$amounts = $stripe->getAllAmounts();
$countries = $stripe->getAllCountries();
$currencies = $stripe->getAllCurrencies();
$params = [
'page_title' => _T('Stripe Settings', 'stripe'),
'stripe' => $stripe,
'webhook_url' => 'plugins/' . $module['route'] . '/webhook',
'amounts' => $amounts,
'countries' => $countries,
'currencies' => $currencies,
];
// display page
$this->view->render(
$response,
'file:[' . $module['route'] . ']stripe_preferences.tpl',
$params
);
return $response;
}
)->setName('stripe_preferences')->add($authenticate);
$this->post(
'/preferences',
function ($request, $response, $args) use ($module, $module_id) {
$post = $request->getParsedBody();
$stripe = new Stripe($this->zdb);
if (isset($post['amounts'])) {
if (isset($post['stripe_pubkey']) && $this->login->isAdmin()) {
$stripe->setPubKey($post['stripe_pubkey']);
}
if (isset($post['stripe_privkey']) && $this->login->isAdmin()) {
$stripe->setPrivKey($post['stripe_privkey']);
}
if (isset($post['stripe_webhook_secret']) && $this->login->isAdmin()) {
$stripe->setWebhookSecret($post['stripe_webhook_secret']);
}
if (isset($post['amount_id']) && isset($post['amounts'])) {
$stripe->setPrices($post['amount_id'], $post['amounts']);
}
if (isset($post['stripe_country']) && $this->login->isAdmin()) {
$stripe->setCountry($post['stripe_country']);
}
if (isset($post['stripe_currency']) && $this->login->isAdmin()) {
$stripe->setCurrency($post['stripe_currency']);
}
if (isset($post['inactives'])) {
$stripe->setInactives($post['inactives']);
} else {
$stripe->unsetInactives();
}
$stored = $stripe->store();
if ($stored) {
$this->flash->addMessage(
'success_detected',
_T('Stripe preferences has been saved.', 'stripe')
);
} else {
$this->session->stripe = $stripe;
$this->flash->addMessage(
'error_detected',
_T('An error occured saving stripe preferences :(', 'stripe')
);
}
}
return $response
->withStatus(301)
->withHeader('Location', $this->router->pathFor('stripe_preferences'));
}
)->setName('store_stripe_preferences')->add($authenticate);
$this->get(
'/form',
function ($request, $response) use ($module, $module_id) {
$stripe = new Stripe($this->zdb);
$current_url = $this->preferences->getURL();
$params = [
'stripe' => $stripe,
'amounts' => $stripe->getAmounts($this->login),
'page_title' => _T('Stripe payment', 'stripe'),
'message' => null,
'current_url' => rtrim($current_url, '/')
];
// display page
$this->view->render(
$response,
'file:[' . $module['route'] . ']stripe_form_amount.tpl',
$params
);
return $response;
}
)->setName('stripe_form_amount');
$this->post(
'/form',
function ($request, $response) use ($module, $module_id) {
$stripe_request = $request->getParsedBody();
$stripe = new Stripe($this->zdb);
$adherent = new Adherent($this->zdb);
$current_url = $this->preferences->getURL();
// Check the amount
$item_number = $stripe_request['item_number'];
$amount = $stripe_request['amount'];
$stripe_amounts = $stripe->getAmounts($this->login);
if ($amount < $stripe_amounts[$item_number]['amount']) {
$params = [
'stripe' => $stripe,
'amounts' => $stripe->getAmounts($this->login),
'page_title' => _T('Stripe payment', 'stripe'),
'message' => _T('The amount you\'ve entered is lower than the minimum amount for the selected option.\\nPlease choose another option or change the amount.', 'stripe'),
'current_url' => rtrim($current_url, '/')
];
// display page
$this->view->render(
$response,
'file:[' . $module['route'] . ']stripe_form_amount.tpl',
$params
);
return $response;
} else {
if ($this->login->isLogged() && !$this->login->isSuperAdmin()) {
$adherent->load($this->login->id);
$metadata['adherent_name'] = Adherent::getSName($this->zdb, $this->login->id);
$metadata['adherent_company'] = $adherent->_company_name;
$metadata['adherent_address_1'] = $adherent->getAddress();
$metadata['adherent_address_2'] = $adherent->getAddressContinuation();
$metadata['adherent_zip'] = $adherent->getZipcode();
$metadata['adherent_town'] = $adherent->getTown();
$metadata['adherent_country'] = $adherent->getCountry();
$metadata['adherent_email'] = $adherent->getEmail();
$metadata['adherent_id'] = $this->login->id;
$metadata['contrib_id'] = $item_number;
}
$client_secret = $stripe->createPaymentIntent($metadata, $amount);
$params = [
'stripe' => $stripe,
'amount' => $amount*100,
'item_name' => $stripe_amounts[$item_number]['name'],
'client_secret' => $client_secret,
'page_title' => _T('Stripe payment', 'stripe'),
'current_url' => rtrim($current_url, '/'),
'metadata' => $metadata,
];
// display page
$this->view->render(
$response,
'file:[' . $module['route'] . ']stripe_form_checkout.tpl',
$params
);
return $response;
}
}
)->setName('stripe_form_checkout');
$this->post(
'/webhook',
function ($request, $response) {
$post = $request->getParsedBody();
$body = $request->getBody();
$stripe = new Stripe($this->zdb);
// Check webhook signature
$stripe_signatures = $request->getHeader('HTTP_STRIPE_SIGNATURE');
foreach ($stripe_signatures as $signature) {
$parsedSignature = explode(',', $signature);
$sig_timestamp = null;
$sig_hash = null;
foreach ($parsedSignature as $chunk) {
$pair = explode('=', $chunk);
if ($pair[0] == 't') {
$sig_timestamp = $pair[1];
}
if ($pair[0] == 'v1') {
$sig_hash = $pair[1];
}
}
if (abs(time() - $sig_timestamp) > 5) {
Analog::log(
'Stripe signature delayed for too many seconds!',
Analog::ERROR
);
echo 'Stripe signature delayed for too many seconds!';
return $response->withStatus(403);
}
$signed_body = $sig_timestamp . '.' . $body;
$body_hash = hash_hmac('sha256', $signed_body, $stripe->getWebhookSecret());
if ($sig_hash != $body_hash) {
Analog::log(
'Stripe signature mismatch!',
Analog::ERROR
);
echo 'Stripe signature mismatch!';
return $response->withStatus(403);
}
}
Analog::log("Stripe webhook request: ".var_export($post, true), Analog::DEBUG);
// Process payload
if (isset($post['type']) &&
($post['type'] == 'payment_intent.succeeded' || $post['type'] == 'invoice.payment_succeeded')) {
//We accept subscription invoice (annual or monthly) ; https://stripe.com/docs/billing/subscriptions/overview
//Todo : rewrite a more cleaner
if ($post['type'] == 'invoice.payment_succeeded') {
$post['data']['object']['metadata'] = array_merge($post['data']['object']['metadata'], $post['data']['object']['lines']['data'][0]['metadata']);
$post['data']['object']['amount_received'] = $post['data']['object']['amount_paid'];
$post['data']['object']['amount'] = $post['data']['object']['amount_due'];
$post['data']['object']['description'] = $post['data']['object']['lines']['data'][0]['metadata']['item_name'];
if ($post['data']['object']['status'] == 'paid') {
$post['data']['object']['status'] = 'succeeded';
}
}
$ph = new StripeHistory($this->zdb, $this->login, $this->preferences);
$ph->add($post);
// are we working on a real contribution?
$real_contrib = false;
if (
isset($post['data']['object']['metadata']['adherent_id'])
&& is_numeric($post['data']['object']['metadata']['adherent_id'])
&& $post['data']['object']['status'] == 'succeeded'
&& $post['data']['object']['amount_received'] == $post['data']['object']['amount']
) {
$real_contrib = true;
}
if ($ph->isProcessed($post)) {
Analog::log(
'A stripe payment notification has been received, but it is already processed!',
Analog::WARNING
);
$ph->setState(StripeHistory::STATE_ALREADYDONE);
echo 'A stripe payment notification has been received, but it is already processed!';
return $response->withStatus(200);
}
// we'll now try to add the relevant cotisation
if ($post['data']['object']['status'] == 'succeeded') {
/**
* We will use the following parameters:
* - $post['data']['object']['amount']: the amount
* - $post['data']['object']['metadata']['adherent_id']: member id
* - $post['data']['object']['metadata']['contrib_id']: contribution type id
*
* If no member id is provided, we only send to post contribution
* script, Galette does not handle anonymous contributions
*/
$contrib_args = [
'type' => $post['data']['object']['metadata']['contrib_id'],
'adh' => $post['data']['object']['metadata']['adherent_id'],
'payment_type' => PaymentType::CREDITCARD
];
$check_contrib_args = [
ContributionsTypes::PK => $post['data']['object']['metadata']['contrib_id'],
Adherent::PK => $post['data']['object']['metadata']['adherent_id'],
'type_paiement_cotis' => PaymentType::CREDITCARD,
'montant_cotis' => $post['data']['object']['amount'] / 100, // Stripe handles cents
];
if ($this->preferences->pref_membership_ext != '') {
$contrib_args['ext'] = $this->preferences->pref_membership_ext;
}
$contrib = new Contribution($this->zdb, $this->login, $contrib_args);
// all goes well, we can proceed
if ($real_contrib) {
// Check contribution to set $contrib->errors to [] and handle contribution overlap
$valid = $contrib->check($check_contrib_args, [], []);
if ($valid !== true) {
Analog::log(
'An error occurred while storing a new contribution from Stripe payment:' .
implode("\n ", $valid),
Analog::ERROR
);
$ph->setState(StripeHistory::STATE_ERROR);
echo 'An error occurred while storing a new contribution from Stripe payment';
return $response->withStatus(500);
}
$store = $contrib->store();
if ($store === true) {
// contribution has been stored :)
Analog::log(
'Stripe payment has been successfully registered as a contribution',
Analog::INFO
);
echo 'Stripe payment has been successfully registered as a contribution';
$ph->setState(StripeHistory::STATE_PROCESSED);
return $response->withStatus(200);
} else {
// something went wrong :'(
Analog::log(
'An error occured while storing a new contribution from Stripe payment',
Analog::ERROR
);
echo 'An error occured while storing a new contribution from Stripe payment';
$ph->setState(StripeHistory::STATE_ERROR);
return $response->withStatus(500);
}
}
} else {
Analog::log(
'A stripe payment notification has been received, but the Adherent ID is not found!',
Analog::WARNING
);
echo 'A stripe payment notification has been received, but the Adherent ID is not found!';
$ph->setState(StripeHistory::STATE_ERROR);
return $response->withStatus(403);
}
} else {
Analog::log(
'Stripe notify URL call without required arguments!',
Analog::ERROR
);
echo 'Stripe notify URL call without required arguments!';
return $response->withStatus(403);
}
}
)->setName('stripe_webhook');
$this->get(
'/logs[/{option:|order|reset|page}/{value}]',
function ($request, $response, $args) use ($module, $module_id) {
$stripe_history = new StripeHistory($this->zdb, $this->login, $this->preferences);
$filters = [];
if (isset($this->session->filter_stripe_history)) {
$filters = $this->session->filter_stripe_history;
} else {
$filters = new HistoryList();
}
$option = null;
if (isset($args['option'])) {
$option = $args['option'];
}
$value = null;
if (isset($args['value'])) {
$value = $args['value'];
}
if ($option !== null) {
switch ($option) {
case 'page':
$filters->current_page = (int)$value;
break;
case 'order':
$filters->orderby = $value;
break;
case 'reset':
$filters = new HistoryList();
break;
}
}
$this->session->filter_stripe_history = $filters;
//assign pagination variables to the template and add pagination links
$stripe_history->setFilters($filters);
$logs = $stripe_history->getStripeHistory();
$filters->setSmartyPagination($this->router, $this->view->getSmarty());
$params = [
'page_title' => _T("Stripe History"),
'stripe_history' => $stripe_history,
'logs' => $logs,
'module_id' => $module_id
];
$this->session->filter_stripe_history = $filters;
// display page
$this->view->render(
$response,
'file:[' . $module['route'] . ']stripe_history.tpl',
$params
);
return $response;
}
)->setName('stripe_history')->add($authenticate);
//history filtering
$this->post(
'/history/filter',
function ($request, $response) {
$post = $request->getParsedBody();
//reset history
$filters = [];
if (isset($post['reset'])) {
} else {
//number of rows to show
if (isset($post['nbshow'])) {
$filters['show'] = $post['nbshow'];
}
}
$this->session->filter_stripe_history = $filters;
return $response
->withStatus(301)
->withHeader('Location', $this->router->pathFor('stripe_history'));
}
)->setName('filter_stripe_history')->add($authenticate);