-
Notifications
You must be signed in to change notification settings - Fork 3
/
functions.php
executable file
·3390 lines (3024 loc) · 117 KB
/
functions.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 if (!defined('ABSPATH')) exit;
const RAISE_WEBHOOK_KEYS = [
'account',
'address',
'amount',
'anonymous',
'city',
'gift_aid',
'comment',
'country',
'country_code',
'currency',
'deductible',
'email',
'form',
'frequency',
'language',
'mailinglist',
'mode',
'name',
'purpose',
'reference',
'referrer',
'post_donation_instructions',
'share_data',
'share_data_offered',
'tax_receipt',
'terms',
'time',
'tip',
'tip_amount',
'tip_offered',
'tip_percentage',
'payment_provider',
'url',
'vendor_customer_id',
'vendor_subscription_id',
'vendor_transaction_id',
'zip',
];
/**
* Initialize form and return form settings
*
* @param string $form Form name
* @param string $mode sandbox/live
* @return array
*/
function raise_init_donation_form($form, $mode)
{
// Update settings
raise_update_settings();
// Load settings
$formSettings = raise_load_settings($form);
// Load logo
$logo = get_option('raise_logo', plugin_dir_url(__FILE__) . 'images/logo.png');
// Make amount patterns
$amountPatterns = array();
$amountMinimums = array();
$currencies = raise_get($formSettings['amount']['currency'], array());
foreach ($currencies as $currency => $currencySettings) {
$cur = strtoupper($currency);
$amountPatterns[$cur] = raise_get($currencySettings['pattern'], '%amount%');
$minimum = raise_get($currencySettings['minimum'], 1);
$amountMinimums[$cur] = array(
'once' => $minimum,
'monthly' => raise_get($currencySettings['minimum_monthly'], $minimum),
);
}
// Get array with custom below minimum amount error messages and upper-case currency keys
$belowMinimumAmountMessages = raise_monolinguify(array_filter(array_map(
function ($cur) {
return raise_get($cur['below_minimum_message']);
},
array_change_key_case(raise_get($formSettings['amount']['currency'], []), CASE_UPPER)
)));
// Get post_donation_instructions and localize labels
$postDonationInstructions = raise_get($formSettings['finish']['post_donation_instructions'], "");
if (is_array($postDonationInstructions) && !raise_has_string_keys($postDonationInstructions)) {
$postDonationInstructions = array_map(function($item) {
if (!empty($item['value']) && is_array($item['value'])) {
$item['value'] = raise_get_localized_value($item['value']);
}
return $item;
}, $postDonationInstructions);
}
$postDonationInstructionsRule = raise_get_jsonlogic_if_rule($postDonationInstructions, 'raise_get_localized_value');
// Get gift_aid rule and localize labels
$giftAidSettings = raise_get($formSettings['payment']['form_elements']['gift_aid'], "");
$giftAidRule = raise_get_checkbox_rule($giftAidSettings);
// Get tax_receipt rule and localize labels
$taxReceiptSettings = raise_get($formSettings['payment']['form_elements']['tax_receipt'], "");
$taxReceiptRule = raise_get_checkbox_rule($taxReceiptSettings);
// Get share_data rule and localize labels
$shareDataSettings = raise_get($formSettings['payment']['form_elements']['share_data'], "");
$shareDataRule = raise_get_checkbox_rule($shareDataSettings);
// Get tip rule and localize labels
$tipSettings = raise_get($formSettings['payment']['form_elements']['tip'], "");
$tipRule = raise_get_checkbox_rule($tipSettings);
// Get bank accounts and localize their labels
$bankAccounts = raise_get($formSettings['payment']['provider']['banktransfer']);
if (is_array($bankAccounts)) {
if (raise_has_string_keys($bankAccounts)) {
// No JsonLogic
if (raise_has_string_keys($bankAccounts['details'])) {
// Normal case
$bankAccounts['details'] = raise_localize_array_keys(raise_get($bankAccounts['details'], []));
} else {
// When using the same keys several times
$bankAccounts['details'] = array_map(function($item) {
return raise_localize_array_keys(raise_get($item, []));
}, $bankAccounts['details']);
}
} else {
// JsonLogic
$bankAccounts = array_map(function($item) {
if (!empty($item['value']['details']) && is_array($item['value']['details'])) {
if (raise_has_string_keys($item['value']['details'])) {
$item['value']['details'] = raise_localize_array_keys($item['value']['details']);
} else {
$item['value']['details'] = array_map(function($details) {
return raise_localize_array_keys($details);
}, $item['value']['details']);
}
}
if (!empty($item['value']['tooltip']) && is_array($item['value']['tooltip'])) {
$item['value']['tooltip'] = raise_get_localized_value($item['value']['tooltip']);
}
return $item;
}, $bankAccounts);
}
}
$bankAccountsRule = raise_get_jsonlogic_if_rule($bankAccounts, 'json_encode');
// Get tooltips and payment provider display rules
$enabledProviders = raise_enabled_payment_providers($formSettings, $mode);
$providerSettings = raise_get($formSettings['payment']['provider'], []);
$tooltipMap = function ($value) { return raise_get_localized_value(raise_get($value['tooltip']), ""); };
$displayMap = function ($value) { return true; };
$accountMap = function ($value) { return raise_get($value['account']); };
$tooltipIf = [];
$displayIf = [];
$accountIf = [];
foreach ($enabledProviders as $provider) {
// First level rule (provider)
$tooltipIf[] = $displayIf[] = $accountIf[] = ['===' => [["var" => "payment_provider"], $GLOBALS['pp_key2pp_label'][$provider]]];
// Second level rule (account)
if (!is_array($providerSettings[$provider])) {
$tooltipIf[] = "";
$displayIf[] = false;
$accountIf[] = null;
} elseif (raise_has_string_keys($providerSettings[$provider])) {
$tooltipIf[] = raise_get_localized_value(raise_get($providerSettings[$provider]['tooltip'], ""));
$displayIf[] = true;
$accountIf[] = raise_get($providerSettings[$provider]['account']);
} else {
$tooltipIf[] = raise_get_jsonlogic_if_rule($providerSettings[$provider], $tooltipMap, "");
$displayIf[] = raise_get_jsonlogic_if_rule($providerSettings[$provider], $displayMap, false);
$accountIf[] = raise_get_jsonlogic_if_rule($providerSettings[$provider], $accountMap);
}
}
$tooltipIf[] = ""; // Default tooltip
$displayIf[] = false; // Default display mode
$paymentProviderTooltipRule = ["if" => $tooltipIf];
$paymentProviderDisplayRule = ["if" => $displayIf];
$paymentProviderAccountRule = ["if" => $accountIf];
// Localize script
wp_localize_script('donation-plugin-form', 'wordpress_vars', array(
'logo' => $logo,
'ajax_endpoint' => admin_url('admin-ajax.php'),
'amount_patterns' => $amountPatterns,
'amount_minimums' => $amountMinimums,
'post_donation_instructions_rule' => $postDonationInstructionsRule,
'payment_provider_tooltip_rule' => $paymentProviderTooltipRule,
'payment_provider_display_rule' => $paymentProviderDisplayRule,
'payment_provider_account_rule' => $paymentProviderAccountRule,
'share_data_rule' => $shareDataRule,
'tip_rule' => $tipRule,
'tax_receipt_rule' => $taxReceiptRule,
'gift_aid_rule' => $giftAidRule,
'bank_account_rule' => $bankAccountsRule,
'organization' => $GLOBALS['raiseOrganization'],
'currency2country' => $GLOBALS['currency2country'],
'monthly_support' => $GLOBALS['monthlySupport'],
'default_frequency' => raise_get($formSettings['amount']['frequency']['default'], 'once'),
'account_description' => raise_get($formSettings['payment']['account_description'], []),
'labels' => [
'yes' => __("yes", "raise"),
'no' => __("no", "raise"),
'donate_button_once' => __("Donate %currency-amount%", "raise"),
'donate_button_monthly' => __("Donate %currency-amount% per month", "raise"),
'donation' => __("Donation", "raise"),
'amount' => __("Amount", "raise"),
'cookie_warning' => __("Please enable cookies before you proceed with your donation.", "raise"),
],
'error_messages' => [
'missing_fields' => __('Please fill out all required fields.', 'raise'),
'invalid_email' => __('Invalid email.', 'raise'),
'below_minimum_amount' => __('The minimum donation is %minimum_amount%.', 'raise'),
'connection_error' => __('Error establishing a connection. Please try again.', 'raise'),
'below_minimum_amount_custom' => $belowMinimumAmountMessages,
'terms' => __('You must accept our Terms and Conditions to continue.', 'raise'),
'gift_aid_confirmation' => __('You must accept the UK Gift Aid Conditions to continue.', 'raise'),
],
));
// Enqueue previously registered scripts and styles (to prevent them loading on every page load)
wp_enqueue_script('donation-plugin-bootstrapjs');
wp_enqueue_script('donation-plugin-jqueryformjs');
wp_enqueue_script('donation-plugin-jquery-slick');
if (in_array('stripe', $enabledProviders)) {
wp_enqueue_script('donation-plugin-stripe');
}
if (in_array('paypal', $enabledProviders)) {
wp_enqueue_script('donation-plugin-paypal');
}
wp_enqueue_script('donation-plugin-json-logic');
wp_enqueue_script('donation-plugin-form');
wp_enqueue_script('donation-plugin-combobox');
return $formSettings;
}
/**
* Load form settings
*
* @param string $form Form name
* @return array
* @throws \Exception
*/
function raise_load_settings($form)
{
// Checked if loaded already
if (isset($GLOBALS['raiseForms'][$form])) {
return $GLOBALS['raiseForms'][$form];
}
// Load parameters
$raiseSettings = json_decode(get_option('raise_settings'), true);
// Check if config plugin is around
$externalSettings = array();
if (function_exists('raise_config')) {
if ($externalSettings = raise_config()) {
// Merge
$raiseSettings = raise_array_replace_recursive($externalSettings, $raiseSettings);
} else {
throw new \Exception("Syntax error in config plugin JSON");
}
}
// Load organization in current language
$organization = !empty($raiseSettings['organization']) ? (raise_get_localized_value($raiseSettings['organization']) ?: '') : '';
// Resolve form inheritance
$formSettings = raise_rec_load_settings($form, $raiseSettings['forms']);
// Remove inherits property
unset($formSettings['inherits']);
// Add organization and form settings to GLOBALS
$GLOBALS['raiseOrganization'] = $organization;
$GLOBALS['raiseForms'] = array($form => $formSettings);
return $formSettings;
}
/**
* Internal: Resolve form inheritance
*
* @param string $form
* @param array $formsSettings
* @param array $childForms To avoid circular inheritance
* @return array
* @throws \Exception
*/
function raise_rec_load_settings($form, $formsSettings, $childForms = array())
{
if (in_array($form, $childForms)) {
throw new \Exception("Circular form definition. See Settings > Raise");
}
if (!isset($formsSettings[$form])) {
throw new \Exception("No settings found for form '$form'. See Settings > Raise");
}
if (!($parentForm = raise_get($formsSettings[$form]['inherits']))) {
return $formsSettings[$form];
}
// Recurse and merge
$childForms[] = $form;
$parentFormSettings = raise_rec_load_settings($parentForm, $formsSettings, $childForms);
return raise_array_replace_recursive($parentFormSettings, $formsSettings[$form]);
}
/**
* Get `if` rule with JSON encoded objects (label, disabled, checked) as return values for checkbox
*
* @param array|string $settings
* @return array
*/
function raise_get_checkbox_rule($settings)
{
if (is_array($settings)) {
if (isset($settings['label'])) {
$settings['label'] = raise_get_localized_value($settings['label']);
} else {
$settings = array_map(function($item) {
if (!empty($item['value']['label']) && is_array($item['value']['label'])) {
$item['value']['label'] = raise_get_localized_value($item['value']['label']);
}
return $item;
}, $settings);
}
}
return raise_get_jsonlogic_if_rule($settings, 'json_encode');
}
/**
* Return list of enabled providers
*
* @param array $formSettings
* @param string $mode
* @return array
*/
function raise_enabled_payment_providers($formSettings, $mode)
{
// Get provider settings
$providerSettings = raise_get($formSettings['payment']['provider'], array());
// Filter out incomplete settings
$providers = array_filter($providerSettings, function ($settings, $provider) use ($mode) {
return strpos($provider, '_') === false // No underscores in provider key
&&
is_array($settings) // Must be array
&&
(
(
// Make sure all necessary account properties are present
raise_has_string_keys($settings)
&&
raise_payment_provider_settings_complete($provider, raise_get($settings[$mode], []))
) || (
// If it's JsonLogic, do the same for all nodes
!raise_has_string_keys($settings)
&&
array_reduce($settings, function ($carry, $item) use ($provider, $mode) {
return $carry && raise_payment_provider_settings_complete($provider, raise_get($item['value'][$mode], []));
}, true)
)
);
}, ARRAY_FILTER_USE_BOTH);
// Only return keys
return array_keys($providers);
}
/**
* Are properties complete?
*
* @param string $provider
* @param array $properties
* @param bool
*/
function raise_payment_provider_settings_complete($provider, array $properties)
{
$requiredProperties = raise_get_payment_provider_properties($provider);
return array_reduce($requiredProperties, function ($carry, $item) use ($properties) {
return $carry && !empty($properties[$item]);
}, true);
}
/**
* Print paymnet provider HTML
*
* @param array $formSettings
* @param string $mode
* @return string
*/
function raise_print_payment_providers($formSettings, $mode)
{
// Get enabled providers
$frequency = raise_get($formSettings['amount']['frequency']['default'], 'once');
$providers = raise_enabled_payment_providers($formSettings, $mode);
$checked = true;
$result = '';
foreach ($providers as $provider) {
switch ($provider) {
case 'stripe':
$value = 'Stripe';
$text = '<div class="payment-method-name sr-only">' . __('credit card', 'raise') . '</div>';
$images = ['pp cc visa', 'pp cc mastercard', 'pp cc amex', 'pp cc gpay', 'pp cc apay'];
break;
case 'paypal':
$value = 'PayPal';
$text = '<div class="payment-method-name sr-only">PayPal</div>';
$images = ['pp paypal'];
break;
case 'bitpay':
$value = 'BitPay';
$text = '<div class="payment-method-name sr-only">Bitcoin</div>';
$images = ['pp bitcoin'];
break;
case 'coinbase':
$value = 'Coinbase';
$text = '<span class="payment-method-name sr-only">Coinbase</span>';
$images = ['pp bitcoin', 'pp bitcoin_cash', 'pp ethereum', 'pp litecoin'];
break;
case 'skrill':
$value = 'Skrill';
$text = '<div class="payment-method-name sr-only">Skrill</div>';
$images = ['pp skrill'];
break;
case 'gocardless':
$value = 'GoCardless';
$text = '<div class="payment-method-name">' . __('direct debit', 'raise') . '</div>';
$images = [];
break;
case 'banktransfer':
$value = 'Bank Transfer';
$text = '<div class="payment-method-name">' . __('bank transfer', 'raise') . '</div>';
$images = [];
break;
default:
// Do nothing
continue 2;
}
// Print radio box
$id = str_replace(' ', '', strtolower($value));
$checkedAttr = $checked ? 'checked' : '';
$checked = false;
$hidden = $frequency === 'once' || in_array($id, $GLOBALS['monthlySupport']) ? '' : ' hidden';
// Construct radio and append to result
$radio = '<div class="pp-images">' . implode('', array_map(function($val) {
return '<div class="' . $val . '"></div>';
}, $images)) . '</div>' . $text;
$radio = '<div data-toggle="tooltip" data-container="body" title="">' . $radio . '</div>';
$radio = '<input type="radio" name="payment_provider" value="' . $value . '" id="payment-' . $id . '" ' . $checkedAttr . '> ' . $radio;
$radio = '<label for="payment-' . $id . '" class="radio-inline' . $hidden . '">' . $radio . '</label>' . "\n";
$result .= $radio;
}
return $result;
}
/**
* Get donation from $_POST
*
* @return array
* @throws \Exception
*/
function raise_get_form_data()
{
// Get data
$post = raise_get_donation_from_post();
// Return formatted data
return raise_format_donation($post);
}
/**
* Get form data from $_POST
*
* @return array
*/
function raise_get_donation_from_post()
{
// Trim the data
$post = array_map('trim', $_POST);
// Replace amount_other
if (!empty($post['amount_other'])) {
$post['amount'] = $post['amount_other'];
}
unset($post['amount_other']);
// Add tip to amount
if (is_numeric($post['amount'])) {
$amountInt = (int)($post['amount'] * 100);
$tipInt = (int)($post['tip_amount'] * 100);
$amountInt += $tipInt;
$post['amount'] = number_format($amountInt / 100, 2, '.', '');
} else {
throw new \Exception('Invalid amount');
}
// Set language
$post['language'] = substr($post['locale'], 0, 2);
return $post;
}
/**
* Format donation
*
* @param array $donation
* @return array Formatted donation
*/
function raise_format_donation(array $donation) {
return [
'form' => $donation['form'],
'mode' => $donation['mode'],
'url' => $_SERVER['HTTP_REFERER'],
'language' => $donation['language'],
'time' => date('c'),
'currency' => $donation['currency'],
'amount' => $donation['amount'],
'tip_amount' => $donation['tip_amount'],
'tip_percentage' => $donation['tip_percentage'],
'frequency' => $donation['frequency'],
'payment_provider' => $donation['payment_provider'],
'email' => $donation['email'],
'name' => stripslashes($donation['name']),
'purpose' => raise_get($donation['purpose'], ''),
'address' => stripslashes(raise_get($donation['address'], '')),
'zip' => raise_get($donation['zip'], ''),
'city' => stripslashes(raise_get($donation['city'], '')),
'country_code' => raise_get($donation['country_code'], ''),
'comment' => raise_get($donation['comment'], ''),
'account' => raise_get($donation['account'], ''),
'post_donation_instructions' => raise_get($donation['post_donation_instructions'], ''),
'vendor_transaction_id' => raise_get($donation['vendor_transaction_id'], ''),
'vendor_subscription_id' => raise_get($donation['vendor_subscription_id'], ''),
'vendor_customer_id' => raise_get($donation['vendor_customer_id'], ''),
'g-recaptcha-response' => raise_get($donation['g-recaptcha-response'], ''),
'anonymous' => (bool) raise_get($donation['anonymous'], false),
'mailinglist' => (bool) raise_get($donation['mailinglist'], false),
'tax_receipt' => (bool) raise_get($donation['tax_receipt'], false),
'share_data' => (bool) raise_get($donation['share_data'], false),
'share_data_offered' => (bool) raise_get($donation['share_data_offered'], false),
'tip' => (bool) raise_get($donation['tip'], false),
'tip_offered' => (bool) raise_get($donation['tip_offered'], false),
'terms' => (bool) raise_get($donation['terms'], false),
'gift_aid' => (bool) raise_get($donation['gift_aid'], false),
];
}
/**
* AJAX endpoint that creates redirect response in HTML (Stripe)
*
* @return string JSON response
*/
function raise_prepare_redirect_html()
{
try {
$post = raise_get_donation_from_post();
// Output
switch ($post['payment_provider']) {
case "Stripe":
$response = raise_prepare_stripe_donation($post);
break;
default:
throw new \Exception('Payment method ' . $post['payment_provider'] . ' is invalid');
}
// Return response
die($response);
} catch (\Exception $ex) {
die($ex->getMessage());
}
}
/**
* AJAX endpoint that creates redirect response in JSON (PayPal, Skrill, GoCardless, BitPay)
*
* @return string JSON response
*/
function raise_prepare_redirect()
{
try {
$post = raise_get_donation_from_post();
// Output
switch ($post['payment_provider']) {
case "PayPal":
$response = raise_prepare_paypal_donation($post);
break;
case "Skrill":
$response = raise_prepare_skrill_donation($post);
break;
case "GoCardless":
$response = raise_prepare_gocardless_donation($post);
break;
case "BitPay":
$response = raise_prepare_bitpay_donation($post);
break;
case "Coinbase":
$response = raise_prepare_coinbase_donation($post);
break;
default:
throw new \Exception('Payment method ' . $post['payment_provider'] . ' is invalid');
}
// Return response
wp_send_json($response);
} catch (\Exception $ex) {
wp_send_json(raise_rest_exception_response($ex));
}
}
/**
* AJAX endpoint that deals with submitted donation data (bank tarnsfer only)
*
* @return string JSON response
*/
function raise_process_banktransfer()
{
try {
// Get donation
$donation = raise_get_form_data();
// Check honey pot (confirm email)
raise_check_honey_pot($_POST);
// Check reCAPTCHA
$formSettings = raise_load_settings($donation['form']);
$secret = raise_get($formSettings['payment']['recaptcha']['secret_key']);
if (!empty($secret)) {
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $donation['g-recaptcha-response'];
$resp = $recaptcha->verify($gRecaptchaResponse, $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
throw new \Exception('Invalid reCAPTCHA');
}
}
// Handle payment
$reference = raise_handle_banktransfer_payment($donation);
// Prepare response
$response = [
'success' => true,
'reference' => $reference,
];
wp_send_json($response);
} catch (\Exception $ex) {
wp_send_json(raise_rest_exception_response($ex), 400);
}
}
/**
* Get monthly Stripe plan
*
* @param int $amount Plan amount in cents
* @param int $currency Plan currency
* @param string $purpose Plan purpose, e.g. AMF
* @param string $purposeLabel Plan purpose label, e.g. Against Malaria Foundation
* @return array
*/
function raise_get_stripe_plan($amount, $currency, $purpose = null, $purposeLabel = null)
{
$purposeSuffix = $purpose ? '-' . $purpose : '';
$purposeLabelSuffix = $purposeLabel ? ' to ' . $purposeLabel : '';
$planId = 'donation-month-' . $currency . '-' . str_replace('.', '_', number_format($amount / 100, 2, '.', '')) . $purposeSuffix;
try {
// Try fetching an existing plan
$plan = \Stripe\Plan::retrieve($planId);
} catch (\Exception $e) {
// Create a new plan
$params = array(
'amount' => $amount,
'interval' => 'month',
'product' => [
'name' => 'monthly donations' . $purposeLabelSuffix,
],
'currency' => $currency,
'id' => $planId,
);
$plan = \Stripe\Plan::create($params);
if (!$plan instanceof \Stripe\Plan) {
throw new \Exception('Credit card API is down. Please try later.');
}
$plan->save();
}
return $plan->id;
}
/**
* Process bank transfer payment (simply log it)
*
* @param array $donation Donation form data
* @return string Reference number
*/
function raise_handle_banktransfer_payment(array $donation)
{
// Generate reference number and add to donation
$reference = raise_get_banktransfer_reference($donation['form'], raise_get($donation['purpose']));
$donation['reference'] = $reference;
// Inject reference number into post_donation_instructions
if (!empty($donation['post_donation_instructions'])) {
$donation['post_donation_instructions'] = str_replace('%reference_number%', $reference, $donation['post_donation_instructions']);
}
// Do post donation actions
raise_do_post_donation_actions($donation);
return $reference;
}
/**
* Trigger webhooks (logging and mailing list)
*
* @param array $donation
*/
function raise_trigger_webhooks(array $donation)
{
// Filter donation
$filteredDonation = raise_filter_webhook_payload($donation);
// Logging
raise_trigger_logging_webhooks($filteredDonation);
// Mailing list
if ($donation['mailinglist'] === 'yes') {
raise_trigger_mailinglist_webhooks($filteredDonation);
}
}
/**
* Send logging web hooks
*
* @param array $donation Donation data for logging
*/
function raise_trigger_logging_webhooks($donation)
{
// Get form and mode
$form = raise_get($donation['form'], '');
$mode = raise_get($donation['mode'], '');
// Trigger hooks for Zapier
$formSettings = raise_load_settings($form);
if (isset($formSettings['webhook']['logging'][$mode])) {
$hooks = raise_csv_to_array($formSettings['webhook']['logging'][$mode]);
foreach ($hooks as $hook) {
raise_send_webhook($hook, $donation);
}
}
}
/**
* Transform boolean values to yes/no strings, translate country code to English,
* add referrer from query string if present
*
* @param array $donation
* @return array
*/
function raise_clean_up_donation_data(array $donation)
{
// Transform boolean values to yes/no strings
$donation = array_map(function($val) {
return is_bool($val) ? ($val ? 'yes' : 'no') : $val;
}, $donation);
// Replace \" with "
$donation = array_map(function($val) {
return is_string($val) ? str_replace('\"', '"', $val) : $val;
}, $donation);
// Translate country code to English
if (!empty($donation['country_code'])) {
$donation['country'] = raise_get_english_name_by_country_code($donation['country_code']);
}
// Add referrer from query string if present
$parts = parse_url(raise_get($donation['url']));
parse_str(raise_get($parts['query'], ''), $query);
$donation['referrer'] = raise_get($query['referrer']);
return $donation;
}
/**
* Remove unncecessary field from webhook data
*
* @param array $donation
* @return array
*/
function raise_filter_webhook_payload(array $donation)
{
// Set all empty fields to empty string
$values = array_map(function ($key) use ($donation) {
return raise_get($donation[$key], '');
}, RAISE_WEBHOOK_KEYS);
return array_combine(RAISE_WEBHOOK_KEYS, $values);
}
/**
* Send mailing_list web hooks
*
* @param array $donation Donation data
*/
function raise_trigger_mailinglist_webhooks($donation)
{
// Get form and mode
$form = raise_get($donation['form'], '');
$mode = raise_get($donation['mode'], '');
// Trigger hooks for Zapier
$formSettings = raise_load_settings($form);
if (isset($formSettings['webhook']['mailing_list'][$mode])) {
// Get subscription data
$subscription = array(
'form' => $donation['form'],
'mode' => $donation['mode'],
'email' => $donation['email'],
'name' => $donation['name'],
'language' => $donation['language'],
);
// Iterate over hooks
$hooks = raise_csv_to_array($formSettings['webhook']['mailing_list'][$mode]);
foreach ($hooks as $hook) {
raise_send_webhook($hook, $subscription);
}
}
}
/**
* Send webhook
*
* @param string $url Target URL
* @param array $params Arguments
*/
function raise_send_webhook($url, array $params)
{
global $wp_version;
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
return;
}
$version = raise_get_plugin_version();
$userAgent = "Raise/{$version} (compatible; WordPress {$wp_version}; +https://github.com/ea-foundation/raise)";
$args = array(
'user-agent' => $userAgent,
'body' => $params,
'timeout' => 30,
'referer' => get_bloginfo('url'),
);
// Send webhook
$response = wp_remote_post($url, $args);
// Make sure it arrived
if (is_wp_error($response)) {
throw new \Exception($response->get_error_message());
}
}
/**
* Get GoCardless client
*
* @param array $donation
* @return \GoCardlessPro\Client
*/
function raise_get_gocardless_client(array $donation)
{
// Get GoCardless account settings
$settings = raise_get_payment_provider_account_settings('gocardless', $donation);
$mode = raise_get($donation['mode']);
return new \GoCardlessPro\Client([
'access_token' => $settings['access_token'],
'environment' => $mode === 'live' ? \GoCardlessPro\Environment::LIVE : \GoCardlessPro\Environment::SANDBOX,
]);
}
/**
* Get payment provider settings properties
*
* @param string $provider
* @return array
*/
function raise_get_payment_provider_properties($provider)
{
switch (strtolower($provider)) {
case "stripe":
return array("secret_key", "public_key");
case "paypal":
return array("client_id", "client_secret");
case "gocardless":
return array("access_token");
case "bitpay":
return array("pairing_code");
case "coinbase":
return array("api_key");
case "skrill":
return array("merchant_account");
default:
return array();
}
}
/**
* AJAX endpoint that returns the GoCardless setup URL. It stores
* user input in session until user is forwarded back from GoCardless
*
* @param array $donation
* @return array
*/
function raise_prepare_gocardless_donation(array $donation)
{
try {
// Make GoCardless redirect flow
$reqId = uniqid(); // Secret request ID. Needed to prevent replay attack
$returnUrl = raise_get_ajax_endpoint() . '?action=gocardless_debit&req=' . $reqId;
$client = raise_get_gocardless_client($donation);
$description = $donation['frequency'] === 'monthly'
? __("Monthly payment mandate of %currency% %amount%", "raise")
: __("One-time payment mandate of %currency% %amount%", "raise");
$redirectFlow = $client->redirectFlows()->create([
"params" => [
"description" => str_replace('%currency%', $donation['currency'], str_replace('%amount%', number_format($donation['amount'], 2, '.', ''), $description)),
"session_token" => $reqId,
"success_redirect_url" => $returnUrl,
"prefilled_customer" => [
"email" => $donation['email'],
],
]
]);
// Save flow ID to session
$_SESSION['raise-gocardless-flow-id'] = $redirectFlow->id;
// Save rest to session
raise_set_donation_data_to_session($donation, $reqId);
// Return redirect URL
return array(
'success' => true,
'url' => $redirectFlow->redirect_url,
'reqId' => $reqId,
);
} catch (\Exception $ex) {
return raise_rest_exception_response($ex);
}
}
/**
* Return exception response
*
* @param \Exception $ex
* @return array
*/
function raise_rest_exception_response($ex)
{
return array(
'success' => false,
'error' => "An error occured and your donation could not be processed.\n\n" . $ex->getMessage() . "\n\nPlease contact us.",
);
}
/**
* AJAX endpoint that debits donor with GoCardless.
* The user is redirected here after successful signup.
*/
function raise_process_gocardless_donation()
{
try {
// Get donation from session
$donation = raise_get_donation_from_session();
// Verify session and purge reqId from session
raise_verify_session();
// Get client
$reqId = $donation['reqId'];
$client = raise_get_gocardless_client($donation);
if (!isset($_GET['redirect_flow_id']) || $_GET['redirect_flow_id'] != $_SESSION['raise-gocardless-flow-id']) {
throw new \Exception('Invalid flow ID');