forked from wp-premium/gravityforms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-gf-payment-addon.php
More file actions
2298 lines (1786 loc) · 85.6 KB
/
Copy pathclass-gf-payment-addon.php
File metadata and controls
2298 lines (1786 loc) · 85.6 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
if ( ! class_exists( 'GFForms' ) ) {
die();
}
/**
* Specialist Add-On class designed for use by Add-Ons that collect payment
*
* @package GFPaymentAddOn
*
* NOTE: This class is still undergoing development and is not ready to be used on live sites.
*/
require_once( 'class-gf-feed-addon.php' );
abstract class GFPaymentAddOn extends GFFeedAddOn {
private $_payment_version = '1.2';
/**
* If set to true, user will not be able to create feeds for a form until a credit card field has been added.
* @var bool
*/
protected $_requires_credit_card = false;
/**
* If set to true, callbacks/webhooks/IPN will be enabled and the appropriate database table will be created.
* @var bool
*/
protected $_supports_callbacks = false;
protected $authorization = array();
protected $redirect_url = '';
protected $current_feed = false;
protected $current_submission_data = false;
protected $is_payment_gateway = false;
//--------- Initialization ----------
public function pre_init() {
parent::pre_init();
// Intercepting callback requests
add_action( 'parse_request', array( $this, 'maybe_process_callback' ) );
if ( $this->payment_method_is_overridden( 'check_status' ) ) {
$this->setup_cron();
}
}
public function init() {
parent::init();
add_filter( 'gform_confirmation', array( $this, 'confirmation' ), 20, 4 );
add_filter( 'gform_validation', array( $this, 'validation' ), 20 );
add_filter( 'gform_entry_post_save', array( $this, 'entry_post_save' ), 10, 2 );
}
public function init_admin() {
parent::init_admin();
//enables credit card field
add_filter( 'gform_enable_credit_card_field', '__return_true' );
add_filter( 'gform_currencies', array( $this, 'supported_currencies' ) );
add_filter( 'gform_delete_lead', array( $this, 'entry_deleted' ) );
if ( rgget( 'page' ) == 'gf_entries' ) {
add_action( 'gform_payment_details', array( $this, 'entry_info' ), 10, 2 );
add_action( 'gform_enable_entry_info_payment_details', array( $this, 'disable_entry_info_payment' ), 10, 2 );
add_filter( 'gform_notes_avatar', array( $this, 'notes_avatar' ), 10, 2 );
}
}
public function init_ajax() {
parent::init_ajax();
add_action( 'wp_ajax_gaddon_cancel_subscription', array( $this, 'ajax_cancel_subscription' ) );
add_action( 'gform_before_delete_field', array( $this, 'before_delete_field' ), 10, 2 );
}
protected function setup() {
parent::setup();
$installed_version = get_option( 'gravityformsaddon_payment_version' );
$installed_addons = get_option( 'gravityformsaddon_payment_addons' );
if ( ! is_array( $installed_addons ) ) {
$installed_addons = array();
}
if ( $installed_version != $this->_payment_version ) {
$this->upgrade_payment( $installed_version );
$installed_addons = array( $this->_slug );
update_option( 'gravityformsaddon_payment_addons', $installed_addons );
} elseif ( ! in_array( $this->_slug, $installed_addons ) ) {
$this->upgrade_payment( $installed_version );
$installed_addons[] = $this->_slug;
update_option( 'gravityformsaddon_payment_addons', $installed_addons );
}
update_option( 'gravityformsaddon_payment_version', $this->_payment_version );
}
private function upgrade_payment( $previous_versions ) {
global $wpdb;
$charset_collate = GFFormsModel::get_db_charset();
$sql = "CREATE TABLE {$wpdb->prefix}gf_addon_payment_transaction (
id int(10) unsigned not null auto_increment,
lead_id int(10) unsigned not null,
transaction_type varchar(30) not null,
transaction_id varchar(50),
is_recurring tinyint(1) not null default 0,
amount decimal(19,2),
date_created datetime,
PRIMARY KEY (id),
KEY lead_id (lead_id),
KEY transaction_type (transaction_type),
KEY type_lead (lead_id,transaction_type)
) $charset_collate;";
GFFormsModel::dbDelta( $sql );
if ( $this->_supports_callbacks ) {
$sql = "CREATE TABLE {$wpdb->prefix}gf_addon_payment_callback (
id int(10) unsigned not null auto_increment,
lead_id int(10) unsigned not null,
addon_slug varchar(250) not null,
callback_id varchar(250),
date_created datetime,
PRIMARY KEY (id),
KEY addon_slug_callback_id (addon_slug(50),callback_id(100))
) $charset_collate;";
GFFormsModel::dbDelta( $sql );
//droping legacy index
GFForms::drop_index( "{$wpdb->prefix}gf_addon_payment_callback", 'slug_callback_id' );
}
}
//--------- Submission Process ------
public function confirmation( $confirmation, $form, $entry, $ajax ) {
if ( empty( $this->redirect_url ) ) {
return $confirmation;
}
$confirmation = array( 'redirect' => $this->redirect_url );
return $confirmation;
}
/**
* Override this function to specify a URL to the third party payment processor. Useful when developing a payment gateway that processes the payment outsite of the website (i.e. PayPal Standard).
*
* @param $feed - Active payment feed containing all the configuration data
* @param $submission_data - Contains form field data submitted by the user as well as payment information (i.e. payment amount, setup fee, line items, etc...)
* @param $form - Current form array containing all form settings
* @param $entry - Current entry array containing entry information (i.e data submitted by users)
*
* @return string - Return a full URL (inlucing http:// or https://) to the payment processor
*/
protected function redirect_url( $feed, $submission_data, $form, $entry ) {
}
public function validation( $validation_result ) {
if ( ! $validation_result['is_valid'] || ! GFFormDisplay::is_last_page( $validation_result['form'] ) ) {
return $validation_result;
}
$form = $validation_result['form'];
$entry = GFFormsModel::create_lead( $form );
$feed = $this->get_payment_feed( $entry, $form );
if ( ! $feed ) {
return $validation_result;
}
$submission_data = $this->get_submission_data( $feed, $form, $entry );
//Do not process payment if payment amount is 0
if ( floatval( $submission_data['payment_amount'] ) <= 0 ) {
$this->log_debug( __METHOD__ . '(): Payment amount is $0.00 or less. Not sending to payment gateway.' );
return $validation_result;
}
$this->is_payment_gateway = true;
$this->current_feed = $feed;
$this->current_submission_data = $submission_data;
$performed_authorization = false;
$is_subscription = $feed['meta']['transactionType'] == 'subscription';
if ( $this->payment_method_is_overridden( 'authorize' ) && ! $is_subscription ) {
//Running an authorization only transaction if function is implemented and this is a single payment
$this->authorization = $this->authorize( $feed, $submission_data, $form, $entry );
$performed_authorization = true;
} elseif ( $this->payment_method_is_overridden( 'subscribe' ) && $is_subscription ) {
$subscription = $this->subscribe( $feed, $submission_data, $form, $entry );
$this->authorization['is_authorized'] = $subscription['is_success'];
$this->authorization['error_message'] = rgar( $subscription, 'error_message' );
$this->authorization['subscription'] = $subscription;
$performed_authorization = true;
}
if ( $performed_authorization ) {
$this->log_debug( __METHOD__ . "(): Authorization result for form #{$form['id']} submission => " . print_r( $this->authorization, 1 ) );
}
if ( $performed_authorization && ! $this->authorization['is_authorized'] ) {
$validation_result = $this->get_validation_result( $validation_result, $this->authorization );
//Setting up current page to point to the credit card page since that will be the highlighted field
GFFormDisplay::set_current_page( $validation_result['form']['id'], $validation_result['credit_card_page'] );
}
return $validation_result;
}
/**
* Override this method to add integration code to the payment processor in order to authorize a credit card with or without capturing payment. This method is executed during the form validation process and allows
* the form submission process to fail with a validation error if there is anything wrong with the payment/authorization. This method is only supported by single payments.
* For subscriptions or recurring payments, use the subscribe() method.
*
* @param $feed - Current configured payment feed
* @param $submission_data - Contains form field data submitted by the user as well as payment information (i.e. payment amount, setup fee, line items, etc...)
* @param $form - Current form array containing all form settings
* @param $entry - Current entry array containing entry information (i.e data submitted by users). NOTE: the entry hasn't been saved to the database at this point, so this $entry object does not have the 'ID' property and is only a memory representation of the entry.
*
* @return array - Return an $authorization array in the following format:
* [
* 'is_authorized' => true|false,
* 'error_message' => 'Error message',
* 'transaction_id' => 'XXX',
*
* //If the payment is captured in this method, return a 'captured_payment' array with the following information about the payment
* 'captured_payment' => ['is_success'=>true|false, 'error_message' => 'error message', 'transaction_id' => 'xxx', 'amount' => 20]
* ]
*/
protected function authorize( $feed, $submission_data, $form, $entry ) {
}
/**
* Override this method to capture a single payment that has been authorized via the authorize() method. Use only with single payments. For subscriptions, use subscribe() instead.
*
* @param $authorization - Contains the result of the authorize() function
* @param $feed - Current configured payment feed
* @param $submission_data - Contains form field data submitted by the user as well as payment information (i.e. payment amount, setup fee, line items, etc...)
* @param $form - Current form array containing all form settings
* @param $entry - Current entry array containing entry information (i.e data submitted by users).
*
* @return array - Return an array with the information about the captured payment in the following format:
* [
* 'is_success'=>true|false,
* 'error_message' => 'error message',
* 'transaction_id' => 'xxx',
* 'amount' => 20,
* 'payment_method' => 'Visa'
* ]
*/
protected function capture( $authorization, $feed, $submission_data, $form, $entry ) {
}
/**
* Override this method to add integration code to the payment processor in order to create a subscription. This method is executed during the form validation process and allows
* the form submission process to fail with a validation error if there is anything wrong when creating the subscription.
*
* @param $feed - Current configured payment feed
* @param $submission_data - Contains form field data submitted by the user as well as payment information (i.e. payment amount, setup fee, line items, etc...)
* @param $form - Current form array containing all form settings
* @param $entry - Current entry array containing entry information (i.e data submitted by users). NOTE: the entry hasn't been saved to the database at this point, so this $entry object does not have the 'ID' property and is only a memory representation of the entry.
*
* @return array - Return an $subscription array in the following format:
* [
* 'is_success'=>true|false,
* 'error_message' => 'error message',
* 'subscription_id' => 'xxx',
* 'amount' => 10
*
* //To implement an initial/setup fee for gateways that don't support setup fees as part of subscriptions, manually capture the funds for the setup fee as a separate transaction and send that payment
* //information in the following 'captured_payment' array
* 'captured_payment' => ['name' => 'Setup Fee', 'is_success'=>true|false, 'error_message' => 'error message', 'transaction_id' => 'xxx', 'amount' => 20]
* ]
*/
protected function subscribe( $feed, $submission_data, $form, $entry ) {
}
/**
* Override this method to add integration code to the payment processor in order to cancel a subscription. This method is executed when a subscription is canceled from the Payment Gateway (i.e. Stripe or PayPal)
*
* @param $entry - Current entry array containing entry information (i.e data submitted by users).
* @param $feed - Current configured payment feed
*
* @return bool - Returns true if the subscription was cancelled successfully and false otherwise.
*
*/
protected function cancel( $entry, $feed ) {
return false;
}
protected function get_validation_result( $validation_result, $authorization_result ) {
$credit_card_page = 0;
foreach ( $validation_result['form']['fields'] as &$field ) {
if ( $field['type'] == 'creditcard' ) {
$field['failed_validation'] = true;
$field['validation_message'] = $authorization_result['error_message'];
$credit_card_page = $field['pageNumber'];
break;
}
}
$validation_result['credit_card_page'] = $credit_card_page;
$validation_result['is_valid'] = false;
return $validation_result;
}
public function entry_post_save( $entry, $form ) {
if ( ! $this->is_payment_gateway ) {
return $entry;
}
$feed = $this->current_feed;
if ( ! empty( $this->authorization ) ) {
//If an authorization was done, capture it
if ( $feed['meta']['transactionType'] == 'subscription' ) {
$entry = $this->process_subscription( $this->authorization, $feed, $this->current_submission_data, $form, $entry );
} else {
if ( $this->payment_method_is_overridden( 'capture' ) && rgempty( 'captured_payment', $this->authorization ) ) {
$this->authorization['captured_payment'] = $this->capture( $this->authorization, $feed, $this->current_submission_data, $form, $entry );
}
$entry = $this->process_capture( $this->authorization, $feed, $this->current_submission_data, $form, $entry );
}
} elseif ( $this->payment_method_is_overridden( 'redirect_url' ) ) {
//If the url_redirect() function is overridden, call it.
//Getting URL to redirect to ( saved to be used by the confirmation() function )
$this->redirect_url = $this->redirect_url( $feed, $this->current_submission_data, $form, $entry );
//Setting transaction_type to subscription or one time payment
$entry['transaction_type'] = rgars( $feed, 'meta/transactionType' ) == 'subscription' ? 2 : 1;
$entry['payment_status'] = 'Processing';
}
//Saving which gateway was used to process this entry
gform_update_meta( $entry['id'], 'payment_gateway', $this->_slug );
return $entry;
}
protected function process_capture( $authorization, $feed, $submission_data, $form, $entry ) {
$payment = rgar( $authorization, 'captured_payment' );
if ( empty( $payment ) ) {
return $entry;
}
$this->log_debug( __METHOD__ . "(): Updating entry #{$entry['id']} with result => " . print_r( $payment, 1 ) );
if ( $payment['is_success'] ) {
$entry['is_fulfilled'] = '1';
$payment['payment_status'] = 'Paid';
$payment['payment_date'] = gmdate( 'Y-m-d H:i:s' );
$this->complete_payment( $entry, $payment );
} else {
$entry['payment_status'] = 'Failed';
$this->add_note( $entry['id'], sprintf( esc_html__( 'Payment failed to be captured. Reason: %s', 'gravityforms' ), $payment['error_message'] ), 'error' );
GFAPI::update_entry( $entry );
}
return $entry;
}
protected function process_subscription( $authorization, $feed, $submission_data, $form, $entry ) {
$subscription = rgar( $authorization, 'subscription' );
if ( empty( $subscription ) ) {
return $entry;
}
$this->log_debug( __METHOD__ . "(): Updating entry #{$entry['id']} with result => " . print_r( $subscription, 1 ) );
// if setup fee / trial is captured as part of a separate transaction
$payment = rgar( $subscription, 'captured_payment' );
$payment_name = rgempty( 'name', $payment ) ? esc_html__( 'Initial payment', 'gravityforms' ) : $payment['name'];
if ( $payment && $payment['is_success'] ) {
$this->insert_transaction( $entry['id'], 'payment', $payment['transaction_id'], $payment['amount'], false );
$amount_formatted = GFCommon::to_money( $payment['amount'], $entry['currency'] );
$note = sprintf( esc_html__( '%s has been captured successfully. Amount: %s. Transaction Id: %s', 'gravityforms' ), $payment_name, $amount_formatted, $payment['transaction_id'] );
$this->add_note( $entry['id'], $note, 'success' );
} elseif ( $payment && ! $payment['is_success'] ) {
$this->add_note( $entry['id'], sprintf( esc_html__( 'Failed to capture %s. Reason: %s.', 'gravityforms' ), $payment['error_message'], $payment_name ), 'error' );
}
// updating subscription information
if ( $subscription['is_success'] ) {
$entry = $this->start_subscription( $entry, $subscription );
} else {
$entry['payment_status'] = 'Failed';
GFAPI::update_entry( $entry );
$this->add_note( $entry['id'], sprintf( esc_html__( 'Subscription failed to be created. Reason: %s', 'gravityforms' ), $subscription['error_message'] ), 'error' );
}
return $entry;
}
protected function insert_transaction( $entry_id, $transaction_type, $transaction_id, $amount, $is_recurring = null ) {
global $wpdb;
// @todo: make sure stats does not show setup fee as a recurring payment
$payment_count = $wpdb->get_var( $wpdb->prepare( "SELECT count(id) FROM {$wpdb->prefix}gf_addon_payment_transaction WHERE lead_id=%d", $entry_id ) );
$is_recurring = $payment_count > 0 && $transaction_type == 'payment' ? 1 : 0;
$sql = $wpdb->prepare(
" INSERT INTO {$wpdb->prefix}gf_addon_payment_transaction (lead_id, transaction_type, transaction_id, amount, is_recurring, date_created)
values(%d, %s, %s, %f, %d, utc_timestamp())", $entry_id, $transaction_type, $transaction_id, $amount, $is_recurring
);
$wpdb->query( $sql );
$txn_id = $wpdb->insert_id;
do_action( 'gform_post_payment_transaction', $txn_id, $entry_id, $transaction_type, $transaction_id, $amount, $is_recurring );
if ( has_filter( 'gform_post_payment_transaction' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_post_payment_transaction.' );
}
return $txn_id;
}
public function get_payment_feed( $entry, $form = false ) {
$submission_feed = false;
if ( $entry['id'] ) {
$feeds = $this->get_feeds_by_entry( $entry['id'] );
$submission_feed = empty( $feeds ) ? false : $this->get_feed( $feeds[0] );
} elseif ( $form ) {
// getting all feeds
$feeds = $this->get_feeds( $form['id'] );
foreach ( $feeds as $feed ) {
if ( $feed['is_active'] && $this->is_feed_condition_met( $feed, $form, $entry ) ) {
$submission_feed = $feed;
break;
}
}
}
return $submission_feed;
}
protected function is_payment_gateway( $entry_id ) {
if ( $this->is_payment_gateway ){
return true;
}
$gateway = gform_get_meta( $entry_id, 'payment_gateway' );
return $gateway == $this->_slug;
}
protected function get_submission_data( $feed, $form, $entry ) {
$form_data = array();
$form_data['form_title'] = $form['title'];
//getting mapped field data
$billing_fields = $this->billing_info_fields();
foreach ( $billing_fields as $billing_field ) {
$field_name = $billing_field['name'];
$input_id = rgar( $feed['meta'], "billingInformation_{$field_name}" );
$form_data[ $field_name ] = rgar( $entry, $input_id );
}
//getting credit card field data
$card_field = $this->get_credit_card_field( $form );
if ( $card_field ) {
$form_data['card_number'] = $this->remove_spaces_from_card_number( rgpost( "input_{$card_field['id']}_1" ) );
$form_data['card_expiration_date'] = rgpost( "input_{$card_field['id']}_2" );
$form_data['card_security_code'] = rgpost( "input_{$card_field['id']}_3" );
$form_data['card_name'] = rgpost( "input_{$card_field['id']}_5" );
}
//getting product field data
$order_info = $this->get_order_data( $feed, $form, $entry );
$form_data = array_merge( $form_data, $order_info );
return $form_data;
}
protected function get_credit_card_field( $form ) {
$fields = GFAPI::get_fields_by_type( $form, array( 'creditcard' ) );
return empty( $fields ) ? false : $fields[0];
}
protected function has_credit_card_field( $form ) {
return $this->get_credit_card_field( $form ) !== false;
}
protected function get_order_data( $feed, $form, $entry ) {
$products = GFCommon::get_product_fields( $form, $entry );
$payment_field = $feed['meta']['transactionType'] == 'product' ? rgars( $feed, 'meta/paymentAmount' ) : rgars( $feed, 'meta/recurringAmount' );
$setup_fee_field = rgar( $feed['meta'], 'setupFee_enabled' ) ? $feed['meta']['setupFee_product'] : false;
$trial_field = rgar( $feed['meta'], 'trial_enabled' ) ? rgars( $feed, 'meta/trial_product' ) : false;
$amount = 0;
$line_items = array();
$discounts = array();
$fee_amount = 0;
$trial_amount = 0;
foreach ( $products['products'] as $field_id => $product ) {
$quantity = $product['quantity'] ? $product['quantity'] : 1;
$product_price = GFCommon::to_number( $product['price'] );
$options = array();
if ( is_array( rgar( $product, 'options' ) ) ) {
foreach ( $product['options'] as $option ) {
$options[] = $option['option_name'];
$product_price += $option['price'];
}
}
$is_trial_or_setup_fee = false;
if ( ! empty( $trial_field ) && $trial_field == $field_id ) {
$trial_amount = $product_price * $quantity;
$is_trial_or_setup_fee = true;
} elseif ( ! empty( $setup_fee_field ) && $setup_fee_field == $field_id ) {
$fee_amount = $product_price * $quantity;
$is_trial_or_setup_fee = true;
}
//Do not add to line items if the payment field selected in the feed is not the current field.
if ( is_numeric( $payment_field ) && $payment_field != $field_id ) {
continue;
}
//Do not add to line items if the payment field is set to "Form Total" and the current field was used for trial or setup fee.
if ( $is_trial_or_setup_fee && ! is_numeric( $payment_field ) ) {
continue;
}
$amount += $product_price * $quantity;
$description = '';
if ( ! empty( $options ) ) {
$description = esc_html__( 'options: ', 'gravityforms' ) . ' ' . implode( ', ', $options );
}
if ( $product_price >= 0 ) {
$line_items[] = array( 'id' => $field_id, 'name' => $product['name'], 'description' => $description, 'quantity' => $quantity, 'unit_price' => GFCommon::to_number( $product_price ), 'options' => rgar( $product, 'options' ) );
} else {
$discounts[] = array( 'id' => $field_id, 'name' => $product['name'], 'description' => $description, 'quantity' => $quantity, 'unit_price' => GFCommon::to_number( $product_price ), 'options' => rgar( $product, 'options' ) );
}
}
if ( $trial_field == 'enter_amount' ) {
$trial_amount = rgar($feed["meta"], "trial_amount") ? GFCommon::to_number(rgar($feed["meta"], "trial_amount")) : 0;
}
if ( ! empty( $products['shipping']['name'] ) && ! is_numeric( $payment_field ) ) {
$line_items[] = array( 'id' => '', 'name' => $products['shipping']['name'], 'description' => '', 'quantity' => 1, 'unit_price' => GFCommon::to_number( $products['shipping']['price'] ), 'is_shipping' => 1 );
$amount += $products['shipping']['price'];
}
return array( 'payment_amount' => $amount, 'setup_fee' => $fee_amount, 'trial' => $trial_amount, 'line_items' => $line_items, 'discounts' => $discounts );
}
protected function is_callback_valid() {
if ( rgget( 'callback' ) != $this->_slug ) {
return false;
}
return true;
}
//--------- Callback (aka Webhook)----------------
public function maybe_process_callback() {
// ignoring requests that are not this addon's callbacks
if ( ! $this->is_callback_valid() ) {
return;
}
// returns either false or an array of data about the callback request which payment add-on will then use
// to generically process the callback data
$this->log_debug( __METHOD__ . '(): Initializing callback processing for: ' . $this->_slug );
$callback_action = $this->callback();
$this->log_debug( __METHOD__ . '(): Result from gateway callback => ' . print_r( $callback_action, true ) );
$result = false;
if ( is_wp_error( $callback_action ) ) {
$this->display_callback_error( $callback_action );
} elseif ( $callback_action && is_array( $callback_action ) && rgar( $callback_action, 'type' ) && ! rgar( $callback_action, 'abort_callback' ) ) {
$result = $this->process_callback_action( $callback_action );
$this->log_debug( __METHOD__ . '(): Result of callback action => ' . print_r( $result, true ) );
if ( is_wp_error( $result ) ) {
$this->display_callback_error( $result );
} elseif ( ! $result ) {
status_header( 200 );
echo 'Callback could not be processed.';
} else {
status_header( 200 );
echo 'Callback processed successfully.';
}
} else {
status_header( 200 );
echo 'Callback bypassed';
}
$this->post_callback( $callback_action, $result );
die();
}
private function display_callback_error( $error ) {
$data = $error->get_error_data();
$status = ! rgempty( 'status_header', $data ) ? $data['status_header'] : 200;
status_header( $status );
echo $error->get_error_message();
}
/**
* Processes callback based on provided data.
*
* $action = array(
* 'type' => 'cancel_subscription', // required
* 'transaction_id' => '', // required (if payment)
* 'subscription_id' => '', // required (if subscription)
* 'amount' => '0.00', // required (some exceptions)
* 'entry_id' => 1, // required (some exceptions)
* 'transaction_type' => '',
* 'payment_status' => '',
* 'note' => ''
* );
*
* @param array $action
* @return mixed
*/
private function process_callback_action( $action ) {
$this->log_debug( __METHOD__ . '(): Processing callback action.' );
$action = wp_parse_args(
$action, array(
'type' => false,
'amount' => false,
'transaction_type' => false,
'transaction_id' => false,
'subscription_id' => false,
'entry_id' => false,
'payment_status' => false,
'note' => false,
)
);
$result = false;
if ( rgar( $action, 'id' ) && $this->is_duplicate_callback( $action['id'] ) ) {
return new WP_Error( 'duplicate', sprintf( esc_html__( 'This webhook has already been processed (Event Id: %s)', 'gravityforms' ), $action['id'] ) );
}
$entry = GFAPI::get_entry( $action['entry_id'] );
if ( ! $entry || is_wp_error( $entry ) ) {
return $result;
}
//$action = do_action('gform_action_pre_payment_callback', $action, $entry);
do_action( 'gform_action_pre_payment_callback', $action, $entry );
if ( has_filter( 'gform_action_pre_payment_callback' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_action_pre_payment_callback.' );
}
switch ( $action['type'] ) {
case 'complete_payment':
$result = $this->complete_payment( $entry, $action );
break;
case 'refund_payment':
$result = $this->refund_payment( $entry, $action );
break;
case 'fail_payment':
$result = $this->fail_payment( $entry, $action );
break;
case 'add_pending_payment':
$result = $this->add_pending_payment( $entry, $action );
break;
case 'void_authorization':
$result = $this->void_authorization( $entry, $action );
break;
case 'create_subscription':
$result = $this->start_subscription( $entry, $action );
$result = rgar( $result, 'payment_status' ) == 'Active' && rgar( $result, 'transaction_id' ) == rgar( $action, 'subscription_id' );
break;
case 'cancel_subscription':
$feed = $this->get_payment_feed( $entry );
$result = $this->cancel_subscription( $entry, $feed, $action['note'] );
break;
case 'expire_subscription':
$result = $this->expire_subscription( $entry, $action );
break;
case 'add_subscription_payment':
$result = $this->add_subscription_payment( $entry, $action );
break;
case 'fail_subscription_payment':
$result = $this->fail_subscription_payment( $entry, $action );
break;
default:
// handle custom events
if ( is_callable( array( $this, rgar( $action, 'callback' ) ) ) ) {
$result = call_user_func_array( array( $this, $action['callback'] ), array( $entry, $action ) );
}
break;
}
if ( rgar( $action, 'id' ) && $result ) {
$this->register_callback( $action['id'], $action['entry_id'] );
}
do_action( 'gform_post_payment_callback', $entry, $action, $result );
if ( has_filter( 'gform_post_payment_callback' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_post_payment_callback.' );
}
return $result;
}
protected function register_callback( $callback_id, $entry_id ) {
global $wpdb;
$wpdb->insert( "{$wpdb->prefix}gf_addon_payment_callback", array( 'addon_slug' => $this->_slug, 'callback_id' => $callback_id, 'lead_id' => $entry_id, 'date_created' => gmdate( 'Y-m-d H:i:s' ) ) );
}
protected function is_duplicate_callback( $callback_id ) {
global $wpdb;
$sql = $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}gf_addon_payment_callback WHERE addon_slug=%s AND callback_id=%s", $this->_slug, $callback_id );
if ( $wpdb->get_var( $sql ) ) {
return true;
}
return false;
}
protected function callback() {
}
protected function post_callback( $callback_action, $result ) {
}
// # PAYMENT INTERACTION FUNCTIONS
public function add_pending_payment( $entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $action['payment_status'] ) {
$action['payment_status'] = 'Pending';
}
if ( ! $action['note'] ) {
$amount_formatted = GFCommon::to_money( $action['amount'], $entry['currency'] );
$action['note'] = sprintf( esc_html__( 'Payment is pending. Amount: %s. Transaction Id: %s.', 'gravityforms' ), $amount_formatted, $action['transaction_id'] );
}
GFAPI::update_entry_property( $entry['id'], 'payment_status', $action['payment_status'] );
$this->add_note( $entry['id'], $action['note'] );
return true;
}
public function complete_payment( &$entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! rgar( $action, 'payment_status' ) ) {
$action['payment_status'] = 'Paid';
}
if ( ! rgar( $action, 'transaction_type' ) ) {
$action['transaction_type'] = 'payment';
}
if ( ! rgar( $action, 'payment_date' ) ) {
$action['payment_date'] = gmdate( 'y-m-d H:i:s' );
}
$entry['is_fulfilled'] = '1';
$entry['transaction_id'] = rgar( $action, 'transaction_id' );
$entry['transaction_type'] = '1';
$entry['payment_status'] = $action['payment_status'];
$entry['payment_amount'] = rgar( $action, 'amount' );
$entry['payment_date'] = $action['payment_date'];
$entry['payment_method'] = rgar( $action, 'payment_method' );
$entry['currency'] = GFCommon::get_currency();
if ( ! rgar( $action, 'note' ) ) {
$amount_formatted = GFCommon::to_money( $action['amount'], $entry['currency'] );
$action['note'] = sprintf( esc_html__( 'Payment has been completed. Amount: %s. Transaction Id: %s.', 'gravityforms' ), $amount_formatted, $action['transaction_id'] );
}
GFAPI::update_entry( $entry );
$this->insert_transaction( $entry['id'], $action['transaction_type'], $action['transaction_id'], $action['amount'] );
$this->add_note( $entry['id'], $action['note'], 'success' );
do_action( 'gform_post_payment_completed', $entry, $action );
if ( has_filter( 'gform_post_payment_completed' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_post_payment_completed.' );
}
return true;
}
public function refund_payment( $entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $action['payment_status'] ) {
$action['payment_status'] = 'Refunded';
}
if ( ! $action['transaction_type'] ) {
$action['transaction_type'] = 'refund';
}
if ( ! $action['note'] ) {
$amount_formatted = GFCommon::to_money( $action['amount'], $entry['currency'] );
$action['note'] = sprintf( esc_html__( 'Payment has been refunded. Amount: %s. Transaction Id: %s.', 'gravityforms' ), $amount_formatted, $action['transaction_id'] );
}
GFAPI::update_entry_property( $entry['id'], 'payment_status', $action['payment_status'] );
$this->insert_transaction( $entry['id'], $action['transaction_type'], $action['transaction_id'], $action['amount'] );
$this->add_note( $entry['id'], $action['note'] );
do_action( 'gform_post_payment_refunded', $entry, $action );
if ( has_filter( 'gform_post_payment_refunded' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_post_payment_refunded.' );
}
return true;
}
public function fail_payment( $entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $action['payment_status'] ) {
$action['payment_status'] = 'Failed';
}
if ( ! $action['note'] ) {
$amount_formatted = GFCommon::to_money( $action['amount'], $entry['currency'] );
$action['note'] = sprintf( esc_html__( 'Payment has failed. Amount: %s.', 'gravityforms' ), $amount_formatted );
}
GFAPI::update_entry_property( $entry['id'], 'payment_status', $action['payment_status'] );
$this->add_note( $entry['id'], $action['note'] );
return true;
}
public function void_authorization( $entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $action['payment_status'] ) {
$action['payment_status'] = 'Voided';
}
if ( ! $action['note'] ) {
$action['note'] = sprintf( esc_html__( 'Authorization has been voided. Transaction Id: %s', 'gravityforms' ), $action['transaction_id'] );
}
GFAPI::update_entry_property( $entry['id'], 'payment_status', $action['payment_status'] );
$this->add_note( $entry['id'], $action['note'] );
return true;
}
/**
* Used to start a new subscription. Updates the associcated entry with the payment and transaction details and adds an entry note.
*
* @param [array] $entry Entry object
* @param [string] $subscription_id ID of the subscription
* @param [float] $amount Numeric amount of the initial subscription payment
*
* @return [array] $entry Entry Object
*/
public function start_subscription( $entry, $subscription ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $this->has_subscription( $entry ) ) {
$entry['payment_status'] = 'Active';
$entry['payment_amount'] = $subscription['amount'];
$entry['payment_date'] = gmdate( 'y-m-d H:i:s' );
$entry['transaction_id'] = $subscription['subscription_id'];
$entry['transaction_type'] = '2'; // subscription
$entry['is_fulfilled'] = '1';
$result = GFAPI::update_entry( $entry );
$this->add_note( $entry['id'], sprintf( esc_html__( 'Subscription has been created. Subscription Id: %s.', 'gravityforms' ), $subscription['subscription_id'] ), 'success' );
do_action( 'gform_post_subscription_started', $entry, $subscription );
if ( has_filter( 'gform_post_subscription_started' ) ) {
$this->log_debug( __METHOD__ . '(): Executing functions hooked to gform_post_subscription_started.' );
}
}
return $entry;
}
/**
* A payment on an existing subscription.
*
* @param [array] $data Transaction data including 'amount' and 'subscriber_id'
* @param [array] $entry Entry object
*
* @return true
*/
public function add_subscription_payment( $entry, $action ) {
$this->log_debug( __METHOD__ . '(): Processing request.' );
if ( ! $action['transaction_type'] ) {
$action['transaction_type'] = 'payment';
}
if ( ! $action['note'] ) {
$amount_formatted = GFCommon::to_money( $action['amount'], $entry['currency'] );
$action['note'] = sprintf( esc_html__( 'Subscription has been paid. Amount: %s. Subscription Id: %s', 'gravityforms' ), $amount_formatted, $action['subscription_id'] );
}