-
Notifications
You must be signed in to change notification settings - Fork 382
Expand file tree
/
Copy pathclass.pmprogateway_paypalexpress.php
More file actions
1397 lines (1175 loc) · 51.9 KB
/
class.pmprogateway_paypalexpress.php
File metadata and controls
1397 lines (1175 loc) · 51.9 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
//include pmprogateway
require_once(dirname(__FILE__) . "/class.pmprogateway.php");
//load classes init method
add_action('init', array('PMProGateway_paypalexpress', 'init'));
class PMProGateway_paypalexpress extends PMProGateway
{
/** @var int Maximum number of request retries */
protected static $maxNetworkRetries = 5;
/** @var float Maximum delay between retries, in seconds */
protected static $maxNetworkRetryDelay = 2.0;
/** @var float Initial delay between retries, in seconds */
protected static $initialNetworkRetryDelay = 0.5;
function __construct($gateway = NULL)
{
$this->gateway = $gateway;
return $this->gateway;
}
/**
* Run on WP init
*
* @since 1.8
*/
static function init()
{
//make sure PayPal Express is a gateway option
add_filter('pmpro_gateways', array('PMProGateway_paypalexpress', 'pmpro_gateways'));
//add fields to payment settings
add_filter('pmpro_payment_options', array('PMProGateway_paypalexpress', 'pmpro_payment_options'));
/*
Filter pmpro_next_payment to get actual value
via the PayPal API. This is disabled by default
for performance reasons, but you can enable it
by copying this line into a custom plugin or
your active theme's functions.php and uncommenting
it there.
*/
//add_filter('pmpro_next_payment', array('PMProGateway_paypalexpress', 'pmpro_next_payment'), 10, 3);
/*
This code is the same for PayPal Website Payments Pro, PayPal Express, and PayPal Standard
So we only load it if we haven't already.
*/
global $pmpro_payment_option_fields_for_paypal;
if(empty($pmpro_payment_option_fields_for_paypal))
{
add_filter('pmpro_payment_option_fields', array('PMProGateway_paypalexpress', 'pmpro_payment_option_fields'), 10, 2);
$pmpro_payment_option_fields_for_paypal = true;
}
//code to add at checkout
$gateway = pmpro_getGateway();
if($gateway == "paypalexpress")
{
add_action('pmpro_checkout_preheader', array('PMProGateway_paypalexpress', 'pmpro_checkout_preheader'));
add_filter('pmpro_include_billing_address_fields', '__return_false');
add_filter('pmpro_include_payment_information_fields', '__return_false');
add_filter('pmpro_required_billing_fields', array('PMProGateway_paypalexpress', 'pmpro_required_billing_fields'));
add_filter('pmpro_checkout_new_user_array', array('PMProGateway_paypalexpress', 'pmpro_checkout_new_user_array'));
add_filter('pmpro_checkout_confirmed', array('PMProGateway_paypalexpress', 'pmpro_checkout_confirmed'));
add_filter('pmpro_checkout_default_submit_button', array('PMProGateway_paypalexpress', 'pmpro_checkout_default_submit_button'));
add_action('http_api_curl', array('PMProGateway_paypalexpress', 'http_api_curl'), 10, 3);
}
add_filter( 'pmpro_process_refund_paypalexpress', array('PMProGateway_paypalexpress', 'process_refund' ), 10, 2 );
}
/**
* Update the SSLVERSION for CURL to support PayPal Express moving to TLS 1.2
*
* @since 1.8.9.1
*/
static function http_api_curl($handle, $r, $url) {
if(strpos($url, 'paypal.com') !== false)
curl_setopt( $handle, CURLOPT_SSLVERSION, 6 );
}
/**
* Make sure this gateway is in the gateways list
*
* @since 1.8
*/
static function pmpro_gateways($gateways)
{
if(empty($gateways['paypalexpress']))
$gateways['paypalexpress'] = __('PayPal Express', 'paid-memberships-pro' );
return $gateways;
}
/**
* Get a list of payment options that the this gateway needs/supports.
*
* @since 1.8
*/
static function getGatewayOptions()
{
$options = array(
'sslseal',
'nuclear_HTTPS',
'gateway_environment',
'gateway_email',
'apiusername',
'apipassword',
'apisignature',
'currency',
'use_ssl',
'tax_state',
'tax_rate',
'paypalexpress_skip_confirmation',
);
return $options;
}
/**
* Set payment options for payment settings page.
*
* @since 1.8
*/
static function pmpro_payment_options($options)
{
//get options
$paypal_options = PMProGateway_paypalexpress::getGatewayOptions();
//merge with others.
$options = array_merge($paypal_options, $options);
return $options;
}
/**
* Display fields for this gateway's options.
*
* @since 1.8
*/
static function pmpro_payment_option_fields($values, $gateway)
{
?>
<tr class="pmpro_settings_divider gateway gateway_paypal gateway_paypalexpress gateway_paypalstandard" <?php if($gateway != "paypal" && $gateway != "paypalexpress" && $gateway != "paypalstandard") { ?>style="display: none;"<?php } ?>>
<td colspan="2">
<hr />
<h2 class="title"><?php esc_html_e( 'PayPal Settings', 'paid-memberships-pro' ); ?></h2>
</td>
</tr>
<tr class="gateway gateway_paypalstandard" <?php if($gateway != "paypalstandard") { ?>style="display: none;"<?php } ?>>
<td colspan="2" style="padding: 0px;">
<div class="notice error inline">
<p>
<?php
$allowed_message_html = array (
'a' => array (
'href' => array(),
'target' => array(),
'title' => array(),
),
);
echo sprintf( wp_kses( __( 'Note: We do not recommend using PayPal Standard. We suggest using PayPal Express, Website Payments Pro (Legacy), or PayPal Pro (Payflow Pro). <a target="_blank" href="%s" title="More information on why can be found here">More information on why can be found here</a>.', 'paid-memberships-pro' ), $allowed_message_html ), 'https://www.paidmembershipspro.com/read-using-paypal-standard-paid-memberships-pro/?utm_source=plugin&utm_medium=pmpro-paymentsettings&utm_campaign=blog&utm_content=read-using-paypal-standard-paid-memberships-pro' );
?>
</p>
</div>
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress gateway_paypalstandard" <?php if($gateway != "paypal" && $gateway != "paypalexpress" && $gateway != "paypalstandard") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label for="gateway_email"><?php esc_html_e('Gateway Account Email', 'paid-memberships-pro' );?></label>
</th>
<td>
<input type="text" id="gateway_email" name="gateway_email" value="<?php echo esc_attr($values['gateway_email'])?>" class="regular-text code" />
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress" <?php if($gateway != "paypal" && $gateway != "paypalexpress") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label for="apiusername"><?php esc_html_e('API Username', 'paid-memberships-pro' );?></label>
</th>
<td>
<input type="text" id="apiusername" name="apiusername" value="<?php echo esc_attr($values['apiusername'])?>" class="regular-text code" />
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress" <?php if($gateway != "paypal" && $gateway != "paypalexpress") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label for="apipassword"><?php esc_html_e('API Password', 'paid-memberships-pro' );?></label>
</th>
<td>
<input type="text" id="apipassword" name="apipassword" value="<?php echo esc_attr($values['apipassword'])?>" autocomplete="off" class="regular-text code pmpro-admin-secure-key" />
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress" <?php if($gateway != "paypal" && $gateway != "paypalexpress") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label for="apisignature"><?php esc_html_e('API Signature', 'paid-memberships-pro' );?></label>
</th>
<td>
<input type="text" id="apisignature" name="apisignature" value="<?php echo esc_attr($values['apisignature'])?>" class="regular-text code" />
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress" <?php if($gateway != "paypal" && $gateway != "paypalexpress") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label for="paypalexpress_skip_confirmation"><?php esc_html_e('Confirmation Step', 'paid-memberships-pro' );?></label>
</th>
<td>
<select id="paypalexpress_skip_confirmation" name="paypalexpress_skip_confirmation">
<option value="0" <?php selected(get_option('pmpro_paypalexpress_skip_confirmation'), 0);?>><?php esc_html_e( 'Require an extra confirmation after users return from PayPal.', 'paid-memberships-pro' ) ?></option>
<option value="1" <?php selected(get_option('pmpro_paypalexpress_skip_confirmation'), 1);?>><?php esc_html_e( 'Skip the extra confirmation after users return from PayPal.', 'paid-memberships-pro' ) ?></option>
</select>
</td>
</tr>
<tr class="gateway gateway_paypal gateway_paypalexpress gateway_paypalstandard" <?php if($gateway != "paypal" && $gateway != "paypalexpress" && $gateway != "paypalstandard") { ?>style="display: none;"<?php } ?>>
<th scope="row" valign="top">
<label><?php esc_html_e('IPN Handler URL', 'paid-memberships-pro' );?></label>
</th>
<td>
<p class="description"><?php esc_html_e('To fully integrate with PayPal, be sure to set your IPN Handler URL to ', 'paid-memberships-pro' );?></p>
<p><code><?php echo esc_html( add_query_arg( 'action', 'ipnhandler', admin_url('admin-ajax.php') ) );?></code></p>
</td>
</tr>
<?php
}
/**
* Remove required billing fields
*
* @since 1.8
*/
static function pmpro_required_billing_fields($fields)
{
unset($fields['bfirstname']);
unset($fields['blastname']);
unset($fields['baddress1']);
unset($fields['bcity']);
unset($fields['bstate']);
unset($fields['bzipcode']);
unset($fields['bphone']);
unset($fields['bemail']);
unset($fields['bcountry']);
unset($fields['CardType']);
unset($fields['AccountNumber']);
unset($fields['ExpirationMonth']);
unset($fields['ExpirationYear']);
unset($fields['CVV']);
return $fields;
}
/**
* Code added to checkout preheader.
*
* @since 2.1
*/
static function pmpro_checkout_preheader() {
global $gateway, $pmpro_level;
$default_gateway = get_option("pmpro_gateway");
if(($gateway == "paypal" || $default_gateway == "paypal") && !pmpro_isLevelFree($pmpro_level)) {
wp_register_script( 'pmpro_paypal',
plugins_url( 'js/pmpro-paypal.js', PMPRO_BASE_FILE ),
array( 'jquery' ),
PMPRO_VERSION );
//wp_localize_script( 'pmpro_paypal', 'pmpro_paypal', array());
wp_enqueue_script( 'pmpro_paypal' );
}
}
/**
* Save session vars before processing
*
* @since 1.8
* @deprecated 2.12.3
*/
static function pmpro_checkout_before_processing() {
global $current_user, $gateway;
_deprecated_function( __FUNCTION__, '2.12.3' );
//save user fields for PayPal Express
if(!$current_user->ID) {
//get values from post
if(isset($_REQUEST['username']))
$username = trim(sanitize_text_field($_REQUEST['username']));
else
$username = "";
if(isset($_REQUEST['password'])) {
// Can't sanitize the password. Be careful.
$password = $_REQUEST['password']; //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
} else {
$password = "";
}
if(isset($_REQUEST['bemail']))
$bemail = sanitize_email($_REQUEST['bemail']);
else
$bemail = "";
//save to session
$_SESSION['pmpro_signup_username'] = $username;
$_SESSION['pmpro_signup_password'] = $password;
$_SESSION['pmpro_signup_email'] = $bemail;
}
if( !empty( $_REQUEST['tos'] ) ) {
$tospost = get_post( get_option( 'pmpro_tospage' ) );
$_SESSION['tos'] = array(
'post_id' => $tospost->ID,
'post_modified' => $tospost->post_modified,
);
}
//can use this hook to save some other variables to the session
// @deprecated 2.12.3
do_action("pmpro_paypalexpress_session_vars");
}
/**
* Review and Confirmation code.
*
* @since 1.8
*/
static function pmpro_checkout_confirmed($pmpro_confirmed)
{
global $pmpro_msg, $pmpro_msgt, $pmpro_level, $current_user, $pmpro_review, $pmpro_paypal_token, $discount_code, $bemail;
//PayPal Express Call Backs
if(!empty($_REQUEST['review']))
{
if(!empty($_REQUEST['PayerID']))
$_SESSION['payer_id'] = sanitize_text_field($_REQUEST['PayerID']);
if(!empty($_REQUEST['paymentAmount']))
$_SESSION['paymentAmount'] = sanitize_text_field($_REQUEST['paymentAmount']);
if(!empty($_REQUEST['currencyCodeType']))
$_SESSION['currCodeType'] = sanitize_text_field($_REQUEST['currencyCodeType']);
if(!empty($_REQUEST['paymentType']))
$_SESSION['paymentType'] = sanitize_text_field($_REQUEST['paymentType']);
$morder = new MemberOrder();
$morder->getMemberOrderByPayPalToken(sanitize_text_field($_REQUEST['token']));
// Pull checkout values from order meta.
pmpro_pull_checkout_data_from_order( $morder );
if( $morder->status === 'token' ){
$morder->Token = $morder->paypal_token; $pmpro_paypal_token = $morder->paypal_token;
if($morder->Token)
{
if($morder->Gateway->getExpressCheckoutDetails($morder))
{
$pmpro_review = true;
}
else
{
$pmpro_msg = $morder->error;
$pmpro_msgt = "pmpro_error";
}
}
else
{
$pmpro_msg = __("The PayPal Token was lost.", 'paid-memberships-pro' );
$pmpro_msgt = "pmpro_error";
}
}else{
$pmpro_msg = __("Checkout was already processed.", 'paid-memberships-pro' );
$pmpro_msgt = "pmpro_error";
}
}
if(empty($pmpro_msg) &&
(!empty($_REQUEST['confirm']) ||
(get_option('pmpro_paypalexpress_skip_confirmation') && $pmpro_review))
)
{
$morder = new MemberOrder();
$morder->getMemberOrderByPayPalToken(sanitize_text_field($_REQUEST['token']));
$morder->Token = $morder->paypal_token; $pmpro_paypal_token = $morder->paypal_token;
// Pull checkout values from order meta.
pmpro_pull_checkout_data_from_order( $morder );
if($morder->Token)
{
//set up values
$morder->membership_id = $pmpro_level->id;
$morder->membership_name = $pmpro_level->name;
$morder->discount_code = $discount_code;
$morder->InitialPayment = pmpro_round_price( $pmpro_level->initial_payment );
$morder->PaymentAmount = pmpro_round_price( $pmpro_level->billing_amount );
$morder->ProfileStartDate = date_i18n("Y-m-d\TH:i:s");
$morder->BillingPeriod = $pmpro_level->cycle_period;
$morder->BillingFrequency = $pmpro_level->cycle_number;
$morder->Email = $bemail;
//setup level var
$morder->getMembershipLevelAtCheckout();
//tax
$morder->subtotal = $morder->InitialPayment;
$morder->getTax();
if($pmpro_level->billing_limit)
$morder->TotalBillingCycles = $pmpro_level->billing_limit;
if(pmpro_isLevelTrial($pmpro_level))
{
$morder->TrialBillingPeriod = $pmpro_level->cycle_period;
$morder->TrialBillingFrequency = $pmpro_level->cycle_number;
$morder->TrialBillingCycles = $pmpro_level->trial_limit;
$morder->TrialAmount = pmpro_round_price( $pmpro_level->trial_amount );
}
if($morder->confirm())
{
$pmpro_confirmed = true;
}
else
{
$pmpro_msg = $morder->error;
$pmpro_msgt = "pmpro_error";
}
}
else
{
$pmpro_msg = __("The PayPal Token was lost.", 'paid-memberships-pro' );
$pmpro_msgt = "pmpro_error";
}
}
if(!empty($morder))
return array("pmpro_confirmed"=>$pmpro_confirmed, "morder"=>$morder);
else
return $pmpro_confirmed;
}
/**
* Swap in user/pass/etc from session
*
* @since 1.8
*/
static function pmpro_checkout_new_user_array($new_user_array)
{
global $current_user;
if(!$current_user->ID)
{
//reload the user fields
if( ! empty( $_SESSION['pmpro_signup_username'] ) ){
$new_user_array['user_login'] = $_SESSION['pmpro_signup_username'];
}
if( ! empty( $_SESSION['pmpro_signup_password'] ) ){
$new_user_array['user_pass'] = $_SESSION['pmpro_signup_password'];
}
if( ! empty( $_SESSION['pmpro_signup_email'] ) ){
$new_user_array['user_email'] = $_SESSION['pmpro_signup_email'];
}
//unset the user fields in session
unset($_SESSION['pmpro_signup_username']);
unset($_SESSION['pmpro_signup_password']);
unset($_SESSION['pmpro_signup_email']);
}
return $new_user_array;
}
/**
* Process at checkout
*
* Repurposed in v2.0. The old process() method is now confirm().
*/
function process(&$order)
{
$order->payment_type = "PayPal Express";
$order->cardtype = "";
$order->ProfileStartDate = pmpro_calculate_profile_start_date( $order, 'Y-m-d\TH:i:s\Z' );
return $this->setExpressCheckout($order);
}
/**
* Process charge or subscription after confirmation.
*
* @since 1.8
*/
function confirm(&$order)
{
if(pmpro_isLevelRecurring($order->membership_level))
{
$order->ProfileStartDate = pmpro_calculate_profile_start_date( $order, 'Y-m-d\TH:i:s\Z' );
return $this->subscribe($order);
}
else
return $this->charge($order);
}
/**
* Swap in our submit buttons.
*
* @since 1.8
*/
static function pmpro_checkout_default_submit_button($show)
{
global $gateway, $pmpro_requirebilling;
//show our submit buttons
?>
<span id="pmpro_paypalexpress_checkout" <?php if(($gateway != "paypalexpress" && $gateway != "paypalstandard") || !$pmpro_requirebilling) { ?>style="display: none;"<?php } ?>>
<input type="hidden" name="submit-checkout" value="1" />
<input type="image" id="pmpro_btn-submit-paypalexpress" class="<?php echo pmpro_get_element_class( 'pmpro_btn-submit-checkout' ); ?>" value="<?php esc_attr_e('Check Out with PayPal', 'paid-memberships-pro' );?>" src="<?php echo apply_filters("pmpro_paypal_button_image", "https://www.paypalobjects.com/webstatic/en_US/i/buttons/checkout-logo-medium.png");?>" />
</span>
<span id="pmpro_submit_span" <?php if(($gateway == "paypalexpress" || $gateway == "paypalstandard") && $pmpro_requirebilling) { ?>style="display: none;"<?php } ?>>
<input type="hidden" name="submit-checkout" value="1" />
<input type="submit" id="pmpro_btn-submit" class="<?php echo pmpro_get_element_class( 'pmpro_btn pmpro_btn-submit-checkout', 'pmpro_btn-submit-checkout' ); ?>" value="<?php if($pmpro_requirebilling) { _e('Submit and Check Out', 'paid-memberships-pro' ); } else { _e('Submit and Confirm', 'paid-memberships-pro' );}?>" />
</span>
<?php
//don't show the default
return false;
}
//PayPal Express, this is run first to authorize from PayPal
function setExpressCheckout(&$order)
{
global $pmpro_currency;
if(empty($order->code))
$order->code = $order->getRandomCode();
//clean up a couple values
$order->payment_type = "PayPal Express";
$order->CardType = "";
$order->cardtype = "";
//taxes on initial amount
$initial_payment = $order->InitialPayment;
$initial_payment_tax = $order->getTaxForPrice($initial_payment);
// Note: SetExpressCheckout expects this amount to be the total including tax.
$initial_payment = pmpro_round_price_as_string( (float) $initial_payment + (float) $initial_payment_tax );
//paypal profile stuff
$nvpStr = "";
$nvpStr .="&AMT=" . $initial_payment . "&CURRENCYCODE=" . $pmpro_currency;
if(!empty($order->ProfileStartDate) && strtotime($order->ProfileStartDate, current_time("timestamp")) > 0)
$nvpStr .= "&PROFILESTARTDATE=" . $order->ProfileStartDate;
if(!empty($order->BillingFrequency))
$nvpStr .= "&BILLINGPERIOD=" . $order->BillingPeriod . "&BILLINGFREQUENCY=" . $order->BillingFrequency . "&AUTOBILLOUTAMT=AddToNextBilling&L_BILLINGTYPE0=RecurringPayments";
$nvpStr .= "&DESC=" . urlencode( apply_filters( 'pmpro_paypal_level_description', substr($order->membership_level->name . " at " . get_bloginfo("name"), 0, 127), $order->membership_level->name, $order, get_bloginfo("name")) );
$nvpStr .= "&NOTIFYURL=" . urlencode( add_query_arg( 'action', 'ipnhandler', admin_url('admin-ajax.php') ) );
$nvpStr .= "&NOSHIPPING=1&L_BILLINGAGREEMENTDESCRIPTION0=" . urlencode( apply_filters( 'pmpro_paypal_level_description', substr($order->membership_level->name . " at " . get_bloginfo("name"), 0, 127), $order->membership_level->name, $order, get_bloginfo("name") ) ) . "&L_PAYMENTTYPE0=Any";
//if billing cycles are defined
if(!empty($order->TotalBillingCycles))
$nvpStr .= "&TOTALBILLINGCYCLES=" . $order->TotalBillingCycles;
//if a trial period is defined
if(!empty($order->TrialBillingPeriod))
{
$trial_amount = $order->TrialAmount;
$trial_tax = $order->getTaxForPrice($trial_amount);
// Note: SetExpressCheckout expects this amount to be the total including tax.
$trial_amount = pmpro_round_price_as_string( (float) $trial_amount + (float) $trial_tax );
$nvpStr .= "&TRIALBILLINGPERIOD=" . $order->TrialBillingPeriod . "&TRIALBILLINGFREQUENCY=" . $order->TrialBillingFrequency . "&TRIALAMT=" . $trial_amount;
}
if(!empty($order->TrialBillingCycles))
$nvpStr .= "&TRIALTOTALBILLINGCYCLES=" . $order->TrialBillingCycles;
if(!empty($order->discount_code))
{
$nvpStr .= "&ReturnUrl=" . urlencode(pmpro_url("checkout", "?pmpro_level=" . $order->membership_level->id . "&pmpro_discount_code=" . $order->discount_code . "&review=" . $order->code));
}
else
{
$nvpStr .= "&ReturnUrl=" . urlencode(pmpro_url("checkout", "?pmpro_level=" . $order->membership_level->id . "&review=" . $order->code));
}
$additional_parameters = apply_filters("pmpro_paypal_express_return_url_parameters", array());
if(!empty($additional_parameters))
{
foreach($additional_parameters as $key => $value)
$nvpStr .= urlencode("&" . $key . "=" . $value);
}
$nvpStr .= "&CANCELURL=" . urlencode(pmpro_url("levels"));
$account_optional = apply_filters('pmpro_paypal_account_optional', true);
if ($account_optional)
$nvpStr .= '&SOLUTIONTYPE=Sole&LANDINGPAGE=Billing';
$nvpStr = apply_filters("pmpro_set_express_checkout_nvpstr", $nvpStr, $order);
///echo str_replace("&", "&<br />", $nvpStr);
///exit;
$this->httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"])) {
$order->status = "token";
$order->paypal_token = urldecode($this->httpParsedResponseAr['TOKEN']);
//update order
$order->saveOrder();
// Save checkout information to order meta.
pmpro_save_checkout_data_to_order( $order );
/**
* Allow performing actions just before sending the user to the gateway to complete the payment.
*
* @since 2.6.5
*
* @param MemberOrder $order The new order with status = token.
*/
do_action( 'pmpro_before_commit_express_checkout', $order );
//redirect to paypal
$paypal_url = "https://www.paypal.com/webscr?cmd=_express-checkout&useraction=commit&token=" . $this->httpParsedResponseAr['TOKEN'];
$environment = get_option("pmpro_gateway_environment");
if("sandbox" === $environment || "beta-sandbox" === $environment)
{
$paypal_url = "https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&useraction=commit&token=" . $this->httpParsedResponseAr['TOKEN'];
}
wp_redirect($paypal_url);
exit;
//exit('SetExpressCheckout Completed Successfully: '.print_r($this->httpParsedResponseAr, true));
} else {
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']);
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
//exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
//write session?
//redirect to PayPal
}
function getExpressCheckoutDetails(&$order)
{
$nvpStr="&TOKEN=".$order->Token;
$nvpStr = apply_filters("pmpro_get_express_checkout_details_nvpstr", $nvpStr, $order);
/* Make the API call and store the results in an array. If the
call was a success, show the authorization details, and provide
an action to complete the payment. If failed, show the error
*/
$this->httpParsedResponseAr = $this->PPHttpPost('GetExpressCheckoutDetails', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"])) {
$order->status = "review";
//update order
$order->saveOrder();
return true;
} else {
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']);
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
//exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
}
function charge(&$order)
{
global $pmpro_currency;
if(empty($order->code))
$order->code = $order->getRandomCode();
//taxes on the amount
$amount = $order->InitialPayment;
$amount_tax = $order->getTaxForPrice($amount);
$order->subtotal = $amount;
// Note: DoExpressCheckoutPayment expects this amount to be the total including tax.
$amount = pmpro_round_price_as_string( (float) $amount + (float) $amount_tax );
//paypal profile stuff
$nvpStr = "";
if(!empty($order->Token))
$nvpStr .= "&TOKEN=" . $order->Token;
$nvpStr .="&AMT=" . $amount . "&CURRENCYCODE=" . $pmpro_currency;
/*
if(!empty($amount_tax))
$nvpStr .= "&TAXAMT=" . $amount_tax;
*/
if(!empty($order->BillingFrequency))
$nvpStr .= "&BILLINGPERIOD=" . $order->BillingPeriod . "&BILLINGFREQUENCY=" . $order->BillingFrequency . "&AUTOBILLOUTAMT=AddToNextBilling";
$nvpStr .= "&DESC=" . urlencode( apply_filters( 'pmpro_paypal_level_description', substr($order->membership_level->name . " at " . get_bloginfo("name"), 0, 127), $order->membership_level->name, $order, get_bloginfo("name")) );
$nvpStr .= "&NOTIFYURL=" . urlencode( add_query_arg( 'action', 'ipnhandler', admin_url('admin-ajax.php') ) );
$nvpStr .= "&NOSHIPPING=1";
$nvpStr .= "&PAYERID=" . $_SESSION['payer_id'] . "&PAYMENTACTION=sale";
$nvpStr = apply_filters("pmpro_do_express_checkout_payment_nvpstr", $nvpStr, $order);
$order->nvpStr = $nvpStr;
$this->httpParsedResponseAr = $this->PPHttpPost('DoExpressCheckoutPayment', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"])) {
$order->payment_transaction_id = urldecode($this->httpParsedResponseAr['TRANSACTIONID']);
$order->status = "success";
//update order
$order->saveOrder();
return true;
} else {
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']);
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
//exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true));
}
}
function subscribe(&$order)
{
global $pmpro_currency, $pmpro_review;
if(empty($order->code))
$order->code = $order->getRandomCode();
//filter order before subscription. use with care.
$order = apply_filters("pmpro_subscribe_order", $order, $this);
//taxes on initial amount
$initial_payment = $order->InitialPayment;
$initial_payment_tax = $order->getTaxForPrice($initial_payment);
// Note: CreateRecurringPaymentsProfile expects this amount to be the total including tax.
$initial_payment = pmpro_round_price_as_string( (float) $initial_payment + (float) $initial_payment_tax );
//taxes on the amount
$amount = $order->PaymentAmount;
$amount_tax = $order->getTaxForPrice( $amount );
// Note: CreateRecurringPaymentsProfile expects this amount to be the total excluding tax.
$amount = pmpro_round_price_as_string( $amount );
//paypal profile stuff
$nvpStr = "";
if(!empty($order->Token))
$nvpStr .= "&TOKEN=" . $order->Token;
$nvpStr .="&INITAMT=" . $initial_payment . "&AMT=" . $amount . "&CURRENCYCODE=" . $pmpro_currency . "&PROFILESTARTDATE=" . $order->ProfileStartDate;
if(!empty($amount_tax))
$nvpStr .= "&TAXAMT=" . pmpro_round_price_as_string( $amount_tax );
$nvpStr .= "&BILLINGPERIOD=" . $order->BillingPeriod . "&BILLINGFREQUENCY=" . $order->BillingFrequency . "&AUTOBILLOUTAMT=AddToNextBilling";
$nvpStr .= "&NOTIFYURL=" . urlencode( add_query_arg( 'action', 'ipnhandler', admin_url('admin-ajax.php') ) );
$nvpStr .= "&DESC=" . urlencode( apply_filters( 'pmpro_paypal_level_description', substr($order->membership_level->name . " at " . get_bloginfo("name"), 0, 127), $order->membership_level->name, $order, get_bloginfo("name")) );
//if billing cycles are defined
if(!empty($order->TotalBillingCycles))
$nvpStr .= "&TOTALBILLINGCYCLES=" . $order->TotalBillingCycles;
//if a trial period is defined
if(!empty($order->TrialBillingPeriod))
{
$trial_amount = $order->TrialAmount;
$trial_tax = $order->getTaxForPrice($trial_amount);
/*
* Note: For the CreateRecurringPaymentsProfile API call, it expects the TRIALAMT to be the total excluding taxes.
*
* However, there is no TRIALTAXAMT for trial periods so this is a workaround.
*/
$trial_amount = pmpro_round_price_as_string( (float) $trial_amount + (float) $trial_tax );
$nvpStr .= "&TRIALBILLINGPERIOD=" . $order->TrialBillingPeriod . "&TRIALBILLINGFREQUENCY=" . $order->TrialBillingFrequency . "&TRIALAMT=" . $trial_amount;
}
if(!empty($order->TrialBillingCycles))
$nvpStr .= "&TRIALTOTALBILLINGCYCLES=" . $order->TrialBillingCycles;
// Set MAXFAILEDPAYMENTS so subscriptions are cancelled after 1 failed payment.
$nvpStr .= "&MAXFAILEDPAYMENTS=1";
$nvpStr = apply_filters("pmpro_create_recurring_payments_profile_nvpstr", $nvpStr, $order);
//for debugging let's add this to the class object
$this->nvpStr = $nvpStr;
///echo str_replace("&", "&<br />", $nvpStr);
///exit;
$this->httpParsedResponseAr = $this->PPHttpPost('CreateRecurringPaymentsProfile', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"])) {
// PayPal docs says that PROFILESTATUS can be:
// 1. ActiveProfile — The recurring payment profile has been successfully created and activated for scheduled payments according the billing instructions from the recurring payments profile.
// 2. PendingProfile — The system is in the process of creating the recurring payment profile. Please check your IPN messages for an update.
// Also, we have seen that PROFILESTATUS can be missing. That case would be an error.
if(isset($this->httpParsedResponseAr["PROFILESTATUS"]) && in_array($this->httpParsedResponseAr["PROFILESTATUS"], array("ActiveProfile", "PendingProfile"))) {
$order->status = "success";
// this is wrong, but we don't know the real transaction id at this point
$order->payment_transaction_id = urldecode($this->httpParsedResponseAr['PROFILEID']);
$order->subscription_transaction_id = urldecode($this->httpParsedResponseAr['PROFILEID']);
//update order
$order->saveOrder();
return true;
} else {
// stop processing the review request on checkout page
$pmpro_review = false;
$order->status = "error";
// this is wrong, but we don't know the real transaction id at this point
$order->payment_transaction_id = urldecode($this->httpParsedResponseAr['PROFILEID']);
$order->subscription_transaction_id = urldecode($this->httpParsedResponseAr['PROFILEID']);
$order->errorcode = '';
$order->error = __( 'Something went wrong creating plan with PayPal; missing PROFILESTATUS.', 'paid-memberships-pro' );
$order->shorterror = __( 'Error creating plan with PayPal.', 'paid-memberships-pro' );
//update order
$order->saveOrder();
return false;
}
} else {
// stop processing the review request on checkout page
$pmpro_review = false;
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']);
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
}
}
function cancel(&$order) {
// Always cancel the order locally even if PayPal might fail
$order->updateStatus("cancelled");
// If we're processing an IPN request for this subscription, it's already cancelled at PayPal.
if ( ( ! empty( $_POST['subscr_id'] ) && $_POST['subscr_id'] == $order->subscription_transaction_id ) ||
( ! empty( $_POST['recurring_payment_id'] ) && $_POST['recurring_payment_id'] == $order->subscription_transaction_id ) ) {
// recurring_payment_failed transaction still need to be cancelled
if ( $_POST['txn_type'] !== 'recurring_payment_failed' ) {
return true;
}
}
// Cancel at gateway
return $this->cancelSubscriptionAtGateway($order);
}
function cancelSubscriptionAtGateway(&$order) {
// Build the nvp string for PayPal API
$nvpStr = "";
$nvpStr .= "&PROFILEID=" . urlencode($order->subscription_transaction_id) . "&ACTION=Cancel&NOTE=" . urlencode("User requested cancel.");
$nvpStr = apply_filters("pmpro_manage_recurring_payments_profile_status_nvpstr", $nvpStr, $order);
$this->httpParsedResponseAr = $this->PPHttpPost('ManageRecurringPaymentsProfileStatus', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"])) {
return true;
} else {
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']) . ". " . __("Please contact the site owner or cancel your subscription from within PayPal to make sure you are not charged going forward.", 'paid-memberships-pro' );
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
}
}
/**
* Cancels a subscription in PayPal.
*
* @param PMPro_Subscription $subscription to cancel.
*/
function cancel_subscription( $subscription ) {
// Build the nvp string for PayPal API
$nvpStr = '&PROFILEID=' . urlencode( $subscription->get_subscription_transaction_id() ) . '&ACTION=Cancel&NOTE=' . urlencode('User requested cancel.');
$this->httpParsedResponseAr = $this->PPHttpPost('ManageRecurringPaymentsProfileStatus', $nvpStr);
return ( 'SUCCESS' == strtoupper( $this->httpParsedResponseAr['ACK'] ) || 'SUCCESSWITHWARNING' == strtoupper( $this->httpParsedResponseAr['ACK'] ) );
}
function getSubscriptionStatus(&$order)
{
if(empty($order->subscription_transaction_id))
return false;
//paypal profile stuff
$nvpStr = "";
$nvpStr .= "&PROFILEID=" . urlencode($order->subscription_transaction_id);
$nvpStr = apply_filters("pmpro_get_recurring_payments_profile_details_nvpstr", $nvpStr, $order);
$this->httpParsedResponseAr = $this->PPHttpPost('GetRecurringPaymentsProfileDetails', $nvpStr);
if("SUCCESS" == strtoupper($this->httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($this->httpParsedResponseAr["ACK"]))
{
return $this->httpParsedResponseAr;
}
else
{
$order->errorcode = $this->httpParsedResponseAr['L_ERRORCODE0'];
$order->error = urldecode($this->httpParsedResponseAr['L_LONGMESSAGE0']);
$order->shorterror = urldecode($this->httpParsedResponseAr['L_SHORTMESSAGE0']);
return false;
}
}
/**
* Pull subscription info from PayPal.
*
* @param PMPro_Subscription $subscription to pull data for.
*
* @return string|null Error message is returned if update fails.
*/
function update_subscription_info( $subscription ) {
$subscription_transaction_id = $subscription->get_subscription_transaction_id();
if ( empty( $subscription_transaction_id ) ) {
return 'Subscription transaction ID is empty.';
}
// Get subscription information from PayPal.
$nvpStr = "";
$nvpStr .= "&PROFILEID=" . urlencode( $subscription_transaction_id );
$response = $this->PPHttpPost('GetRecurringPaymentsProfileDetails', $nvpStr);
// If the request failed, return the error message.
if ("SUCCESS" != strtoupper($response["ACK"]) && "SUCCESSWITHWARNING" != strtoupper($response["ACK"])) {
return __( 'Subscription could not be found.', 'paid-memberships-pro' );
}
// Found subscription.
$update_array = array();
// PayPal may or may not return the start date of the subscription.
if ( ! empty( $response['PROFILESTARTDATE'] ) ) {
$update_array['startdate'] = date_i18n( 'Y-m-d H:i:s', strtotime( $response['PROFILESTARTDATE'] ) );
} else {
$oldest_orders = $subscription->get_orders( [
'limit' => 1,
'orderby' => '`timestamp` ASC, `id` ASC',
] );
if ( ! empty( $oldest_orders ) ) {
$oldest_order = current( $oldest_orders );
$update_array['startdate'] = date_i18n( 'Y-m-d H:i:s', $oldest_order->getTimestamp( true ) );
}
}
if ( in_array( $response['STATUS'], array( 'Pending', 'Active' ), true ) ) {
// Subscription is active.
$update_array['status'] = 'active';
$update_array['next_payment_date'] = date( 'Y-m-d H:i:s', strtotime( $response['NEXTBILLINGDATE'] ) );
$update_array['billing_amount'] = floatval( $response['REGULARAMT'] );
$update_array['cycle_number'] = (int) $response['REGULARBILLINGFREQUENCY'];
$update_array['cycle_period'] = $response['REGULARBILLINGPERIOD'];
$update_array['trial_amount'] = empty( $response['TRIALAMT'] ) ? 0 : floatval( $response['TRIALAMT'] );
$update_array['trial_limit'] = empty( $response['TRIALTOTALBILLINGCYCLES'] ) ? 0 : (int) $response['TRIALTOTALBILLINGCYCLES'];
$update_array['billing_limit'] = empty( $response['REGULARTOTALBILLINGCYCLES'] ) ? 0 : (int) $response['REGULARTOTALBILLINGCYCLES'];
} else {
// Subscription is no longer active.
// Can't fill subscription end date, $request only has the date of the last payment.
$update_array['status'] = 'cancelled';
}
// Update the subscription.
$subscription->set( $update_array );
// Also use this opportunity to pull any missing subscription payments from PayPal.
// Start searching 5 years ago.
$nvpStr = "";
$nvpStr .= "&STARTDATE=" . urlencode( date( 'Y-m-d\TH:i:s\Z', strtotime( '-5 years' ) ) );
$nvpStr .= "&PROFILEID=" . urlencode( $subscription_transaction_id );
$nvpStr .= "&STATUS=Success";
$response = $this->PPHttpPost('TransactionSearch', $nvpStr);
// If the request failed, bail.
if ("SUCCESS" != strtoupper($response["ACK"]) && "SUCCESSWITHWARNING" != strtoupper($response["ACK"])) {
return;
}
// Loop through the transactions and add any payments that are missing.
$transaction_loop_index = 0;
while ( isset( $response[ "L_TRANSACTIONID{$transaction_loop_index}" ] ) ) {
$transaction_id = $response[ "L_TRANSACTIONID{$transaction_loop_index}" ];
$transaction_date = $response[ "L_TIMESTAMP{$transaction_loop_index}" ];