-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathding_debt_easy.module
More file actions
1038 lines (929 loc) · 31.8 KB
/
ding_debt_easy.module
File metadata and controls
1038 lines (929 loc) · 31.8 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
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Integration with Nets Easy payment.
*/
use Nets\Easy\Client;
use Nets\Easy\Exception\PaymentCommunicationException;
use Nets\Easy\Exception\PaymentException;
define('DING_DEBT_EASY_DEFAULT_TERMS_URL', 'payment/easy/terms');
define('DING_DEBT_EASY_DEFAULT_PRIVACY_URL', 'payment/easy/privacy');
define('DING_DEBT_EASY_CALLBACK_URL', 'payment/easy/callback');
define('DING_DEBT_EASY_WEBHOOK', 'payment/easy/webhook');
define('DING_DEBT_EASY_CANCEL_URL', 'payment/easy/cancel');
// Looking forward to PHP 8.1's enums.
define('DING_DEBT_EASY_STATUS_CREATED', 'created');
define('DING_DEBT_EASY_STATUS_RESERVED', 'reserved');
define('DING_DEBT_EASY_STATUS_PENDING', 'pending');
define('DING_DEBT_EASY_STATUS_COMPLETED', 'completed');
define('DING_DEBT_EASY_STATUS_FAILED', 'failed');
define('DING_DEBT_EASY_STATUS_CANCELED', 'canceled');
define('DING_DEBT_EASY_MAX_RETRIES', 6);
/**
* Implements hook_menu().
*/
function ding_debt_easy_menu() {
$items = [];
$items['admin/config/payment/ding_debt_easy'] = array(
'title' => 'Nets Easy payment settings',
'description' => 'Configure Nets Easy payment gateway.',
'page callback' => 'drupal_get_form',
'page arguments' => ['ding_debt_easy_admin_settings_form'],
'access arguments' => ['administer easy settings'],
'type' => MENU_NORMAL_ITEM,
'file' => 'includes/ding_debt_easy.admin.inc',
);
$items['admin/config/payment/ding_debt_easy/settings'] = array(
'title' => 'Settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'file' => 'includes/ding_debt_easy.admin.inc',
);
$items[DING_DEBT_EASY_DEFAULT_TERMS_URL] = [
'title' => 'Terms declaration',
'type' => MENU_CALLBACK,
'page callback' => 'ding_debt_easy_terms_page',
'access arguments' => array('perform payment'),
'file' => 'includes/ding_debt_easy.pages.inc',
];
$items[DING_DEBT_EASY_DEFAULT_PRIVACY_URL] = [
'title' => 'Privacy declaration',
'type' => MENU_CALLBACK,
'page callback' => 'ding_debt_easy_privacy_page',
'access arguments' => array('perform payment'),
'file' => 'includes/ding_debt_easy.pages.inc',
];
// Payment completed (callback).
$items[DING_DEBT_EASY_CALLBACK_URL] = [
'title' => 'Payment reserved callback',
'type' => MENU_CALLBACK,
'page callback' => '_ding_debt_easy_callback',
'access arguments' => array('perform payment'),
];
// Payment canceled.
$items[DING_DEBT_EASY_CANCEL_URL] = [
'title' => 'Payment canceled callback',
'type' => MENU_CALLBACK,
'page callback' => '_ding_debt_easy_canceled',
'access arguments' => array('perform payment'),
];
// Payment webhook (callback).
$items[DING_DEBT_EASY_WEBHOOK] = [
'title' => 'Payment webhook callback',
'type' => MENU_CALLBACK,
'page callback' => '_ding_debt_easy_webhook',
// Allow all to make the callback regardless of permissions. This ensures
// that nets always can call this callback.
'access callback' => TRUE,
];
return $items;
}
/**
* Implements hook_permission().
*/
function ding_debt_easy_permission() {
return array(
'administer easy settings' => array(
'title' => t('Administer ding dept easy module'),
'description' => t('Change Nets Easy integration settings.'),
),
'administer easy reports' => array(
'title' => t('Administer payment reports'),
'description' => t('Administer easy payment reports'),
),
'perform payment' => array(
'title' => t('Perform payment'),
'description' => t('Perform payment of debts'),
),
);
}
/**
* Implements hook_theme().
*/
function ding_debt_easy_theme($existing, $type, $theme, $path) {
return [
'ding_debt_easy_terms' => [
'variables' => [
'terms' => NULL,
'url' => NULL,
],
'template' => 'ding_debt_easy_terms',
'path' => $path . '/templates',
],
'ding_debt_easy_cards_supported' => [
'variables' => [
'cards' => NULL,
],
'template' => 'ding_debt_easy_cards_supported',
'path' => $path . '/templates',
],
];
}
/**
* Implements hook_ding_provider().
*/
function ding_debt_easy_ding_provider() {
return [
'title' => 'Net easy payment provider',
'provides' => [
'payment' => [
'prefix' => 'payment',
'file' => drupal_get_path('module', 'ding_debt_easy') . '/includes/easy.payment.inc',
],
],
];
}
/**
* Implements hook_cron().
*/
function ding_debt_easy_cron() {
_ding_debt_easy_wipe();
_ding_debt_easy_retry_payments();
}
/**
* Wipe old local payment records base on configuration.
*/
function _ding_debt_easy_wipe() {
$interval = _ding_debt_easy_get_wipe_interval();
// Zero here is wipe out is disabled in configuration.
if (0 < $interval) {
$limit = DateTimeImmutable::createFromFormat('U', REQUEST_TIME - $interval);
$limit = $limit->setTimezone(new DateTimeZone(drupal_get_user_timezone()));
$num_deleted = db_delete('ding_debt_easy')
->condition('changed', $limit->getTimestamp(), '<')
->execute();
watchdog('ding_debt_easy', '%num_deleted payments was removed from the local database.', [
'%num_deleted' => $num_deleted,
], WATCHDOG_INFO);
}
}
/**
* Retry pending payments.
*/
function _ding_debt_easy_retry_payments() {
$orders = db_select('ding_debt_easy', 'dbe')
->fields('dbe', ['payment_id'])
->condition('status', DING_DEBT_EASY_STATUS_PENDING)
->orderBy('changed', 'DESC')
->condition('retries', DING_DEBT_EASY_MAX_RETRIES, '<=')
->execute()
->fetchAll();
foreach ($orders as $order) {
// Load local order from database this way to ensure thing are decoded
// correctly.
$order = _ding_debt_easy_get_payment_local($order->payment_id);
// Check interval retry (back-off strategy with 6 retries ending 24 hours
// from first try, starting at 5 min - 300, 900, 2700 ... 86400 sec.).
$limit = $order['changed'] + (int) (300 * pow(3, $order['retries']));
if (REQUEST_TIME > $limit) {
// Check order status at the provider.
/** @var \DingProviderDebt[] $fees */
$fees = ding_provider_invoke('debt', 'list', NULL, TRUE, $order['patron_id'], TRUE);
$chargeable = TRUE;
foreach ($order['provider_ids'] as $id) {
if (!isset($fees[$id])) {
// The fee is not found at the provider.
_ding_debt_easy_update_status_local($order['payment_id'], DING_DEBT_EASY_STATUS_FAILED);
_ding_debt_easy_remove_personal_info($order['payment_id']);
$chargeable = FALSE;
break;
}
if (empty($fees[$id]->paid_date)) {
// The fee has not been marked as paid at the provider. So we simply
// try to mark them all once more, as paid. This logic may seam
// strange, but the premise is that it's better to mark a fee as paid
// even if it can not be charged at the gateway. It's less important
// that the library has false marked fees than the citizen have been
// charged for a fee that is not marked.
$status = ding_provider_invoke('debt', 'payment_received', NULL, $order['provider_ids'], $order['order_id'], $order['patron_id']);
if (!$status) {
$chargeable = FALSE;
}
// Jump out of the foreach loop for this order fees. If marking of the
// fee as paid have failed the $chargeable variable will be false and
// the charge will not be completed.
break;
}
}
if ($chargeable) {
// All has been marked as paid, try charge the gateway if not already
// charged.
$client = _ding_debt_easy_get_client();
$data = $client->fetchPayment($order['payment_id']);
if (!isset($data['summary']['chargedAmount'])) {
// Not charged at the gateway, so lets try that.
$client = _ding_debt_easy_get_client();
try {
$charge_id = $client->chargePayment($order['payment_id'], $data['orderDetails']['amount']);
_ding_debt_easy_set_charge_id_local($order['payment_id'], $charge_id);
_ding_debt_easy_update_status_local($order['payment_id'], DING_DEBT_EASY_STATUS_COMPLETED);
_ding_debt_easy_remove_personal_info($order['payment_id']);
}
catch (Exception $exception) {
// Something went wrong, the order will be retried later.
}
}
else {
// Already charged (should not happen, but someone may have charged it
// in the easy portal) maker the order as completed.
_ding_debt_easy_update_status_local($order['payment_id'], DING_DEBT_EASY_STATUS_COMPLETED);
_ding_debt_easy_remove_personal_info($order['payment_id']);
}
}
}
// Update the number of retires, no matter what happened above this was a
// retry. For some reason the retries counter from the database is a string
// when loaded from the database, so we cast it here.
_ding_debt_easy_update_retries_local($order['payment_id'], (int) $order['retries']);
}
}
/**
* The currencies available at the payment gateway.
*
* Sadly there is no endpoint to fetches these. So it's created based on
* https://nets-devs.isotop.se/nets-easy/en-EU/api/#currency-and-amount.
*
* @return string[]
* Array indexed by short name for currencies (as defined in ISO-4217).
*/
function _ding_debt_easy_get_currency_options() {
return [
'DKK' => t('Danish krone'),
'EUR' => t('Euro'),
'GBP' => t('Pound sterling'),
'NOK' => t('Norwegian krone'),
'SEK' => t('Swedish krona'),
'USD' => t('United States dollar'),
];
}
/**
* Get current configured currency (default: DKK).
*
* @return string
* The short name for the currently configured currency.
*/
function ding_debt_easy_get_currency() {
$config = variable_get('ding_debt_easy_config', []);
return empty($config['currency']) ? 'DKK' : $config['currency'];
}
/**
* The list of language select at the gateway.
*
* See https://nets-devs.isotop.se/nets-easy/en-EU/api/#localization.
*
* @return string[]
* List of languages keys by localization id/code.
*/
function _ding_debt_easy_get_localization_options() {
return [
'da-DK' => t('Danish'),
'en-GB' => t('English'),
'nl-NL' => t('Dutch'),
'fi-FI' => t('Finnish'),
'fr-FR' => t('French'),
'de-DE' => t('German'),
'nb-NO' => t('Norwegian'),
'pl-PL' => t('Polish'),
'es-ES' => t('Spanish'),
'sk-SK' => t('Slovak'),
'sv-SE' => t('Swedish'),
];
}
/**
* Return the selected wipe interval in seconds.
*
* Default: 30 days.
*
* @return int
* The select wipe interval.
*/
function _ding_debt_easy_get_wipe_interval() {
$config = variable_get('ding_debt_easy_config', []);
return empty($config['wipe_interval']) ? 86400 * 30 : $config['wipe_interval'];
}
/**
* Get current localization id/code.
*
* @return string
* Current selected localization land id/code.
*/
function ding_debt_easy_get_localization() {
$config = variable_get('ding_debt_easy_config', []);
return empty($config['lang']) ? 'da-DK' : $config['lang'];
}
/**
* Get list of integration types.
*
* Currently, the embedded type is not implemented, but it's very possible to do so.
*
* @return string[]
* List of integration types.
*/
function _ding_debt_easy_get_integration_type_options() {
return [
'HostedPaymentPage' => 'Hosted Payment Page',
// 'EmbeddedCheckout' => 'Embedded Checkout (not implemented)',
];
}
/**
* Get payment gateway integration type.
*
* @return string
* The type of integration to use.
*/
function ding_debt_easy_get_integration_type() {
$config = variable_get('ding_debt_easy_config', []);
return empty($config['integration_type']) ? 'HostedPaymentPage' : $config['integration_type'];
}
/**
* Get terms page url.
*
* @return string
* URL to terms page.
*/
function ding_debt_easy_get_term_url() {
$config = variable_get('ding_debt_easy_terms', []);
return empty($config['url']) ? '/' . DING_DEBT_EASY_DEFAULT_TERMS_URL : $config['url'];
}
/**
* Get privacy URL.
*
* @return string
* URL to privacy page.
*/
function ding_debt_easy_get_privacy_url() {
$config = variable_get('ding_debt_easy_privacy', []);
return empty($config['url']) ? '/' . DING_DEBT_EASY_DEFAULT_PRIVACY_URL : $config['url'];
}
/**
* Get return URL after payment at the gateway.
*
* @return string
* The URL.
*/
function ding_debt_easy_get_return_url() {
$config = variable_get('ding_debt_easy_endpoints', []);
return empty($config['callback']) ? DING_DEBT_EASY_CALLBACK_URL : $config['callback'];
}
/**
* Get cancel URL after cancellation of payment at the gateway.
*
* @return string
* The URL.
*/
function ding_debt_easy_get_cancel_url() {
$config = variable_get('ding_debt_easy_endpoints', []);
return empty($config['cancel']) ? DING_DEBT_EASY_CANCEL_URL : $config['cancel'];
}
/**
* Get list of the configured payments types.
*
* @param bool $with_logos
* If TRUE the array is enriched with paths to logos.
*
* @return array
* Keyed by payment method.
*/
function ding_debt_easy_get_payment_types($with_logos = TRUE) {
$cards = [];
$config = variable_get('ding_debt_easy_config', []);
if (!empty($config['cards'])) {
$cards = array_filter($config['cards']);
if ($with_logos) {
// Update options with links to the logos.
$supported_cards = _ding_debt_easy_get_payment_types_options();
foreach ($cards as $card) {
$cards[$card] = $supported_cards[$card];
}
}
}
return $cards;
}
/**
* Get basic API configuration.
*
* @return array
* The API endpoint to use and the keys needed to communication with the
* endpoint.
*/
function ding_debt_easy_get_api_config() {
$endpoints = variable_get('ding_debt_easy_api_endpoints', [
// Default to testing endpoint.
'testing' => TRUE,
'prod' => 'https://api.dibspayment.eu/',
'test' => 'https://test.api.dibspayment.eu/',
]);
return [
'endpoint' => !empty($endpoints['testing']) ? $endpoints['test'] : $endpoints['prod'],
] + variable_get('ding_debt_easy_keys', []);
}
/**
* Get list of card supports by Net easy.
*
* Note: the invoice methods has been removed as the libraries don't support
* these payments methods. For the full list see
* https://nets-devs.isotop.se/nets-easy/en-EU/api/#payment-methods
*
* @return string[]
* List of supported cards as keys linked to logos.
*/
function _ding_debt_easy_get_payment_types_options() {
$cards = [
'Dankort' => 'dankort.png',
'MasterCard' => 'mastercard.png',
'MobilePay' => 'mobilpay.png',
'PayPal' => 'paypal.png',
'Swish' => 'swish.png' ,
'Vipps' => 'vipps.png',
'Visa' => 'visa.png',
];
$path = '/' . drupal_get_path('module', 'ding_debt_easy') . '/img/';
array_walk($cards, function (&$value, $key) use ($path) {
$value = $path . $value;
});
return $cards;
}
/**
* Callback/return point for payments reserved at the payment gateway.
*
* Will redirect back to the user's debt page.
*
* @throws \DingProviderDoesntImplement
* @throws \DingProviderNoProvider
* @throws \GuzzleHttp\Exception\GuzzleException
*/
function _ding_debt_easy_callback() {
global $user;
$params = drupal_get_query_parameters();
if (empty($params['paymentid'])) {
watchdog('ding_debt_easy', 'The payment callback has been called without a payment id.', [], WATCHDOG_ERROR);
drupal_set_message(t('Something unexpected happened with processing the payment. Please try again or contact the library.'));
drupal_goto(DING_DEBT_USER_DEBT_PAGE);
}
$payment_id = $params['paymentid'];
// Clear the users cache before redirecting to ensure the payment overview is
// updated with data from the provider and not the cache.
ding_provider_invoke('user', 'clear_cache', $user);
// Fetch order details form the database.
$local_record = _ding_debt_easy_get_payment_local($payment_id);
// Fetch order details form the database.
if (_ding_debt_easy_validate_payment($payment_id, $local_record)) {
$client = _ding_debt_easy_get_client();
$data = $client->fetchPayment($payment_id);
$amount = $data['orderDetails']['amount'];
_ding_debt_easy_process_payment($payment_id, $local_record, $amount);
}
// Inform user. As the payment status is handle in async web-hooks we may get
// here before the payment have been processed. So we only have to different
// message we can set.
if (DING_DEBT_EASY_STATUS_COMPLETED === $local_record['status']) {
$msg = t('Your payment of @amount was received. Transaction ID: @transaction, order no.: @order.', [
'@amount' => $local_record['amount'] / 100,
'@transaction' => $payment_id,
'@order' => $local_record['order_id'],
]);
}
else {
$msg = t('Your payment of @amount is begin processed. Transaction ID: @transaction, order no.: @order.', [
'@amount' => $local_record['amount'] / 100,
'@transaction' => $payment_id,
'@order' => $local_record['order_id'],
]);
}
drupal_set_message($msg);
drupal_goto(DING_DEBT_USER_DEBT_PAGE);
}
/**
* Web-hook callback handling.
*
* This function is a callback used by Nets-easy web-hooks and should always
* return http status code 200. If any other status is returned nets will keep
* re-calling the site with different intervals.
*
* @see https://developers.nets.eu/nets-easy/en-EU/api/webhooks/
*/
function _ding_debt_easy_webhook() {
// This callback should never be cached.
drupal_page_is_cacheable(FALSE);
// When content-type is JSON the data is not placed in _POST variable, so we
// have to parse the payload by hand.
$data = json_decode(file_get_contents("php://input"), true);
$payment_id = $data['data']['paymentId'];
$local_record = _ding_debt_easy_get_payment_local($payment_id);
// Validate HTTP_AUTHORIZATION header to ensure call comes from nets.
$token = $_SERVER['HTTP_AUTHORIZATION'];
if ($local_record['auth'] !== $token) {
watchdog('ding_debt_easy', 'Web-hook callback with wrong authorization header. Payment id: %id', ['%id' => $payment_id], 'WATCHDOG_WARNING');
return;
}
// The payment gateway web-hooks seen calling back two or more times with the
// same order sometimes, so to protect against this we have this extra check.
if (DING_DEBT_EASY_STATUS_COMPLETED === $local_record['status']) {
watchdog('ding_debt_easy', 'Web-hook callback all ready completed. Payment id: %id', ['%id' => $payment_id], 'WATCHDOG_WARNING');
return;
}
switch ($data['event']) {
case 'payment.checkout.completed':
// Get data needed from the payload.
$amount = $data['data']['order']['amount']['amount'];
// Fetch order details form the database.
if (_ding_debt_easy_validate_payment($payment_id, $local_record)) {
_ding_debt_easy_process_payment($payment_id, $local_record, $amount);
}
break;
case 'payment.cancel.created':
_ding_debt_easy_update_status_local($payment_id, DING_DEBT_EASY_STATUS_CANCELED);
break;
case 'payment.reservation.created.v2':
_ding_debt_easy_update_status_local($payment_id, DING_DEBT_EASY_STATUS_RESERVED);
break;
default:
// Ignore all other callbacks.
break;
}
}
/**
* Canceled payment at the gateway.
*
* The payment status is updated in the web-hooks callback. So here simply
* inform the user about the cancellation.
*/
function _ding_debt_easy_canceled() {
drupal_set_message(t('The payment have been canceled'));
drupal_goto(DING_DEBT_USER_DEBT_PAGE);
}
/**
* Validate payment status.
*
* @param string $payment_id
* The payment id at the payment gateway.
* @param array $local_record
* Local record for the payment.
*
* @return bool
* If the payment is ready for processing TRUE else FALSE.
*/
function _ding_debt_easy_validate_payment($payment_id, array $local_record) {
// Validate the current status for the local record to prevent payment errors.
$valid_status = [
DING_DEBT_EASY_STATUS_RESERVED,
DING_DEBT_EASY_STATUS_PENDING,
DING_DEBT_EASY_STATUS_CREATED,
];
if (!in_array($local_record['status'], $valid_status)) {
watchdog('ding_debt_easy', 'Unable process payment for the order (%order_id). The order have state: %state', [
'%order_id' => $local_record['order_id'],
'%state' => $local_record['status'],
], WATCHDOG_INFO);
_ding_debt_easy_update_status_local($local_record['order_id'], DING_DEBT_EASY_STATUS_FAILED);
_ding_debt_easy_remove_personal_info($payment_id);
return FALSE;
}
return TRUE;
}
/**
* Process the payment at the provider and update the local record.
*
* @param string $payment_id
* The payment id at the payment gateway.
* @param array $local_record
* Local record for the payment.
* @param int $amount
* The amount to process.
*
* @throws \DingProviderDoesntImplement
* @throws \DingProviderNoProvider
* @throws \GuzzleHttp\Exception\GuzzleException
*/
function _ding_debt_easy_process_payment($payment_id, array $local_record, $amount) {
$client = _ding_debt_easy_get_client();
// Mark the order as paid at the provider, which only return true/false. It's
// the most we can do in regard to what went wrong. Also we don't send any
// user into this as this is handled in a web-hook.
$status = ding_provider_invoke('debt', 'payment_received', NULL, $local_record['provider_ids'], $local_record['order_id'], $local_record['patron_id']);
if ($status) {
// Charged the payment gateway.
try {
$charge_id = $client->chargePayment($payment_id, $amount);
_ding_debt_easy_set_charge_id_local($payment_id, $charge_id);
_ding_debt_easy_update_status_local($payment_id, DING_DEBT_EASY_STATUS_COMPLETED);
_ding_debt_easy_remove_personal_info($payment_id);
}
catch (PaymentCommunicationException $exception) {
watchdog_exception('ding_debt_easy', $exception, 'There is a communication problem with the gateway (Order ID: %order_id)', [
'%order_id' => $local_record['order_id'],
]);
// As the amount has not been charged. The local order will be set to pending for retry via cron.
_ding_debt_easy_update_status_local($local_record['order_id'], DING_DEBT_EASY_STATUS_PENDING);
}
catch (PaymentException $exception) {
watchdog_exception('ding_debt_easy', $exception, 'There is a communication problem with the gateway (Order ID: %order_id)', [
'%order_id' => $local_record['order_id'],
]);
// As the amount has not been charged. The local order will be set to
// pending for retry via cron.
_ding_debt_easy_update_status_local($local_record['order_id'], DING_DEBT_EASY_STATUS_PENDING);
}
}
else {
// Check order status at the provider.
/** @var \DingProviderDebt[] $fees */
$fees = ding_provider_invoke('debt', 'list', NULL, TRUE, $local_record['patron_id'], TRUE);
foreach ($local_record['provider_ids'] as $id) {
// Check if the order contains one or more ids marked as payed at the
// provider. (This can happen if a user is presented with a stale list
// of debts and the user tries to pay the same id once more. Stale list
// can arise when user prematurely closes the browser window before
// _ding_debt_easy_callback() has been run.
$payed = FALSE;
if (isset($fees[$id]) && $fees[$id]->paid_date) {
$payed = TRUE;
break;
}
}
if ($payed) {
watchdog('ding_debt_easy', 'The order contains one or more ids already payed for. (Order ID: %order_id)', [
'%order_id' => $local_record['order_id'],
]);
_ding_debt_easy_update_status_local($local_record['order_id'], DING_DEBT_EASY_STATUS_FAILED);
}
else {
watchdog('ding_debt_easy', 'There is a communication problem with the provider (Order ID: %order_id)', [
'%order_id' => $local_record['order_id'],
]);
// As the amount has not been marked as paid at the provider. The local
// order will be set to pending for retry via cron.
_ding_debt_easy_update_status_local($local_record['order_id'], DING_DEBT_EASY_STATUS_PENDING);
}
}
}
/**
* Get local database payment record.
*
* @param string $id
* The payment id at the gateway or the local order id.
*
* @return array|bool
* The local payment database record. If record in not found FALSE will be
* returned.
*/
function _ding_debt_easy_get_payment_local($id) {
$query = db_select('ding_debt_easy', 'e')
->fields('e');
// We know that all internal order ids are prefixed with NE.
if (substr($id, 0, 2) === 'NE') {
$query->condition('order_id', $id, '=');
}
else {
$query->condition('payment_id', $id, '=');
}
$data = $query->execute()
->fetchAssoc();
if (is_array($data)) {
// Decode provider id(s).
$data['provider_ids'] = explode(';', $data['provider_ids']);
}
return $data;
}
/**
* Get internal order id.
*
* Creates internal database record and based on that the unique order id.
*
* @param mixed $patron_id
* The user id at the provider. Use later for pending payment retries.
* @param string[] $provider_ids
* The order id's from the provider.
* @param int $amount
* The order amount.
*
* @return false|string
* The order id or false on database error.
*/
function _ding_debt_easy_create_order_local($patron_id, $provider_ids, $amount) {
// Create database record to get row id and reserve the ID in the database.
try {
$id = db_insert('ding_debt_easy')
->fields([
'patron_id' => $patron_id,
'provider_ids' => implode(';', $provider_ids),
'status' => DING_DEBT_EASY_STATUS_CREATED,
'amount' => $amount,
'changed' => REQUEST_TIME,
'auth' => md5(bin2hex(random_bytes(32))),
])
->execute();
} catch (Exception $e) {
return FALSE;
}
// Generate the order id (based on the row id) and update record with the new
// order id.
$order_id = _ding_debt_easy_generate_order_id($id);
db_update('ding_debt_easy')
->fields([
'order_id' => $order_id,
])
->condition('id', $id, '=')
->execute();
return $order_id;
}
/**
* Update local payment record with payment id.
*
* @param string $order_id
* The internal CMS order id (the order to add payment id to).
* @param string $payment_id
* The gateway payment id.
*
* @return array|bool
* The local payment database record.
*/
function _ding_debt_easy_add_payment_id_local($order_id, $payment_id) {
$res = db_update('ding_debt_easy')
->fields([
'payment_id' => $payment_id,
'changed' => REQUEST_TIME,
])
->condition('order_id', $order_id, '=')
->execute();
return $res > 0 ? _ding_debt_easy_get_payment_local($payment_id) : FALSE;
}
/**
* Update local order record based on retries.
*
* @param string $payment_id
* The payment id of the order.
* @param int $current
* The current number of retires.
*/
function _ding_debt_easy_update_retries_local($payment_id, $current) {
if ($current === DING_DEBT_EASY_MAX_RETRIES) {
_ding_debt_easy_update_status_local($payment_id, DING_DEBT_EASY_STATUS_FAILED);
_ding_debt_easy_remove_personal_info($payment_id);
}
else {
$current++;
// Update retires count.
db_update('ding_debt_easy')
->fields([
'retries' => $current,
])
->condition('payment_id', $payment_id, '=')
->execute();
}
}
/**
* Generate order id with the format NEXX-XXXX-XXX.
*
* We need a local order id to send to Nets and to use in reports and display to
* end user. It should be human-readable and easy to use.
*
* It's built based on the local record id prefixed with NE (Nets Easy) and the
* current year. Dash is added to every 4 char in the number to make it more
* readable and memorable. The NE prefix is also added to make it stand out from
* FBS order ids that exists for every order item.
*
* @param int $row_id
* The database record id to ensure uniqueness for the id.
*
* @return string
* The generated order id.
*/
function _ding_debt_easy_generate_order_id($row_id) {
// Generate order ID based on record id (NEXX-XXXX-XXX).
$prefix = 'NE' . date('y');
$offset = 1000000;
$order_id = $prefix . '-' . chunk_split($offset + $row_id, 4, '-');
return substr($order_id, 0, -1);
}
/**
* Update local database payment status.
*
* @param string $id
* The payment id at the gateway or the local order id.
* @param string $status
* The current status of the payment. Note constants exists, which should be
* used as status variable.
*
* @return array|bool
* The updated local order record or FALSE on failure.
*/
function _ding_debt_easy_update_status_local($id, $status) {
$query = db_update('ding_debt_easy')
->fields([
'status' => $status,
'changed' => REQUEST_TIME,
]);
// We know that all internal order ids are prefixed with NE.
if (substr($id, 0, 2) === 'NE') {
$query->condition('order_id', $id, '=');
}
else {
$query->condition('payment_id', $id, '=');
}
$res = $query->execute();
return $res > 0 ? _ding_debt_easy_get_payment_local($id) : FALSE;
}
/**
* Add charge id to local status record.
*
* @param string $payment_id
* The payment id at the gateway.
* @param string $charge_id
* The charge id at the gateway.
*
* @return array|bool
* The updated local order record or FALSE on failure.
*/
function _ding_debt_easy_set_charge_id_local($payment_id, $charge_id) {
$res = db_update('ding_debt_easy')
->fields([
'charge_id' => $charge_id,
'changed' => REQUEST_TIME,
])
->condition('payment_id', $payment_id, '=')
->execute();
return $res > 0 ? _ding_debt_easy_get_payment_local($payment_id) : FALSE;
}
/**
* Remove personal information from the local database.
*
* @param string $id
* The payment id or order id.
*/
function _ding_debt_easy_remove_personal_info($id) {
$query = db_update('ding_debt_easy')
->fields([
'patron_id' => 0,
'changed' => REQUEST_TIME,
]);
// We know that all internal order ids are prefixed with NE.
if (substr($id, 0, 2) === 'NE') {
$query->condition('order_id', $id, '=');
}
else {
$query->condition('payment_id', $id, '=');
}
$query->execute();
}
/**
* Get client to communicate with Nets Easy gateway.
*
* @return \Nets\Easy\Client
* The client.
*/
function _ding_debt_easy_get_client() {
_ding_debt_easy_load_library();
$config = ding_debt_easy_get_api_config();
$http_client = new \GuzzleHttp\Client();
return new Client($http_client, $config['secret'], $config['checkout'], $config['endpoint']);
}
/**
* Helper to load the client library.
*
* @todo Why do files[] not work, there must be a better way then x-auto-load
* module.
*/
function _ding_debt_easy_load_library() {
$path = drupal_get_path('module', 'ding_debt_easy') . '/lib/Nets/Easy/';
require_once $path . 'Checkout.inc';
require_once $path . 'Client.inc';
require_once $path . 'Order.inc';
require_once $path . 'Notification.inc';
require_once $path . 'OrderItem.inc';