This repository has been archived by the owner on Sep 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathSmartdebit.php
executable file
·1182 lines (1082 loc) · 44.2 KB
/
Smartdebit.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
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
/**
* https://civicrm.org/licensing
*/
/**
* Class CRM_Core_Payment_Smartdebit
*
* Implementation of the Smartdebit payment processor class
*/
use CRM_Smartdebit_ExtensionUtil as E;
class CRM_Core_Payment_Smartdebit extends CRM_Core_Payment {
use CRM_Core_Payment_SmartdebitTrait;
/**
* mode of operation: live or test
*
* @var object
*/
protected $_mode = NULL;
/**
* Constructor
*
* @param string $mode the mode of operation: live or test
* @param $paymentProcessor
*/
public function __construct($mode, &$paymentProcessor)
{
$this->_mode = $mode;
$this->_paymentProcessor = $paymentProcessor;
$this->_processorName = E::ts('Smart Debit Processor');
}
/**
* We can use the smartdebit processor on the backend
* @return bool
*/
public function supportsBackOffice() {
return TRUE;
}
/**
* We can edit smartdebit recurring contributions
* @return bool
*/
public function supportsEditRecurringContribution() {
return TRUE;
}
/**
* We can configure a start date for a smartdebit mandate
* @return bool
*/
public function supportsFutureRecurStartDate() {
return TRUE;
}
/**
* This function checks to see if we have the right config values
*
* @return string the error message if any
*/
public function checkConfig()
{
$error = [];
if (empty($this->_paymentProcessor['user_name'])) {
$error[] = E::ts('The "username" is not set in the Smart Debit Payment Processor settings.');
}
if (empty($this->_paymentProcessor['password'])) {
$error[] = E::ts('The "password" is not set in the Smart Debit Payment Processor settings.');
}
if (!empty($error)) {
return implode('<p>', $error);
}
else {
return NULL;
}
}
/**
* Get Smart Debit User Details
*
* @param null $id
* @param bool $test
* @param bool $isActive
*
* @return array|bool
*/
public static function getProcessorDetails($params = []) {
$params['is_test'] = CRM_Utils_Array::value('is_test', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, TRUE);
$params['id'] = CRM_Utils_Array::value('payment_processor_id', $params, CRM_Utils_Array::value('id', $params, NULL));
$params['domain_id'] = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
if (empty($params['id'])) {
$paymentProcessorTypeId = CRM_Core_PseudoConstant::getKey('CRM_Financial_BAO_PaymentProcessor', 'payment_processor_type_id', 'Smart_Debit');
$params['payment_processor_type_id'] = $paymentProcessorTypeId;
$params['options'] = ['sort' => "id DESC", 'limit' => 1];
}
try {
$paymentProcessorDetails = civicrm_api3('PaymentProcessor', 'getsingle', $params);
}
catch (Exception $e) {
CRM_Core_Session::setStatus(E::ts('Smart Debit API User Details Missing, Please check that the Smart Debit Payment Processor is configured.'), 'Smart Debit', 'error');
return FALSE;
}
$paymentProcessorDetails['user_name'] = self::getUserStatic($paymentProcessorDetails);
$paymentProcessorDetails['password'] = self::getPasswordStatic($paymentProcessorDetails);
$paymentProcessorDetails['signature'] = self::getSignatureStatic($paymentProcessorDetails);
return $paymentProcessorDetails;
}
/**
* @param \CRM_Core_Form $form
*
* @return bool|void
* @throws \HTML_QuickForm_Error
*/
public function buildForm(&$form)
{
if ($form->isSubmitted()) return;
// Set ddi_reference
$defaults = [];
$defaults['ddi_reference'] = CRM_Smartdebit_Base::getDDIReference();
// Set preferred collection day default to the first choice.
$collectionDaysArray = CRM_Smartdebit_DateUtils::getCollectionDaysOptions();
if (count($collectionDaysArray) > 0) {
$defaults['preferred_collection_day'] = CRM_Utils_Array::first(array_keys($collectionDaysArray));
}
$form->setDefaults($defaults);
// Add help and javascript
CRM_Core_Region::instance('billing-block')->add(
['template' => 'CRM/Core/Payment/Smartdebit/Smartdebit.tpl', 'weight' => -1]);
return;
}
/**
* Override custom Payment Instrument validation
* to validate payment details with SmartDebit
* Sets appropriate parameters and calls Smart Debit API to validate a payment (does not setup the payment)
*
* @param array $params
* @param array $errors
*
* @throws \Exception
*/
public function validatePaymentInstrument($params, &$errors) {
CRM_Core_Form::validateMandatoryFields($this->getMandatoryFields(), $params, $errors);
$smartDebitParams = self::preparePostArray($params);
CRM_Smartdebit_Hook::alterVariableDDIParams($params, $smartDebitParams, 'validate');
self::checkSmartDebitParams($smartDebitParams);
$url = CRM_Smartdebit_Api::buildUrl($this->_paymentProcessor, 'api/ddi/variable/validate');
$response = CRM_Smartdebit_Api::requestPost($url, $smartDebitParams, $this->getUser(), $this->getPassword());
$directDebitResponse = [
'data_type' => 'recurring',
'entity_type' => 'contribution_recur',
'first_collection_date' => $smartDebitParams['variable_ddi[start_date]'],
'preferred_collection_day' => $params['preferred_collection_day'],
'ddi_reference' => $params['ddi_reference'],
'response_status' => $response['message'],
];
// On success an array is returned, last success element is an array of attributes
if ((is_array($response['success'])) && isset(end($response['success'])['@attributes'])) {
foreach (end($response['success'])['@attributes'] as $key => $value) {
$directDebitResponse[$key] = $value;
}
}
// Take action based upon the response status
if ($response['success']) {
$directDebitResponse['entity_id'] = isset($params['entity_id']) ? $params['entity_id'] : 0;
self::recordSmartDebitResponse($directDebitResponse);
}
else {
self::formatErrorsForContributionForm($response['error'], $errors, $params);
}
}
/**
* Parse and format error message for display on contribution form
*
* @param $responseErrors
* @param array $errors
* @param array $params Parameters passed to original function
*/
public static function formatErrorsForContributionForm($responseErrors, &$errors, $params) {
if (!is_array($responseErrors)) {
$responseErrors = [$responseErrors];
}
foreach ($responseErrors as $error) {
$shortErr = substr($error, 0, 14);
switch ($shortErr) {
case 'Sort code is i': // Sort code ..
$errors['bank_identification_number'] = CRM_Utils_Array::value('bank_identification_number', $errors) . $error . '. ';
break;
case 'Account number': // Account number ..
$errors['bank_account_number'] = CRM_Utils_Array::value('bank_account_number', $errors) . $error . '. ';
break;
case 'Account name i': // Account name ..
$errors['account_holder'] = CRM_Utils_Array::value('account_holder', $errors) . $error . '. ';
break;
case 'Start date mus': // Start date ..
$errors['preferred_collection_day'] = CRM_Utils_Array::value('preferred_collection_day', $errors) . $error . '. ';
break;
case 'Frequency type': //' must be in list'
Civi::log()->debug('Smartdebit validation error: Frequency type must be in list. collection_frequency='
. CRM_Utils_Array::value('collection_frequency', $params) . '; collection_interval='
. CRM_Utils_Array::value('collection_interval', $params));
$errors['unknown'] = CRM_Utils_Array::value('unknown', $errors) . $error . '. ';
break;
default:
$errors['unknown'] = CRM_Utils_Array::value('unknown', $errors) . $error . '. ';
}
}
if (isset($errors['unknown'])) {
CRM_Core_Session::setStatus($errors['unknown'], 'Payment validation error', 'error');
}
}
/**
* Override CRM_Core_Payment function
*
* @return string
*/
public function getPaymentTypeName() {
return 'direct_debit';
}
/**
* Override CRM_Core_Payment function
*
* @return string
*/
public function getPaymentTypeLabel() {
return 'Direct Debit';
}
/**
* Override CRM_Core_Payment function
*
* @return array
*/
public function getPaymentFormFields() {
return [
'payer_confirmation',
'preferred_collection_day',
'account_holder',
'bank_account_number',
'bank_identification_number',
'ddi_reference',
];
}
/**
* Return an array of all the details about the fields potentially required for payment fields.
*
* Only those determined by getPaymentFormFields will actually be assigned to the form
*
* @return array
* field metadata
*/
public function getPaymentFormFieldsMetadata() {
// Get the collection days options
$collectionDaysArray = CRM_Smartdebit_DateUtils::getCollectionDaysOptions();
return [
'account_holder' => [
'htmlType' => 'text',
'name' => 'account_holder',
'title' => E::ts('Account Holder'),
'cc_field' => TRUE,
'attributes' => [
'size' => 20,
'maxlength' => 18,
'autocomplete' => 'on'
],
'is_required' => TRUE,
'description' => E::ts('Should be no more than 18 characters. Should not include punctuation (e.g. O\'Callaghan should be OCallaghan). First initial and surname is valid. (e.g. D Watson).'),
],
// UK BACS Account number is 8 digits
'bank_account_number' => [
'htmlType' => 'text',
'name' => 'bank_account_number',
'title' => E::ts('Bank Account Number'),
'cc_field' => TRUE,
'attributes' => [
'size' => 20,
'maxlength' => 8,
'autocomplete' => 'off'
],
'is_required' => TRUE,
'description' => E::ts('8 digits (e.g. 12345678).'),
],
// UK BACS sortcode is 6 digits
'bank_identification_number' => [
'htmlType' => 'text',
'name' => 'bank_identification_number',
'title' => E::ts('Sort Code'),
'cc_field' => TRUE,
'attributes' => [
'size' => 20,
'maxlength' => 6,
'autocomplete' => 'off'
],
'is_required' => TRUE,
'description' => E::ts('6 digits (e.g. 01 23 45).'),
],
'preferred_collection_day' => [
'htmlType' => (count($collectionDaysArray) > 1) ? 'select' : 'hidden',
'name' => 'preferred_collection_day',
'title' => E::ts('Preferred Collection Day'),
'cc_field' => TRUE,
'attributes' => $collectionDaysArray, // eg. array('1' => '1st', '8' => '8th', '21' => '21st'),
'is_required' => TRUE
],
'payer_confirmation' => [
'htmlType' => 'checkbox',
'name' => 'payer_confirmation',
'title' => E::ts('Confirm'),
'cc_field' => TRUE,
'attributes' => '',
'is_required' => TRUE,
'description' => E::ts('Please confirm that you are the account holder and the only person required to authorise Direct Debits from this account.'),
],
'ddi_reference' => [
'htmlType' => 'hidden',
'name' => 'ddi_reference',
'title' => 'DDI Reference',
'cc_field' => TRUE,
'attributes' => [
'size' => 20,
'maxlength' => 64,
'autocomplete' => 'off'
],
'is_required' => TRUE,
]
];
}
/**
* Get form metadata for billing address fields.
*
* @param int $billingLocationID
*
* @return array
* Array of metadata for address fields.
*/
public function getBillingAddressFieldsMetadata($billingLocationID = NULL) {
$metadata = parent::getBillingAddressFieldsMetadata($billingLocationID);
if (!$billingLocationID) {
// Note that although the billing id is passed around the forms the idea that it would be anything other than
// the result of the function below doesn't seem to have eventuated.
// So taking this as a param is possibly something to be removed in favour of the standard default.
$billingLocationID = CRM_Core_BAO_LocationType::getBilling();
}
// State/county field is not required.
if (!empty($metadata["billing_state_province_id-{$billingLocationID}"]['is_required'])) {
$metadata["billing_state_province_id-{$billingLocationID}"]['is_required'] = FALSE;
}
return $metadata;
}
/**
* Get an array of the fields that can be edited on the recurring contribution.
*
* @return array
*/
public function getEditableRecurringScheduleFields() {
return [
'amount',
'frequency_interval',
'frequency_unit',
'start_date',
];
}
/**
* @param array $params
* collection_start_date: DateTime
* collection_frequency: Smartdebit formatted collection frequency
* collection_interval: Smartdebit formatted collection interval
* @param boolean $single Whether this is a recurring or one-off payment
*
* @return \DateTime|bool
* @throws \Exception
*/
public static function getCollectionEndDate($params, $single) {
if (!empty($params['installments'])) {
$installments = $params['installments'];
}
else {
$installments = 0;
}
if (!empty($installments)) {
// Need to set an end date after final installment
$plus = [
'years' => 0,
'months' => 0,
'weeks' => 0
];
switch ($params['collection_frequency']) {
case 'Y':
$plus['years'] = $installments * $params['collection_interval'];
break;
case 'Q':
$plusQuarters = $installments * $params['collection_interval'];
$plus['months'] = $plusQuarters * 3;
break;
case 'M':
$plus['months'] = $installments * $params['collection_interval'];
break;
case 'W':
$plus['weeks'] = $installments * $params['collection_interval'];
break;
default:
Civi::log()->debug('Smartdebit getCollectionEndDate: An unknown collection frequency (' . $params['collection_frequency'] . ') was passed!');
}
$intervalSpec= 'P' . $plus['years'] . 'Y' . $plus['months'] . 'M' . $plus['weeks'] . 'W';
}
elseif ($single) {
// Set end date 6 days after start date (min DD freq with Smart Debit is 1 week/7days)
$intervalSpec = 'P6D';
}
else {
return FALSE;
}
$endDate = $params['collection_start_date']->add(new DateInterval($intervalSpec));
return $endDate;
}
/**
* Determine the frequency based on the recurring params if set
* Should check the [frequency_unit] and if set use that
* Smart debit supports frequency intervals of 1-4 for each Y,Q,M,W.
*
* @return array (string Y,Q,M,W,O; int frequencyInterval)
*/
private static function getCollectionFrequency($params) {
// Smart Debit supports Y, Q, M, W parameters
// We return 'O' if the payment is not recurring. You should then supply an end date to smart debit
// to ensure only a single payment is taken.
// Get frequency unit
if (!empty($params['frequency_unit'])) {
$frequencyUnit = $params['frequency_unit'];
}
else {
$frequencyUnit = '';
}
// Get frequency interval
if (!empty($params['frequency_interval'])) {
$frequencyInterval = $params['frequency_interval'];
}
else {
$frequencyInterval = 1;
}
$single = FALSE; // Used as a flag that it's a single payment
switch (strtolower($frequencyUnit)) {
case 'year':
$collectionFrequency = 'Y';
break;
case 'month':
if ($frequencyInterval % 3 != 0) {
// Monthly
if ($frequencyInterval > 4) {
Civi::log()->debug('The maximum monthly collection interval for Smart Debit is 4 months but you specified ' . $frequencyInterval . ' months.
Resetting to 4 months. If you meant to select a quarterly interval make sure the collection interval is a multiple of 3.');
$frequencyInterval = 4;
}
$collectionFrequency = 'M';
} else {
// Quarterly (frequencyInterval is a multiple of 3)
if ($frequencyInterval > 12) {
Civi::log()->debug('The maximum quarterly collection interval for Smart Debit is 4 quarters but you specified ' . $frequencyInterval . ' months. Resetting to 4 quarters');
$frequencyInterval = 12;
}
// Convert frequencyInterval from months to quarters
$frequencyInterval = ($frequencyInterval / 3);
$collectionFrequency = 'Q';
}
break;
case 'week':
// weekly
if ($frequencyInterval > 4) {
Civi::log()->debug('The maximum weekly collection interval for Smart Debit is 4 weeks but you specified ' . $frequencyInterval . ' weeks.
Resetting to 4 weeks.');
$frequencyInterval = 4;
}
$collectionFrequency = 'W';
break;
case 'day':
// Make sure frequencyInterval is a multiple of 7 days (ie 1 week)
if ($frequencyInterval % 7 != 0) {
Civi::log()->debug('The minimum collection interval for Smart Debit is 1 week but you specified ' . $frequencyInterval . ' days. Resetting to 1 week');
$frequencyInterval = 7;
}
if ($frequencyInterval > 28) {
Civi::log()->debug('The maximum weekly collection interval for Smart Debit is 4 weeks but you specified ' . $frequencyInterval . ' days. Resetting to 4 weeks');
$frequencyInterval = 28;
}
// Convert frequencyInterval from days to weeks
$frequencyInterval = ($frequencyInterval / 7);
$collectionFrequency = 'W';
break;
default:
$collectionFrequency = 'Y';
$single = TRUE; // Used as a flag that it's a single payment
}
return [$collectionFrequency, $frequencyInterval, $single];
}
/**
* @param array $params
*
* @return array
* @throws \Exception
*/
private static function getCollectionFrequencyPostParams($params) {
$collectionDate = CRM_Smartdebit_DateUtils::getNextAvailableCollectionDate($params['preferred_collection_day'], TRUE);
$smartDebitParams['variable_ddi[start_date]'] = $collectionDate->format('Y-m-d');
list($collectionFrequency, $collectionInterval, $single) = self::getCollectionFrequency($params);
$params['collection_start_date'] = $collectionDate;
$params['collection_frequency'] = $collectionFrequency;
$params['collection_interval'] = $collectionInterval;
$endDate = self::getCollectionEndDate($params, $single);
if (!empty($endDate)) {
$smartDebitParams['variable_ddi[end_date]'] = $endDate->format("Y-m-d");
}
$smartDebitParams['variable_ddi[frequency_type]'] = $collectionFrequency;
if (!empty($collectionFrequency)) {
$smartDebitParams['variable_ddi[frequency_factor]'] = $collectionInterval;
}
return $smartDebitParams;
}
/**
* Get the currency for the transaction.
* ( Added to core in 4.7.31 )
*
* @param $params
*
* @return string
*/
public function getAmount($params) {
return self::formatAmount($params);
}
/**
* Get the Signature (PSLID)
*
* @return string
*/
public function getSignature() {
return self::getSignatureStatic($this->_paymentProcessor);
}
/**
* Get the Signature (PSLID)
*
* @param array $paymentProcessorParams
*
* @return string
*/
public static function getSignatureStatic($paymentProcessorParams) {
return trim(CRM_Utils_Array::value('signature', $paymentProcessorParams));
}
/**
* Get the Username
*
* @return string
*/
public function getUser() {
return self::getUserStatic($this->_paymentProcessor);
}
/**
* Get the Username
*
* @param array $paymentProcessorParams
*
* @return string
*/
public static function getUserStatic($paymentProcessorParams) {
return trim(CRM_Utils_Array::value('user_name', $paymentProcessorParams));
}
/**
* Get the Password
*
* @return string
*/
public function getPassword() {
return self::getPasswordStatic($this->_paymentProcessor);
}
/**
* Get the Password
*
* @param array $paymentProcessorParams
*
* @return string
*/
public static function getPasswordStatic($paymentProcessorParams) {
return trim(CRM_Utils_Array::value('password', $paymentProcessorParams));
}
/**
* Get the currency for the transaction formatted for smartdebit
* Smartdebit requires that the amount is sent in "pence" eg. £12.37 would be 1237.
*
* @param $params
*
* @return int|string
*/
public static function formatAmount($params) {
if (empty($params['amount'])) {
return 0;
}
else {
$amount = CRM_Utils_Money::format($params['amount'], NULL, NULL, TRUE);
return (int) preg_replace('/[^\d]/', '', strval($amount));
}
}
private static function checkSmartDebitParams(&$smartDebitParams) {
foreach ($smartDebitParams as $key => &$value) {
switch ($key) {
case 'variable_ddi[address_1]':
case 'variable_ddi[town]':
$value = str_replace(',', ' ', $value);
break;
case 'variable_ddi[first_amount]':
case 'variable_ddi[default_amount]':
$value = self::formatAmount(['amount' => $value]);
break;
}
}
}
/**
* Prepare Post Array for POSTing to Smart Debit APi
*
* @param array $params
*
* @return array
* @throws \Exception
*/
private function preparePostArray($params) {
// When passed in from backend forms via AJAX (ie. select from multiple payprocs
// $params is not fully set for doDirectPayment, but $_REQUEST has the missing info
foreach ($_REQUEST as $key => $value) {
if (!isset($params[$key])) {
$params[$key] = CRM_Utils_Array::value($key, $_REQUEST);
}
}
$contactId = $this->getContactId($params);
$billingLocationID = CRM_Core_BAO_LocationType::getBilling();
// Construct params list to send to Smart Debit ...
$smartDebitParams = [
'variable_ddi[service_user][pslid]' => $this->getSignature(),
'variable_ddi[reference_number]' => CRM_Utils_Array::value('ddi_reference', $params),
'variable_ddi[payer_reference]' => $contactId,
'variable_ddi[first_name]' => CRM_Utils_Array::value('billing_first_name', $params),
'variable_ddi[last_name]' => CRM_Utils_Array::value('billing_last_name', $params),
'variable_ddi[address_1]' => CRM_Utils_Array::value('billing_street_address-' . $billingLocationID, $params),
'variable_ddi[town]' => CRM_Utils_Array::value('billing_city-' . $billingLocationID, $params),
'variable_ddi[postcode]' => CRM_Utils_Array::value('billing_postal_code-' . $billingLocationID, $params),
'variable_ddi[country]' => CRM_Utils_Array::value('billing_country_id-' . $billingLocationID, $params),
'variable_ddi[account_name]' => CRM_Utils_Array::value('account_holder', $params),
'variable_ddi[sort_code]' => CRM_Utils_Array::value('bank_identification_number', $params),
'variable_ddi[account_number]' => CRM_Utils_Array::value('bank_account_number', $params),
'variable_ddi[first_amount]' => CRM_Utils_Array::value('amount', $params, 0),
'variable_ddi[default_amount]' => CRM_Utils_Array::value('amount', $params, 0),
'variable_ddi[email_address]' => $this->getBillingEmail($params, $contactId),
];
$smartDebitFrequencyParams = self::getCollectionFrequencyPostParams($params);
$smartDebitParams = array_merge($smartDebitParams, $smartDebitFrequencyParams);
return $smartDebitParams;
}
/**
* Process payment
*
* Sets appropriate parameters and calls Smart Debit API to create a payment
*
* Payment processors should set payment_status_id.
*
* @param array $params
* Assoc array of input parameters for this transaction.
*
* @param string $component
*
* @return array
* Result array
*
* @throws \CiviCRM_API3_Exception
* @throws \Civi\Payment\Exception\PaymentProcessorException
*/
public function doPayment(&$params, $component = 'contribute') {
$this->beginDoPayment($params);
$smartDebitParams = self::preparePostArray($params);
CRM_Smartdebit_Hook::alterVariableDDIParams($params, $smartDebitParams, 'create');
self::checkSmartDebitParams($smartDebitParams);
$url = CRM_Smartdebit_Api::buildUrl($this->_paymentProcessor, 'api/ddi/variable/create');
$response = CRM_Smartdebit_Api::requestPost($url, $smartDebitParams, $this->getUser(), $this->getPassword());
// Take action based upon the response status
if ($response['success']) {
if (isset($smartDebitParams['variable_ddi[reference_number]'])) {
$params['trxn_id'] = $smartDebitParams['variable_ddi[reference_number]'];
}
// Record the start/end date for the recurring contribution
if (isset($smartDebitParams['variable_ddi[start_date]'])) {
$params['start_date'] = $smartDebitParams['variable_ddi[start_date]'];
$params['next_sched_contribution_date'] = $params['start_date'];
}
if (isset($smartDebitParams['variable_ddi[end_date]'])) {
$params['end_date'] = $smartDebitParams['variable_ddi[end_date]'];
}
$params['is_test'] = CRM_Utils_Array::value('is_test', $this->_paymentProcessor, FALSE);
$params = $this->setRecurTransactionId($params);
CRM_Smartdebit_Base::completeDirectDebitSetup($params);
}
else {
$message = CRM_Utils_Array::value('message', $response) . ': ' . CRM_Smartdebit_Api::formatResponseError(CRM_Utils_Array::value('error', $response));
Civi::log()->error('Smartdebit::doPayment error: ' . $message . ' ' . print_r($smartDebitParams, TRUE));
throw new \Civi\Payment\Exception\PaymentProcessorException($message, CRM_Utils_Array::value('code', $response), $smartDebitParams);
}
// This allows us to set the contribution to completed if
// "Mark initial contribution as completed" is enabled in smartdebit settings
$params['contribution_status_id'] = self::getInitialContributionStatus(FALSE);
$contributionParams['receive_date'] = $params['start_date'];
$contributionParams['trxn_id'] = CRM_Smartdebit_DateUtils::getContributionTransactionId($params['trxn_id'], $params['start_date']);
if (empty($params['payment_instrument_id'])) {
$contributionParams['payment_instrument_id'] = (int) CRM_Smartdebit_Settings::getValue('payment_instrument_id');
}
if ($this->getContributionId($params)) {
$contributionParams['id'] = $this->getContributionId($params);
civicrm_api3('Contribution', 'create', $contributionParams);
unset($contributionParams['id']);
}
$params = array_merge($params, $contributionParams);
// We need to set this to ensure that contributions are set to the correct status
if (!empty($params['contribution_status_id'])) {
$params['payment_status_id'] = $params['contribution_status_id'];
}
return $params;
}
/**
* As the recur transaction is created before payment, we need to update it with our params after payment
*
* @param $params
*
* @return mixed
* @throws \CiviCRM_API3_Exception
*/
private function setRecurTransactionId($params) {
if (!empty($params['trxn_id'])) {
// Common parameters
$recurParams = [
'trxn_id' => $params['trxn_id'],
'is_test' => CRM_Utils_Array::value('is_test', $params, FALSE),
'payment_processor_id' => CRM_Utils_Array::value('payment_processor_id', $params, NULL),
'start_date' => $params['start_date'],
'next_sched_contribution_date' => $params['next_sched_contribution_date'],
'contribution_status_id' => self::getInitialContributionStatus(TRUE),
];
if (!empty($params['end_date'])) {
$recurParams['end_date'] = $params['end_date'];
}
if (!empty($params['preferred_collection_day'])) {
$recurParams['cycle_day'] = $params['preferred_collection_day'];
}
if (!empty($params['contributionRecurID'])) {
// Recurring transaction, so this is a recurring payment
$recurParams['id'] = $params['contributionRecurID'];
// Update the related contribution before the recur (so we can access it from the hook)
if (!empty($params['contributionID'])) {
// contributionID not set if we're creating a pledge
$contributionParams['id'] = $params['contributionID'];
// Receive date will be the date that the direct debit is taken, not today.
$contributionParams['receive_date'] = $recurParams['start_date'];
civicrm_api3('Contribution', 'create', $contributionParams);
}
// Hook to allow modifying recurring contribution params
CRM_Smartdebit_Hook::updateRecurringContribution($recurParams);
// Update the recurring payment
civicrm_api3('ContributionRecur', 'create', $recurParams);
// Update the contribution status
}
else {
// No recurring transaction, assume this is a non-recurring payment (so create a recurring contribution with a single installment
// Fill recurring transaction parameters
if (empty($params['receive_date'])) {
$params['receive_date'] = date('YmdHis');
}
$recurParams['contact_id'] = $this->getContactId($params);
$recurParams['create_date'] = $params['receive_date'];
$recurParams['modified_date'] = $params['receive_date'];
$recurParams['start_date'] = $params['start_date'];
$recurParams['next_sched_contribution_date'] = $params['next_sched_contribution_date'];
$recurParams['amount'] = $params['amount'];
$recurParams['frequency_unit'] = 'year';
$recurParams['frequency_interval'] = '1';
$recurParams['installments'] = '1';
$recurParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $params, CRM_Utils_Array::value('financialTypeID', $params));
$recurParams['auto_renew'] = '0'; // Make auto renew
$recurParams['currency'] = $params['currencyID'];
$recurParams['invoice_id'] = $params['invoiceID'];
$recur = CRM_Smartdebit_Base::createRecurContribution($recurParams);
// Record recurring contribution ID in params for return
$params['contributionRecurID'] = $recur['id'];
$params['contribution_recur_id'] = $recur['id'];
// We need to link the recurring contribution and contribution record, as Civi won't do it for us (4.7.21)
$contributionParams = [
'contribution_recur_id' => $params['contribution_recur_id'],
'contact_id' => $this->getContactId($params),
'is_test' => $params['is_test'],
];
if (empty($params['contributionID'])) {
Civi::log()->debug('Smartdebit: No contribution ID specified. Is this a non-recur transaction?');
}
else {
// Update the related contribution before the recur (so we can access it from the hook)
$contributionParams['id'] = $params['contributionID'];
civicrm_api3('Contribution', 'create', $contributionParams);
}
if ($contributionParams['contribution_status_id'] ==
CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')) {
$params['is_recur'] = 1; // Required for CRM_Core_Payment to set contribution status = Pending
}
}
}
return $params;
}
/**
* Get the initial (recur) contribution status based on the desired configuration.
* If initial_completed=TRUE we need to set initial contribution to completed.
*
* @param bool $isRecur TRUE if we should return status of recurring contribution instead.
*
* @return bool|int|null|string
*/
public static function getInitialContributionStatus($isRecur = FALSE) {
$initialCompleted = (boolean) CRM_Smartdebit_Settings::getValue('initial_completed');
if ($isRecur) {
return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'In Progress');
}
if ($initialCompleted) {
return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
}
return CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
}
/**
* Record the response from SmartDebit after validatePayment()
*
* @param array $direct_debit_response
*/
private static function recordSmartDebitResponse($direct_debit_response) {
$sql = "
UPDATE " . CRM_Smartdebit_Base::TABLENAME . " SET
created = NOW()
, request_counter = request_counter + 1
";
isset($direct_debit_response['data_type']) ? $sql .= ", data_type = \"{$direct_debit_response['data_type']}\"" : NULL;
isset($direct_debit_response['entity_type']) ? $sql .= ", entity_type = \"{$direct_debit_response['entity_type']}\"" : NULL;
isset($direct_debit_response['entity_id']) ? $sql .= " , entity_id = {$direct_debit_response['entity_id']}" : NULL;
isset($direct_debit_response['bank_name']) ? $sql .= " , bank_name = \"{$direct_debit_response['bank_name']}\"" : NULL;
isset($direct_debit_response['branch']) ? $sql .= " , branch = \"{$direct_debit_response['branch']}\"" : NULL;
isset($direct_debit_response['address1']) ? $sql .= " , address1 = \"{$direct_debit_response['address1']}\"" : NULL;
isset($direct_debit_response['address2']) ? $sql .= " , address2 = \"{$direct_debit_response['address2']}\"" : NULL;
isset($direct_debit_response['address3']) ? $sql .= " , address3 = \"{$direct_debit_response['address3']}\"" : NULL;
isset($direct_debit_response['address4']) ? $sql .= " , address4 = \"{$direct_debit_response['address4']}\"" : NULL;
isset($direct_debit_response['town']) ? $sql .= " , town = \"{$direct_debit_response['town']}\"" : NULL;
isset($direct_debit_response['county']) ? $sql .= " , county = \"{$direct_debit_response['county']}\"" : NULL;
isset($direct_debit_response['postcode']) ? $sql .= " , postcode = \"{$direct_debit_response['postcode']}\"" : NULL;
isset($direct_debit_response['first_collection_date']) ? $sql .= " , first_collection_date = \"{$direct_debit_response['first_collection_date']}\"" : NULL;
isset($direct_debit_response['preferred_collection_day']) ? $sql .= ", preferred_collection_day = \"{$direct_debit_response['preferred_collection_day']}\"" : NULL;
isset($direct_debit_response['response_status']) ? $sql .= " , response_status = \"{$direct_debit_response['response_status']}\"" : NULL;
isset($direct_debit_response['response_raw']) ? $sql .= " , response_raw = \"{$direct_debit_response['response_raw']}\"" : NULL;
$sql .= " WHERE ddi_reference = \"{$direct_debit_response['ddi_reference']}\"";
CRM_Core_DAO::executeQuery($sql);
}
/**
* Change the subscription amount using the Smart Debit API
*
* @param string $message
* @param array $params
*
* @return bool
* @throws \Exception
*/
public function changeSubscriptionAmount(&$message = '', $params = []) {
// Smartdebit start_date can change during the subscription (eg. if we update amount)
// so we need to be careful when setting it here.
// Logic: If a start_date is passed in via UpdateSubscription form we use it, otherwise
// we don't touch
$startDate = NULL;
if (!empty($params['start_date']) && (array_key_exists('_qf_UpdateSubscription_next', $params))) {
$startDate = $params['start_date'];
}
unset($params['start_date']);
return self::changeSubscription($this->_paymentProcessor, $params, $startDate);
}
/**
* This function allows to update the subscription with Smartdebit
* @param array $paymentProcessor
* @param array $recurContributionParams
* @param date $startDate We pass this in separately to recurContributionParams as we don't use recur start_date
* because subscription can change during life
*
* @return bool
* @throws \Exception
*/
public static function changeSubscription($paymentProcessor, $recurContributionParams, $startDate = NULL) {
try {
$recurRecord = civicrm_api3('ContributionRecur', 'getsingle', [
'id' => $recurContributionParams['id'],
'options' => ['limit' => 1],
]);
}
catch (CiviCRM_API3_Exception $e) {
CRM_Core_Error::statusBounce('No recurring record! ' . $e->getMessage());
return FALSE;
}
if (empty($recurRecord['trxn_id'])) {
CRM_Core_Session::setStatus('Update Subscription - No trxn_id!', 'Smart Debit', 'error');
return FALSE;
}
$recurContributionParams['amount'] = isset($recurContributionParams['amount']) ? $recurContributionParams['amount'] : 0;
$smartDebitParams = [
'variable_ddi[service_user][pslid]' => self::getSignatureStatic($paymentProcessor),
'variable_ddi[first_amount]' => $recurContributionParams['amount'],
'variable_ddi[default_amount]' => $recurContributionParams['amount'],
];
// End Date
$recurContributionParams['end_date'] = CRM_Utils_Array::value('end_date', $recurContributionParams, CRM_Utils_Array::value('end_date', $recurRecord, NULL));
if (!empty($recurContributionParams['end_date'])) {
$smartDebitParams['variable_ddi[end_date]'] = date("Y-m-d", strtotime($recurContributionParams['end_date']));
}
if (!isset($recurContributionParams['frequency_unit'])) {
$recurContributionParams['frequency_unit'] = $recurRecord['frequency_unit'];
}
if (!isset($recurContributionParams['frequency_interval'])) {
$recurContributionParams['frequency_interval'] = $recurRecord['frequency_interval'];
}
if (isset($recurContributionParams['frequency_unit']) || isset($recurContributionParams['frequency_interval'])) {
$smartDebitFrequencyParams = self::getCollectionFrequencyPostParams($recurContributionParams);
$smartDebitParams = array_merge($smartDebitParams, $smartDebitFrequencyParams);
}
if (!empty($startDate)) {
// We want to update the start_date
$smartDebitParams['variable_ddi[start_date]'] = $startDate;
$recurContributionParams['start_date'] = $startDate;
}