-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass-gf-chip.php
More file actions
1575 lines (1359 loc) · 56.2 KB
/
class-gf-chip.php
File metadata and controls
1575 lines (1359 loc) · 56.2 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
/**
* GF_Chip addon class for CHIP payment gateway.
*
* @package GravityFormsCHIP
*/
defined( 'ABSPATH' ) || die();
GFForms::include_payment_addon_framework();
/**
* Gravity Forms addon for CHIP payment gateway.
*
* Handles global and per-form configuration, payment creation, callbacks, and refunds.
*
* @package GravityFormsCHIP
*/
class GF_Chip extends GFPaymentAddOn {
/**
* Singleton instance.
*
* @var GF_Chip|null
*/
private static $_instance = null;
/**
* Plugin main file path (chip-for-gravity-forms.php). Used for base path/URL and plugin identity.
*
* @var string
*/
protected $_full_path;
/**
* Addon slug.
*
* @var string
*/
protected $_slug = 'gravityformschip';
/**
* Addon title.
*
* @var string
*/
protected $_title = 'CHIP for Gravity Forms';
/**
* Short title for menu.
*
* @var string
*/
protected $_short_title = 'CHIP';
/**
* Whether addon supports payment callbacks.
*
* @var bool
*/
protected $_supports_callbacks = true;
/**
* Capability names.
*
* @var array<string>
*/
protected $_capabilities = array( 'gravityforms_chip', 'gravityforms_chip_uninstall' );
/**
* Capability for settings page.
*
* @var string
*/
protected $_capabilities_settings_page = 'gravityforms_chip';
/**
* Capability for form settings.
*
* @var string
*/
protected $_capabilities_form_settings = 'gravityforms_chip';
/**
* Capability for uninstall.
*
* @var string
*/
protected $_capabilities_uninstall = 'gravityforms_chip_uninstall';
/**
* Constructor.
*/
public function __construct() {
$this->_full_path = defined( 'GF_CHIP_PLUGIN_FILE' ) ? GF_CHIP_PLUGIN_FILE : __FILE__;
parent::__construct();
}
/**
* Returns the singleton instance.
*
* @return GF_Chip
*/
public static function get_instance() {
if ( null === self::$_instance ) {
self::$_instance = new GF_Chip();
}
return self::$_instance;
}
/**
* Runs before init. Registers actions for thank-you page and AJAX handlers.
*/
public function pre_init() {
// Inspired by gravityformsstripe.
add_action( 'wp', array( $this, 'maybe_thankyou_page' ), 5 );
add_action( 'wp_ajax_gf_chip_refund_payment', array( $this, 'chip_refund_payment' ), 10, 0 );
add_action( 'wp_ajax_gf_chip_get_global_credentials', array( $this, 'ajax_get_global_credentials' ), 10, 0 );
parent::pre_init();
}
/**
* Runs on init. Registers payment callback handler.
*/
public function init() {
parent::init();
add_action( 'gform_post_payment_callback', array( $this, 'handle_post_payment_callback' ), 10, 3 );
add_action( 'gform_post_save_feed_settings', array( $this, 'maybe_store_public_key_on_feed_save' ), 10, 4 );
}
/**
* Config for post-payment actions position.
*
* @param string $feed_slug Feed slug.
* @return array
*/
public function get_post_payment_actions_config( $feed_slug ) {
return array(
'position' => 'before',
'setting' => 'conditionalLogic',
);
}
/**
* Supported currencies for CHIP (MYR).
*
* @param array $currencies Currency list.
* @return array
*/
public function supported_currencies( $currencies ) {
return array( 'MYR' => $currencies['MYR'] );
}
/**
* Returns the addon menu icon URL.
*
* @return string
*/
public function get_menu_icon() {
return plugins_url( 'assets/logo.svg', __FILE__ );
}
/**
* Scripts to enqueue. Adds feed settings copy-global script.
*
* @return array
*/
public function scripts() {
$scripts = array(
array(
'handle' => 'gf_chip_feed_settings_copy_global',
'src' => $this->get_base_url() . '/assets/js/feed-settings-copy-global.js',
'version' => defined( 'GF_CHIP_MODULE_VERSION' ) ? GF_CHIP_MODULE_VERSION : null,
'deps' => array( 'jquery' ),
'enqueue' => array(
array(
'admin_page' => array( 'form_settings' ),
'tab' => $this->_slug,
),
),
'strings' => array(
'nonce' => wp_create_nonce( 'gf_chip_get_global_credentials' ),
'action' => 'gf_chip_get_global_credentials',
'error' => __( 'Request failed.', 'chip-for-gravity-forms' ),
),
),
);
return array_merge( parent::scripts(), $scripts );
}
/**
* Plugin settings sections (global CHIP keys, account status, optional config).
*
* @return array
*/
public function plugin_settings_fields() {
$configuration = array(
array(
'title' => esc_html__( 'CHIP', 'chip-for-gravity-forms' ),
'description' => $this->get_description(),
'fields' => $this->global_keys_fields(),
),
array(
'id' => 'gf_chip_account_status',
'title' => esc_html__( 'Account Status', 'chip-for-gravity-forms' ),
'description' => $this->global_account_status_description(),
'fields' => array( array( 'type' => 'account_status' ) ),
),
);
if ( get_option( 'gf_chip_global_key_validation' ) ) {
$configuration[] = array(
'title' => esc_html__( 'CHIP Optional Configuration', 'chip-for-gravity-forms' ),
'description' => esc_html__( 'Further customize the behavior of the payment.', 'chip-for-gravity-forms' ),
'fields' => $this->global_advance_fields(),
);
}
return apply_filters( 'gf_chip_plugin_settings_fields', $configuration );
}
/**
* Description HTML for the global settings section (intro + screenshot).
*
* @return string
*/
public function get_description() {
$img_url = plugins_url( 'assets/form-settings.png', __FILE__ );
ob_start();
?>
<p>
<?php
printf(
// translators: %1$s opens link tag, %2$s closes link tag, %3$s is line break.
esc_html__(
'CHIP — Digital Finance Platform. %1$sLearn more%2$s. %3$s%3$sGlobal settings are optional. You may configure CHIP per form in each form\'s CHIP feed settings instead.',
'chip-for-gravity-forms'
),
'<a href="https://www.chip-in.asia/" target="_blank" rel="noopener noreferrer">',
'</a>',
'<br>'
);
?>
<?php
printf(
// translators: %1$s is the opening anchor tag, %2$s is the closing anchor tag for the screenshot link.
esc_html__( 'To use this global configuration on a form, choose "Global Configuration" in the form\'s CHIP feed settings. %1$sView configuration screenshot%2$s.', 'chip-for-gravity-forms' ),
'<a href="' . esc_url( $img_url ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
);
?>
</p>
<?php
return ob_get_clean();
}
/**
* Field definitions for Brand ID and Secret Key (global settings).
*
* @return array
*/
public function global_keys_fields() {
return array(
array(
'name' => 'brand_id',
'label' => esc_html__( 'Brand ID', 'chip-for-gravity-forms' ),
'type' => 'text',
'required' => true,
'tooltip' => '<h6>' . esc_html__( 'Brand ID', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Brand ID enables you to represent your brand in the system using the same CHIP account.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'secret_key',
'label' => esc_html__( 'Secret Key', 'chip-for-gravity-forms' ),
'type' => 'text',
'required' => true,
'tooltip' => '<h6>' . esc_html__( 'Secret Key', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'The secret key is used to identify your account with CHIP. We recommend creating a dedicated secret key for each website.', 'chip-for-gravity-forms' ),
),
);
}
/**
* Optional global settings (refund, due strict, due timing).
*
* @return array
*/
public function global_advance_fields() {
return array(
array(
'name' => 'enable_refund',
'label' => 'Refund',
'type' => 'toggle',
'default_value' => 'false',
'tooltip' => '<h6>' . esc_html__( 'Refund features', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Whether to enable refund through Gravity Forms. If configured, refunds can be made through Gravity Forms → Entries. Default is disabled.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'due_strict',
'label' => esc_html__( 'Due Strict', 'chip-for-gravity-forms' ),
'type' => 'toggle',
'tooltip' => '<h6>' . esc_html__( 'Due Strict', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Whether to permit payments when the purchase\'s due date has passed. By default those are permitted (and status will be set to overdue once the due moment has passed). If this is set to true, it will not be possible to pay for an overdue invoice, and when the due date has passed the purchase\'s status will be set to expired.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'due_strict_timing',
'label' => esc_html__( 'Due Strict Timing (minutes)', 'chip-for-gravity-forms' ),
'type' => 'text',
'placeholder' => '60 for 60 minutes',
'tooltip' => '<h6>' . esc_html__( 'Due Strict Timing (minutes)', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Set due time to enforce due timing for purchases (e.g. 60 for 60 minutes). If due_strict is set while due strict timing is unset, it will default to 1 hour. Leave blank if unsure.', 'chip-for-gravity-forms' ),
),
);
}
/**
* Returns the inner HTML for the Account Status block (global settings).
*
* @return string
*/
public function global_account_status_description() {
return '<div id="gf-chip-account-status-block">' . $this->get_account_status_html() . '</div>';
}
/**
* Returns the inner HTML for the Account Status block (used for initial render and AJAX refresh).
*
* @return string
*/
public function get_account_status_html() {
$state = 'Not set';
if ( get_option( 'gf_chip_global_key_validation' ) ) {
$state = 'Success';
} elseif ( ! empty( get_option( 'gf_chip_global_error_code' ) ) ) {
$state = get_option( 'gf_chip_global_error_code' );
}
$display_state = ( 'Success' === $state ) ? '✓ ' . $state : $state;
$display_state = esc_html( $display_state );
ob_start();
?>
<p>
<?php
printf(
// translators: %1$s and %2$s are strong tags, %3$s is the status (e.g. ✓ Success, Not set, or an error code).
esc_html__(
'CHIP API connection: %1$s%3$s%2$s.',
'chip-for-gravity-forms'
),
'<strong>',
'</strong>',
esc_html( $display_state )
);
?>
</p>
<?php
return ob_get_clean();
}
/**
* Returns Account Status HTML for form feed settings (Brand ID and Secret Key from feed or current form context).
*
* @return string
*/
public function get_form_feed_account_status_description() {
$brand_id = $this->get_setting( 'brand_id', '' );
$secret_key = $this->get_setting( 'secret_key', '' );
return $this->get_account_status_html_for_credentials( $brand_id, $secret_key );
}
/**
* Returns Account Status HTML for given Brand ID and Secret Key (validates and shows Success / Not set / error).
*
* @param string $brand_id Brand ID.
* @param string $secret_key Secret Key.
* @return string
*/
public function get_account_status_html_for_credentials( $brand_id = '', $secret_key = '' ) {
$brand_id = trim( (string) $brand_id );
$secret_key = trim( (string) $secret_key );
$state = 'Not set';
if ( '' !== $brand_id && '' !== $secret_key ) {
$chip = GF_CHIP_API::get_instance( $secret_key, $brand_id );
$public_key = $chip->get_public_key();
if ( is_string( $public_key ) ) {
$state = 'Success';
} elseif ( is_array( $public_key ) && ! empty( $public_key['__all__'] ) && is_array( $public_key['__all__'] ) ) {
$state = implode( ', ', array_column( $public_key['__all__'], 'code' ) );
} else {
$state = __( 'An unspecified error occurred.', 'chip-for-gravity-forms' );
}
}
$display_state = ( 'Success' === $state ) ? '✓ ' . $state : esc_html( $state );
return '<p>' . sprintf(
// translators: %1$s and %2$s are strong tags, %3$s is the status (e.g. ✓ Success, Not set, or an error code).
esc_html__( 'CHIP API connection: %1$s%3$s%2$s.', 'chip-for-gravity-forms' ),
'<strong>',
'</strong>',
$display_state
) . '</p>';
}
/**
* Saves plugin settings and updates Account Status by validating the new keys.
* Called when the user clicks Save Settings on the CHIP settings page.
*
* @param array $settings Decrypted plugin settings (brand_id, secret_key, etc.).
*/
public function update_plugin_settings( $settings ) {
$this->validate_and_update_account_status( $settings );
parent::update_plugin_settings( $settings );
// Sections were built before save; rebuild them so the response has updated Account Status and Optional Configuration (when validation passed).
$renderer = $this->get_settings_renderer();
if ( $renderer && method_exists( $renderer, 'set_fields' ) ) {
$sections = $this->plugin_settings_fields();
$sections = $this->prepare_settings_sections( $sections, 'plugin_settings' );
$renderer->set_fields( $sections );
}
}
/**
* Validates Brand ID and Secret Key against CHIP API and updates Account Status options.
* Used so the Account Status block shows the correct state after Save Settings.
*
* @param array $settings Plugin settings containing brand_id and secret_key.
*/
public function validate_and_update_account_status( $settings ) {
$brand_id = isset( $settings['brand_id'] ) ? trim( (string) $settings['brand_id'] ) : '';
$secret_key = isset( $settings['secret_key'] ) ? trim( (string) $settings['secret_key'] ) : '';
if ( '' === $brand_id || '' === $secret_key ) {
update_option( 'gf_chip_global_key_validation', false );
update_option( 'gf_chip_global_error_code', '' );
$this->log_debug( __METHOD__ . '(): Global keys cleared or empty; Account Status set to Not set.' );
return;
}
$this->log_debug(
__METHOD__ . '(): Validating global keys. New value ' . wp_json_encode(
array(
'brand_id' => $brand_id,
'secret_key' => '***',
)
)
);
$chip = GF_CHIP_API::get_instance( $secret_key, $brand_id );
$public_key = $chip->get_public_key();
if ( is_string( $public_key ) ) {
update_option( 'gf_chip_global_key_validation', true );
update_option( 'gf_chip_global_error_code', '' );
$company_uid = $chip->get_company_uid();
if ( is_string( $company_uid ) && '' !== $company_uid ) {
update_option( 'gf_chip_public_key_' . $company_uid, $public_key, false );
}
$this->log_debug( __METHOD__ . '(): Global keys validated successfully.' );
} elseif ( is_array( $public_key ) && ! empty( $public_key['__all__'] ) && is_array( $public_key['__all__'] ) ) {
$error_code_a = array_column( $public_key['__all__'], 'code' );
$error_code = implode( ', ', $error_code_a );
update_option( 'gf_chip_global_key_validation', false );
update_option( 'gf_chip_global_error_code', $error_code );
$this->log_debug( __METHOD__ . '(): Global keys validation failed: ' . $error_code );
} else {
update_option( 'gf_chip_global_key_validation', false );
update_option( 'gf_chip_global_error_code', __( 'An unspecified error occurred.', 'chip-for-gravity-forms' ) );
$this->log_debug( __METHOD__ . '(): Global keys validation failed with unspecified error.' );
}
}
/**
* After feed save: store public key by company_uid when Form Configuration has brand_id and secret_key.
*
* @param int $feed_id Feed ID.
* @param int $form_id Form ID.
* @param array $settings Saved feed meta (e.g. chipConfigurationType, brand_id, secret_key).
* @param object $addon GFAddOn instance that saved the feed.
*/
public function maybe_store_public_key_on_feed_save( $feed_id, $form_id, $settings, $addon ) {
if ( ! is_object( $addon ) || ! isset( $addon->_slug ) || $addon->_slug !== $this->_slug ) {
return;
}
$configuration_type = isset( $settings['chipConfigurationType'] ) ? $settings['chipConfigurationType'] : '';
if ( 'form' !== $configuration_type ) {
return;
}
$brand_id = isset( $settings['brand_id'] ) ? trim( (string) $settings['brand_id'] ) : '';
$secret_key = isset( $settings['secret_key'] ) ? trim( (string) $settings['secret_key'] ) : '';
if ( '' === $brand_id || '' === $secret_key ) {
return;
}
$chip = GF_CHIP_API::get_instance( $secret_key, $brand_id );
$public_key = $chip->get_public_key();
if ( ! is_string( $public_key ) ) {
return;
}
$company_uid = $chip->get_company_uid();
if ( is_string( $company_uid ) && '' !== $company_uid ) {
update_option( 'gf_chip_public_key_' . $company_uid, $public_key, false );
}
}
/**
* Feed settings fields (configuration type, Brand ID, Secret Key, optional config, client/purchase/misc mapping).
*
* @return array
*/
public function feed_settings_fields() {
$feed_settings_fields = parent::feed_settings_fields();
$feed_settings_fields[0]['description'] = esc_html__( 'Configuration page for CHIP for Gravity Forms.', 'chip-for-gravity-forms' );
// Remove subscription option from Transaction type.
unset( $feed_settings_fields[0]['fields'][1]['choices'][2] );
// Ensure transaction type mandatory.
$feed_settings_fields[0]['fields'][1]['required'] = true;
// Temporarily remove transaction type section.
$transaction_type_array = $feed_settings_fields[0]['fields'][1];
unset( $feed_settings_fields[0]['fields'][1] );
// Temporarily remove product and services section.
$product_and_services = $feed_settings_fields[2];
$other_settings = $feed_settings_fields[3];
unset( $feed_settings_fields[2] );
unset( $feed_settings_fields[3] );
// Add CHIP configuration settings.
$feed_settings_fields[0]['fields'][] = array(
'name' => 'chipConfigurationType',
'label' => esc_html__( 'Configuration Type', 'chip-for-gravity-forms' ),
'type' => 'select',
'required' => true,
'onchange' => "jQuery(this).parents('form').submit();",
'choices' => array(
array(
'label' => esc_html__( 'Select configuration type', 'chip-for-gravity-forms' ),
'value' => '',
),
array(
'label' => esc_html__( 'Global Configuration', 'chip-for-gravity-forms' ),
'value' => 'global',
),
array(
'label' => esc_html__( 'Form Configuration', 'chip-for-gravity-forms' ),
'value' => 'form',
),
),
'tooltip' => '<h6>' . esc_html__( 'Configuration Type', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Select a configuration type. If you want to configure CHIP on a per-form basis, use Form Configuration. If you want to use globally set keys, choose Global Configuration.', 'chip-for-gravity-forms' ),
);
$copy_btn = sprintf(
'<p class="gf-chip-copy-global-wrap" style="margin: 0.75em 0 0.5em 0;"><button type="button" class="button gf-chip-copy-global-config" id="gf-chip-copy-global-config">%s</button></p>',
esc_html__( 'Copy from global configuration', 'chip-for-gravity-forms' )
);
$feed_settings_fields[] = array(
'title' => esc_html__( 'CHIP Form Configuration Settings', 'chip-for-gravity-forms' ),
'dependency' => array(
'field' => 'chipConfigurationType',
'values' => array( 'form' ),
),
'description' => '<p>' . esc_html__( 'Set your Brand ID and Secret Key for the use of CHIP with this form.', 'chip-for-gravity-forms' ) . '</p>' . $copy_btn,
'fields' => array(
array(
'name' => 'brand_id',
'label' => esc_html__( 'Brand ID', 'chip-for-gravity-forms' ),
'type' => 'text',
'class' => 'medium',
'required' => true,
'tooltip' => '<h6>' . esc_html__( 'Brand ID', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Brand ID enables you to represent your brand in the system using the same CHIP account.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'secret_key',
'label' => esc_html__( 'Secret Key', 'chip-for-gravity-forms' ),
'type' => 'text',
'class' => 'medium',
'required' => true,
'tooltip' => '<h6>' . esc_html__( 'Secret Key', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'The secret key is used to identify your account with CHIP. We recommend creating a dedicated secret key for each website.', 'chip-for-gravity-forms' ),
),
),
);
$feed_settings_fields[] = array(
'title' => esc_html__( 'Account Status', 'chip-for-gravity-forms' ),
'dependency' => array(
'field' => 'chipConfigurationType',
'values' => array( 'form' ),
),
'description' => $this->get_form_feed_account_status_description(),
'fields' => array(
// Placeholder so GF renders the section (description above shows the status).
array(
'name' => '_gf_chip_account_status_placeholder',
'type' => 'hidden',
'label' => '',
),
),
);
$feed_settings_fields[] = array(
'title' => esc_html__( 'CHIP Optional Configuration', 'chip-for-gravity-forms' ),
'dependency' => array(
'field' => 'chipConfigurationType',
'values' => array( 'form' ),
),
'description' => esc_html__( 'Further customize the behavior of the payment.', 'chip-for-gravity-forms' ),
'fields' => array(
array(
'name' => 'enable_refund',
'label' => esc_html__( 'Refund', 'chip-for-gravity-forms' ),
'type' => 'toggle',
'tooltip' => '<h6>' . esc_html__( 'Refund features', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Whether to enable refund through Gravity Forms. If configured, refunds can be made through Gravity Forms → Entries. Default is disabled.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'due_strict',
'label' => esc_html__( 'Due Strict', 'chip-for-gravity-forms' ),
'type' => 'toggle',
'tooltip' => '<h6>' . esc_html__( 'Due Strict', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Whether to permit payments when the purchase\'s due date has passed. By default those are permitted (and status will be set to overdue once the due moment has passed). If this is set to true, it will not be possible to pay for an overdue invoice, and when the due date has passed the purchase\'s status will be set to expired.', 'chip-for-gravity-forms' ),
),
array(
'name' => 'due_strict_timing',
'label' => esc_html__( 'Due Strict Timing (minutes)', 'chip-for-gravity-forms' ),
'type' => 'text',
'placeholder' => '60 for 60 minutes',
'tooltip' => '<h6>' . esc_html__( 'Due Strict Timing (minutes)', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Set due time to enforce due timing for purchases (e.g. 60 for 60 minutes). If due_strict is set while due strict timing is unset, it will default to 1 hour. Leave blank if unsure.', 'chip-for-gravity-forms' ),
),
),
);
// Readd transaction type section.
$feed_settings_fields[0]['fields'][] = $transaction_type_array;
// Readd product and services section.
$feed_settings_fields[] = $product_and_services;
$feed_settings_fields[] = $other_settings;
return apply_filters( 'gf_chip_feed_settings_fields', array_values( $feed_settings_fields ) );
}
/**
* Other settings field definitions (client metadata, purchase info, miscellaneous, cancel URL).
*
* @return array
*/
public function other_settings_fields() {
$other_settings_fields = parent::other_settings_fields();
$other_settings_fields[0]['name'] = 'clientInformation';
$other_settings_fields[0]['label'] = esc_html__( 'Client Information', 'chip-for-gravity-forms' );
$other_settings_fields[0]['field_map'] = $this->client_info_fields();
$other_settings_fields[0]['tooltip'] = '<h6>' . esc_html__( 'Client Information', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Map your form fields to the available listed fields. Only email is required; other fields are optional. You may refer to the CHIP API for further information about the specific fields.', 'chip-for-gravity-forms' );
$conditional_logic = $other_settings_fields[1];
unset( $other_settings_fields[1] );
// This dynamic_field_map inspired by gravityformsstripe plugin.
$other_settings_fields[] = array(
'name' => 'clientMetaData',
'label' => esc_html__( 'Client Information Metadata', 'chip-for-gravity-forms' ),
'type' => 'dynamic_field_map',
'limit' => 15,
'tooltip' => '<h6>' . esc_html__( 'Client Information Metadata', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'You may send custom key information to CHIP /purchases/ client fields. A maximum of 15 custom keys may be sent. The key name must be 40 characters or less, and the mapped data will be truncated accordingly as per CHIP requirements. Accepted keys are: \'bank_account\', \'bank_code\', \'personal_code\', \'street_address\', \'country\', \'city\', \'zip_code\', \'shipping_street_address\', \'shipping_country\', \'shipping_city\', \'shipping_zip_code\', \'legal_name\', \'brand_name\', \'registration_number\', \'tax_number\'.', 'chip-for-gravity-forms' ),
);
$other_settings_fields[] = array(
'name' => 'purchaseInformation',
'label' => esc_html__( 'Purchase Information', 'chip-for-gravity-forms' ),
'type' => 'field_map',
'field_map' => $this->purchase_info_fields(),
'tooltip' => '<h6>' . esc_html__( 'Purchase Information', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Map your form fields to the available listed fields.', 'chip-for-gravity-forms' ),
);
$other_settings_fields[] = array(
'name' => 'miscellaneous',
'label' => esc_html__( 'Miscellaneous', 'chip-for-gravity-forms' ),
'type' => 'field_map',
'field_map' => $this->miscellaneous_info_fields(),
'tooltip' => '<h6>' . esc_html__( 'Miscellaneous', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Map your form fields to the available listed fields.', 'chip-for-gravity-forms' ),
);
$other_settings_fields[] = array(
'name' => 'cancelUrl',
'label' => esc_html__( 'Cancel URL', 'chip-for-gravity-forms' ),
'type' => 'text',
'placeholder' => 'https://example.com/pages',
'tooltip' => '<h6>' . esc_html__( 'Cancel URL', 'chip-for-gravity-forms' ) . '</h6>' . esc_html__( 'Redirect to a custom URL when the customer cancels. Leaving this blank will redirect back to the form page. Note: You can set success behavior by configuring the confirmation redirect.', 'chip-for-gravity-forms' ),
);
$other_settings_fields[] = $conditional_logic;
return array_values( $other_settings_fields );
}
/**
* Returns empty array to prevent option from showing in feed settings.
*
* @return array
*/
public function option_choices() {
return array();
}
/**
* Client info field mappings (email, full name).
*
* @return array
*/
public function client_info_fields() {
$client_info_fields = array(
array(
'name' => 'email',
'label' => esc_html__( 'Email', 'chip-for-gravity-forms' ),
'required' => true,
),
array(
'name' => 'full_name',
'label' => esc_html__( 'Full Name', 'chip-for-gravity-forms' ),
'required' => false,
),
);
return apply_filters( 'gf_chip_client_info_fields', $client_info_fields );
}
/**
* Purchase info field mappings (notes).
*
* @return array
*/
public function purchase_info_fields() {
$purchase_info_fields = array(
array(
'name' => 'notes',
'label' => esc_html__( 'Purchase Note', 'chip-for-gravity-forms' ),
'required' => false,
),
);
return apply_filters( 'gf_chip_purchase_info_fields', $purchase_info_fields );
}
/**
* Miscellaneous field mappings (reference).
*
* @return array
*/
public function miscellaneous_info_fields() {
$miscellaneous_info_fields = array(
array(
'name' => 'reference',
'label' => esc_html__( 'Reference', 'chip-for-gravity-forms' ),
'required' => false,
),
);
return apply_filters( 'gf_chip_miscellaneous_info_fields', $miscellaneous_info_fields );
}
/**
* Builds the redirect URL to CHIP checkout for the given feed/entry.
*
* @param array $feed Feed config.
* @param array $submission_data Submission data.
* @param array $form Form.
* @param array $entry Entry.
* @return string Checkout URL or empty on failure.
*/
public function redirect_url( $feed, $submission_data, $form, $entry ) {
$entry_id = $entry['id'];
$this->log_debug( __METHOD__ . '(): Started for entry id: #' . $entry_id );
$configuration_type = rgars( $feed, 'meta/chipConfigurationType', 'global' );
$payment_amount_location = rgars( $feed, 'meta/paymentAmount' ); // Location for payment amount.
$name_location = rgars( $feed, 'meta/clientInformation_full_name' ); // Location for buyer name.
$email_location = rgars( $feed, 'meta/clientInformation_email' ); // Location for buyer email address.
$notes_location = rgars( $feed, 'meta/purchaseInformation_notes' ); // Location for purchase notes.
$reference_location = rgars( $feed, 'meta/miscellaneous_reference' ); // Location for reference.
$full_name_location_array = array();
foreach ( $form['fields'] as $field ) {
if ( 'name' === $field->type ) {
if ( $name_location !== (string) $field->id ) {
continue;
}
$full_name_location_array[ $field->id ] = array();
foreach ( $field->inputs as $input ) {
$full_name_location_array[ $field->id ][] = $input['id'];
}
}
}
// This branch when the total amount is set to form total.
if ( 'form_total' === $payment_amount_location ) {
$amount = rgar( $submission_data, 'payment_amount' ) * 100;
$product_name = rgar( $form, 'title' );
$product_qty = '1';
} else {
// This if the total amount choose to specific product.
$items = rgar( $submission_data, 'line_items' );
foreach ( $items as $item ) {
if ( (string) $item['id'] === (string) $payment_amount_location ) {
$amount = $item['unit_price'] * 100;
$product_name = $item['name'];
$product_qty = $item['quantity'];
break;
}
}
}
$currency = rgar( $entry, 'currency' );
$email = rgar( $entry, $email_location );
$notes = rgar( $entry, $notes_location );
$reference = rgar( $entry, $reference_location );
$full_name = rgar( $entry, $name_location, '' );
if ( ! empty( $full_name_location_array ) ) {
if ( array_key_exists( $name_location, $full_name_location_array ) ) {
foreach ( $full_name_location_array[ $name_location ] as $full_name_location ) {
$full_name .= ' ' . rgar( $entry, $full_name_location );
}
$full_name = trim( $full_name );
}
}
$client_meta_data = $this->get_chip_client_meta_data( $feed, $entry, $form );
$gf_global_settings = get_option( 'gravityformsaddon_gravityformschip_settings' );
if ( $gf_global_settings ) {
$secret_key = rgar( $gf_global_settings, 'secret_key' );
$brand_id = rgar( $gf_global_settings, 'brand_id' );
$due_strict = rgar( $gf_global_settings, 'due_strict' );
$due_timing = rgar( $gf_global_settings, 'due_strict_timing', 60 );
}
if ( 'form' === $configuration_type ) {
$secret_key = rgars( $feed, 'meta/secret_key' );
$brand_id = rgars( $feed, 'meta/brand_id' );
$due_strict = rgars( $feed, 'meta/due_strict' );
$due_timing = rgars( $feed, 'meta/due_strict_timing', 60 );
}
$chip = GF_CHIP_API::get_instance( $secret_key, $brand_id );
$redirect_url_args = array(
'callback' => $this->_slug,
'entry_id' => $entry_id,
);
$params = array(
'success_callback' => $this->get_redirect_url( $redirect_url_args ),
'success_redirect' => $this->get_redirect_url( $redirect_url_args ),
'failure_redirect' => $this->get_redirect_url( $redirect_url_args ),
'cancel_redirect' => $this->get_redirect_url( $redirect_url_args ),
'creator_agent' => 'Gravity Forms: ' . GF_CHIP_MODULE_VERSION,
'reference' => empty( $reference ) ? $entry_id : substr( $reference, 0, 128 ),
'platform' => 'gravityforms',
'send_receipt' => false,
'due' => time() + ( absint( $due_timing ) * 60 ),
'brand_id' => $brand_id,
'client' => array(
'email' => $email,
'full_name' => substr( $full_name, 0, 30 ),
),
'purchase' => array(
'timezone' => apply_filters( 'gf_chip_purchase_timezone', $this->get_timezone() ),
'currency' => $currency,
'notes' => substr( $notes, 0, 10000 ),
'due_strict' => '1' === $due_strict,
'products' => array(
array(
'name' => substr( $product_name, 0, 256 ),
'price' => round( $amount ),
'quantity' => $product_qty,
),
),
),
);
// Merge client array with client meta data array.
$params['client'] += $client_meta_data;
// Enable customization for gateway charges.
$params = apply_filters( 'gf_chip_purchases_api_parameters', $params, array( $feed, $submission_data, $form, $entry ) );
$this->log_debug( __METHOD__ . '(): Params keys ' . wp_json_encode( $params ) );
$payment = $chip->create_payment( $params );
if ( ! rgar( $payment, 'id' ) ) {
$this->log_debug( __METHOD__ . '(): Attempt to create purchases failed ' . wp_json_encode( $payment ) );
return false;
}
// Store chip payment id.
gform_update_meta( $entry_id, 'chip_payment_id', rgar( $payment, 'id' ), rgar( $form, 'id' ) );
// Add note.
$note = esc_html__( 'Customer was redirected to the payment page. ', 'chip-for-gravity-forms' );
$note .= esc_html__( 'URL: ', 'chip-for-gravity-forms' ) . $payment['checkout_url'];
$this->add_note( $entry['id'], $note, 'success' );
// Add is test note.
if ( true === $payment['is_test'] ) {
$note = __( 'This is a test environment where payment status is simulated.', 'chip-for-gravity-forms' );
$this->add_note( $entry['id'], $note, 'error' );
}
$this->log_debug( __METHOD__ . '(): Attempt to create purchases successful ' . wp_json_encode( $payment ) );
return $payment['checkout_url'];
}
/**
* Builds redirect URL with callback and entry_id for CHIP.
*
* @param array $args Query args (e.g. callback, entry_id).
* @return string
*/
public function get_redirect_url( $args = array() ) {
return add_query_arg(
$args,
home_url( '/' )
);
}
/**
* Builds client metadata array from feed custom keys and form field values.
*
* @param array $feed Feed config.
* @param array $entry Entry.
* @param array $form Form.
* @return array
*/
public function get_chip_client_meta_data( $feed, $entry, $form ) {
// Initialize metadata array.
$metadata = array();
// Find feed metadata.
$custom_meta = rgars( $feed, 'meta/clientMetaData' );
if ( is_array( $custom_meta ) ) {
// Loop through custom meta and add to metadata for stripe.
foreach ( $custom_meta as $meta ) {
// If custom key or value are empty, skip meta.
if ( empty( $meta['custom_key'] ) || empty( $meta['value'] ) ) {
continue;
}
// Get field value for meta key.
$field_value = $this->get_field_value( $form, $entry, $meta['value'] );
if ( ! empty( $field_value ) ) {
// Add to metadata array.
$metadata[ $meta['custom_key'] ] = $field_value;
}
}
if ( ! empty( $metadata ) ) {
$this->log_debug( __METHOD__ . '(): ' . wp_json_encode( $metadata ) );
}
}
return $metadata;
}
/**
* Timezone string for purchase (WordPress timezone or UTC).
*
* @return string
*/
public function get_timezone() {
if ( preg_match( '/^[A-z]+\/[A-z\_\/\-]+$/', wp_timezone_string() ) ) {
return wp_timezone_string();
}
return 'UTC';
}
/**
* Payment callback: fetches payment status from CHIP and returns action for post_callback.
*
* @return array|null Action array or null.
*/
public function callback() {
if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] && ! empty( $_SERVER['HTTP_X_SIGNATURE'] ) ) {
$action = $this->process_webhook_callback();