forked from MarkEdmondson1234/googleID
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitpay-checkout-for-woocommerce.index.php
1084 lines (894 loc) · 44.7 KB
/
bitpay-checkout-for-woocommerce.index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: BitPay Checkout for WooCommerce
* Plugin URI: https://www.bitpay.com
* Description: Create Invoices and process through BitPay. Configure in your <a href ="admin.php?page=wc-settings&tab=checkout§ion=bitpay_checkout_gateway">WooCommerce->Payments plugin</a>.
* Version: 3.12.1912
* Author: BitPay
* Author URI: mailto:[email protected]?subject=BitPay Checkout for WooCommerce
*/
if (!defined('ABSPATH')): exit;endif;
add_action('wp_enqueue_scripts', 'enable_bitpayquickpay_js');
global $current_user;
#autoloader
function BPC_autoloader($class)
{
if (strpos($class, 'BPC_') !== false):
if (!class_exists('BitPayLib/' . $class, false)):
#doesnt exist so include it
include 'BitPayLib/' . $class . '.php';
endif;
endif;
}
function BPC_Logger($msg, $type = null, $isJson = false, $error = false)
{
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$structure = plugin_dir_path(__FILE__) . 'logs/';
if (!file_exists($structure)) {
mkdir($structure);
}
$transaction_log = plugin_dir_path(__FILE__) . 'logs/' . date('Ymd') . '_transactions.log';
$error_log = plugin_dir_path(__FILE__) . 'logs/' . date('Ymd') . '_error.log';
$header = PHP_EOL . '======================' . $type . '===========================' . PHP_EOL;
$footer = PHP_EOL . '=================================================' . PHP_EOL;
if ($error):
error_log($header, 3, $error_log);
error_log($msg, 3, $error_log);
error_log($footer, 3, $error_log);
else:
if ($bitpay_checkout_options['bitpay_log_mode'] == 1):
error_log($header, 3, $transaction_log);
if ($isJson):
error_log(print_r($msg, true), 3, $transaction_log);
else:
error_log($msg, 3, $transaction_log);
endif;
error_log($footer, 3, $transaction_log);
endif;
endif;
}
spl_autoload_register('BPC_autoloader');
#check and see if requirements are met for turning on plugin
function _isCurl()
{
return function_exists('curl_version');
}
function bitpay_checkout_woocommerce_bitpay_failed_requirements()
{
global $wp_version;
global $woocommerce;
$errors = array();
// WooCommerce required
if (true === empty($woocommerce)) {
$errors[] = 'The WooCommerce plugin for WordPress needs to be installed and activated. Please contact your web server administrator for assistance.';
} elseif (true === version_compare($woocommerce->version, '2.2', '<')) {
$errors[] = 'Your WooCommerce version is too old. The BitPay payment plugin requires WooCommerce 2.2 or higher to function. Your version is ' . $woocommerce->version . '. Please contact your web server administrator for assistance.';
} elseif (!_isCurl()) {
$errors[] = 'cUrl needs to be installed/enabled for BitPay Checkout to function';
}
if (empty($errors)):
return false;
else:
return implode("<br>\n", $errors);
endif;
}
add_action('plugins_loaded', 'wc_bitpay_checkout_gateway_init', 11);
#create the table if it doesnt exist
function bitpay_checkout_plugin_setup()
{
$failed = bitpay_checkout_woocommerce_bitpay_failed_requirements();
$plugins_url = admin_url('plugins.php');
if ($failed === false) {
global $wpdb;
$table_name = '_bitpay_checkout_transactions';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table_name(
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`transaction_id` varchar(255) NOT NULL,
`transaction_status` varchar(50) NOT NULL DEFAULT 'new',
`date_added` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta($sql);
#check out of date plugins
$plugins = get_plugins();
foreach ($plugins as $file => $plugin) {
if ('Bitpay Woocommerce' === $plugin['Name'] && true === is_plugin_active($file)) {
deactivate_plugins(plugin_basename(__FILE__));
wp_die('BitPay for WooCommerce requires that the old plugin, <b>Bitpay Woocommerce</b>, is deactivated and deleted.<br><a href="' . $plugins_url . '">Return to plugins screen</a>');
}
}
} else {
// Requirements not met, return an error message
wp_die($failed . '<br><a href="' . $plugins_url . '">Return to plugins screen</a>');
}
}
register_activation_hook(__FILE__, 'bitpay_checkout_plugin_setup');
function bitpay_checkout_insert_order_note($order_id = null, $transaction_id = null)
{
global $wpdb;
if ($order_id != null && $transaction_id != null):
global $woocommerce;
//Retrieve the order
$order = new WC_Order($order_id);
$order->set_transaction_id($transaction_id);
$order->save();
//Retrieve the transaction ID
$table_name = '_bitpay_checkout_transactions';
$wpdb->insert(
$table_name,
array(
'order_id' => $order_id,
'transaction_id' => $transaction_id,
)
);
else:
BPC_Logger('Missing values' . PHP_EOL . 'order id: ' . $order_id . PHP_EOL . 'transaction id: ' . $transaction_id, 'error', false, true);
endif;
}
function bitpay_checkout_update_order_note($order_id = null, $transaction_id = null, $transaction_status = null)
{
global $wpdb;
$table_name = '_bitpay_checkout_transactions';
if ($order_id != null && $transaction_id != null && $transaction_status != null):
$wpdb->update($table_name, array('transaction_status' => $transaction_status), array("order_id" => $order_id, 'transaction_id' => $transaction_id));
else:
BPC_Logger('Missing values' . PHP_EOL . 'order id: ' . $order_id . PHP_EOL . 'transaction id: ' . $transaction_id . PHP_EOL . 'transaction status: ' . $transaction_status . PHP_EOL, 'error', false, true);
endif;
}
function bitpay_checkout_get_order_transaction($order_id, $transaction_id)
{
global $wpdb;
$table_name = '_bitpay_checkout_transactions';
$rowcount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(order_id) FROM $table_name WHERE transaction_id = %s LIMIT 1",$transaction_id));
return $rowcount;
}
function bitpay_checkout_get_order_id_bitpay_invoice_id($transaction_id)
{
global $wpdb;
$table_name = '_bitpay_checkout_transactions';
$order_id = $wpdb->get_var($wpdb->prepare("SELECT order_id FROM $table_name WHERE transaction_id = %s LIMIT 1", $transaction_id));
return $order_id;
}
function bitpay_checkout_delete_order_transaction($order_id)
{
global $wpdb;
$table_name = '_bitpay_checkout_transactions';
$wpdb->query($wpdb->prepare("DELETE FROM $table_name WHERE order_id = %s",$order_id));
}
function wc_bitpay_checkout_gateway_init()
{
if (class_exists('WC_Payment_Gateway')) {
class WC_Gateway_BitPay extends WC_Payment_Gateway
{
public function __construct()
{
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$this->id = 'bitpay_checkout_gateway';
$this->icon = BPC_getBitPaymentIcon();
$this->has_fields = true;
$this->method_title = __(BPC_getBitPayVersionInfo($clean = true), 'wc-bitpay');
$this->method_label = __('BitPay', 'wc-bitpay');
$this->method_description = __('Expand your payment options by accepting instant BTC and BCH payments without risk or price fluctuations.', 'wc-bitpay');
if (empty($_GET['woo-bitpay-return'])) {
$this->order_button_text = __('Pay with BitPay', 'woocommerce-gateway-bitpay_checkout_gateway');
}
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = $this->get_option('title');
$this->description = $this->get_option('description') . '<br>';
$this->instructions = $this->get_option('instructions', $this->description);
// Actions
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
// Customer Emails
add_action('woocommerce_email_before_order_table', array($this, 'email_instructions'), 10, 3);
}
public function email_instructions($order, $sent_to_admin, $plain_text = false)
{
if ($this->instructions && !$sent_to_admin && 'bitpay_checkout_gateway' === $order->get_payment_method() && $order->has_status('processing')) {
echo wp_kses_post(wpautop(wptexturize($this->instructions)) . PHP_EOL);
}
}
public function init_form_fields()
{
$this->form_fields = array(
'enabled' => array(
'title' => __('Enable/Disable', 'woocommerce'),
'label' => __('Enable BitPay', 'woocommerce'),
'type' => 'checkbox',
'description' => '',
'default' => 'no',
),
'bitpay_checkout_info' => array(
'description' => __('You should not ship any products until BitPay has finalized your transaction.<br>The order will stay in a <b>Hold</b> and/or <b>Processing</b> state, and will automatically change to <b>Completed</b> after the payment has been confirmed.', 'woocommerce'),
'type' => 'title',
),
'bitpay_checkout_merchant_info' => array(
'description' => __('If you have not created a BitPay Merchant Token, you can create one on your BitPay Dashboard.<br><a href = "https://test.bitpay.com/dashboard/merchant/api-tokens" target = "_blank">(Test)</a> or <a href= "https://www.bitpay.com/dashboard/merchant/api-tokens" target = "_blank">(Production)</a> </p>', 'woocommerce'),
'type' => 'title',
),
'bitpay_checkout_tier_info' => array(
'description' => __('<em><b>*** </b>If you are having trouble creating BitPay invoices, verify your Tier settings on your <a href = "https://support.bitpay.com/hc/en-us/articles/206003676-How-do-I-raise-my-approved-processing-volume-tier-limit-" target = "_blank">BitPay Dashboard</a>.</em>', 'woocommerce'),
'type' => 'title',
),
'title' => array(
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
'default' => __('BitPay', 'woocommerce'),
),
'description' => array(
'title' => __('Description', 'woocommerce'),
'type' => 'text',
'description' => __('This is the message box that will appear on the <b>checkout page</b> when they select BitPay.', 'woocommerce'),
'default' => 'Pay with BitPay using one of the supported cryptocurrencies',
),
'bitpay_checkout_token_dev' => array(
'title' => __('Development Token', 'woocommerce'),
'label' => __('Development Token', 'woocommerce'),
'type' => 'text',
'description' => 'Your <b>development</b> merchant token. <a href = "https://test.bitpay.com/dashboard/merchant/api-tokens" target = "_blank">Create one here</a> and <b>uncheck</b> `Require Authentication`.',
'default' => '',
),
'bitpay_checkout_token_prod' => array(
'title' => __('Production Token', 'woocommerce'),
'label' => __('Production Token', 'woocommerce'),
'type' => 'text',
'description' => 'Your <b>production</b> merchant token. <a href = "https://www.bitpay.com/dashboard/merchant/api-tokens" target = "_blank">Create one here</a> and <b>uncheck</b> `Require Authentication`.',
'default' => '',
),
'bitpay_checkout_endpoint' => array(
'title' => __('Endpoint', 'woocommerce'),
'type' => 'select',
'description' => __('Select <b>Test</b> for testing the plugin, <b>Production</b> when you are ready to go live.'),
'options' => array(
'production' => 'Production',
'test' => 'Test',
),
'default' => 'test',
),
'bitpay_checkout_flow' => array(
'title' => __('Checkout Flow', 'woocommerce'),
'type' => 'select',
'description' => __('If this is set to <b>Redirect</b>, then the customer will be redirected to <b>BitPay</b> to checkout, and return to the checkout page once the payment is made.<br>If this is set to <b>Modal</b>, the user will stay on <b>' . get_bloginfo('name', null) . '</b> and complete the transaction.', 'woocommerce'),
'options' => array(
'1' => 'Modal',
'2' => 'Redirect',
),
'default' => '2',
),
'bitpay_checkout_slug' => array(
'title' => __('Checkout Page', 'woocommerce'),
'type' => 'text',
'description' => __('By default, this will be "checkout". If you have a different Checkout page, enter the <b>page slug</b>. <br>ie. ' . get_home_url() . '/<b>checkout</b><br><br>View your pages <a target = "_blank" href = "/wp-admin/edit.php?post_type=page">here</a>, your current checkout page should have <b>Checkout Page</b> next to the title.<br><br>Click the "quick edit" and copy and paste a custom slug here if needed.', 'woocommerce'),
'default' => 'checkout',
),
'bitpay_checkout_product' => array(
'title' => __('Show on Product page ', 'woocommerce'),
'type' => 'select',
'description' => __('Set to YES if you would like to show BitPay as an immediate checkout option on the product page', 'woocommerce'),
'options' => array(
'1' => 'Yes',
'2' => 'No',
),
'default' => '2',
),
'bitpay_checkout_show_logo' => array(
'title' => __('Show logo on Checkout ', 'woocommerce'),
'type' => 'select',
'description' => __('Set to YES if you would like to show the BitPay logo on the payment page', 'woocommerce'),
'options' => array(
'1' => 'Yes',
'2' => 'No',
),
'default' => '1',
),
'bitpay_checkout_capture_email' => array(
'title' => __('Auto-Capture Email', 'woocommerce'),
'type' => 'select',
'description' => __('Should BitPay try to auto-add the client\'s email address? If <b>Yes</b>, the client will not be able to change the email address on the BitPay invoice. If <b>No</b>, they will be able to add their own email address when paying the invoice.', 'woocommerce'),
'options' => array(
'1' => 'Yes',
'0' => 'No',
),
'default' => '1',
),
'bitpay_checkout_checkout_message' => array(
'title' => __('Checkout Message', 'woocommerce'),
'type' => 'textarea',
'description' => __('Insert your custom message for the <b>Order Received</b> page, so the customer knows that the order will not be completed until BitPay releases the funds.', 'woocommerce'),
'default' => 'Thank you. We will notify you when BitPay has processed your transaction.',
),
'bitpay_checkout_order_process_status' => array(
'title' => __('Woocommerce "Processing" Status', 'woocommerce'),
'type' => 'select',
'description' => __('Based on the transaction speed configured in your <a href = "'.BPC_getProcessingLink().'" target = "_blank">BitPay Dashboard</a>, indicate which BitPay invoice status shall be used to mark the Woocommerce order to the status <b>Processing</b>', 'woocommerce'),
'options' => array(
'0'=>'Confirmed',
'1'=>'Complete'
),
'default' => '0',
),
'bitpay_checkout_order_expired_status' => array(
'title' => __('Woocommerce "Expired" Status', 'woocommerce'),
'type' => 'select',
'description' => __('If set to <b>Yes</b>, automatically set the order to canceled when the invoice has expired and has been notified by the BitPay IPN', 'woocommerce'),
'options' => array(
'0'=>'No',
'1'=>'Yes'
),
'default' => '0',
),
'bitpay_checkout_order_complete_status' => array(
'title' => __('Woocommerce "Complete" Status', 'woocommerce'),
'type' => 'select',
'description' => __('If set to <b>Yes</b>, automatically set the order to complete when the invoice has confirmed and has been notified by the BitPay IPN', 'woocommerce'),
'options' => array(
'0'=>'No',
'1'=>'Yes'
),
'default' => '0',
),
'bitpay_log_mode' => array(
'title' => __('Developer Logging', 'woocommerce'),
'type' => 'select',
'description' => __('Errors will be logged to the plugin <b>log</b> directory automatically. Set to <b>Enabled</b> to also log transactions, ie invoices and IPN updates', 'woocommerce'),
'options' => array(
'0' => 'Disabled',
'1' => 'Enabled',
),
'default' => '1',
),
);
}
function process_payment($order_id)
{
#this is the one that is called intially when someone checks out
global $woocommerce;
$order = new WC_Order($order_id);
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url($order),
);
}
} // end \WC_Gateway_Offline class
} //end check for class existence
else {
global $wpdb;
if (!function_exists('get_plugins')) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugins_url = admin_url('plugins.php');
$plugins = get_plugins();
foreach ($plugins as $file => $plugin) {
if ('BitPay Checkout for WooCommerce' === $plugin['Name'] && true === is_plugin_active($file)) {
deactivate_plugins(plugin_basename(__FILE__));
wp_die('WooCommerce needs to be installed and activated before BitPay Checkout for WooCommerce can be activated.<br><a href="' . $plugins_url . '">Return to plugins screen</a>');
}
}
}
}
//this is an error message incase a token isnt set
add_action('admin_notices', 'bitpay_checkout_check_token');
function bitpay_checkout_check_token()
{
if (isset($_GET['section'])):
if ($_GET['section'] == 'bitpay_checkout_gateway' && $_POST && is_admin()):
if (!file_exists(plugin_dir_path(__FILE__) . 'logs')) {
mkdir(plugin_dir_path(__FILE__) . 'logs', 0755, true);
}
//lookup the token based on the environment
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
//dev or prod token
$bitpay_checkout_token = BPC_getBitPayToken($bitpay_checkout_options['bitpay_checkout_endpoint']);
$bitpay_checkout_endpoint = $bitpay_checkout_options['bitpay_checkout_endpoint'];
if (empty($bitpay_checkout_token)): ?>
<?php _e('There is no token set for your <b>' . strtoupper($bitpay_checkout_endpoint) . '</b> environment. <b>BitPay</b> will not function if this is not set.');?>
<?php
##check and see if the token is valid
else:
if ($_POST && !empty($bitpay_checkout_token) && !empty($bitpay_checkout_endpoint)) {
if (!BPC_isValidBitPayToken($bitpay_checkout_token, $bitpay_checkout_endpoint)): ?>
<div class="error notice">
<p>
<?php _e('The token for <b>' . strtoupper($bitpay_checkout_endpoint) . '</b> is invalid. Please verify your settings.');?>
</p>
</div>
<?php endif;
}
endif;
endif;
endif;
}
//show on the product page
add_action( 'woocommerce_after_add_to_cart_form', function() {
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_product = $bitpay_checkout_options['bitpay_checkout_product'];
if($bitpay_checkout_product == 1):?>
<script type = "text/javascript">
function bpAddToCart(){
var btn = jQuery(".single_add_to_cart_button")
btn.trigger('click')
}
</script>
<div class = "bpbutton" style = "padding-top:15px;padding-bottom:15px;clear:both;"><img style = "cursor:pointer" onclick = "bpAddToCart()" src = "//bitpay.com/cdn/en_US/bp-btn-pay-currencies.svg"></div>
<?php
endif;
});
//show on the cart page
add_action( 'woocommerce_after_cart_totals', function() {
$url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) );
$url.='?payment=bitpay';
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_product = $bitpay_checkout_options['bitpay_checkout_product'];
if($bitpay_checkout_product == 1):?>
<script type = "text/javascript">
function bpCheckout(){
window.location = '<?php echo $url;?>'
}
</script>
<div class = "bpbutton" style = "padding-bottom:15px;clear:both;"><img style = "cursor:pointer" onclick = "bpCheckout()" src = "//bitpay.com/cdn/en_US/bp-btn-pay-currencies.svg"></div>
<?php
endif;
});
//show on the mini cart
function bitpay_mini_checkout() {
$url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) );
$url.='?payment=bitpay';
?>
<script type = "text/javascript">
//widget_shopping_cart_content
var obj = document.createElement("div");
// obj.style.cssText = 'margin:0 auto;cursor:pointer';
obj.innerHTML = '<img style = "margin:0 auto;cursor:pointer;padding-bottom:10px;" onclick = "bpMiniCheckout()" src = "//bitpay.com/cdn/en_US/bp-btn-pay-currencies.svg">'
var miniCart = document.getElementsByClassName("widget_shopping_cart_content")[0];
miniCart.appendChild(obj);
function bpMiniCheckout(){
let checkoutUrl = '<?php echo $url;?>';
window.location = checkoutUrl
}
</script>
<?php
}
add_action( 'woocommerce_widget_shopping_cart_buttons', 'bitpay_mini_checkout', 20 );
//redirect to cart if bitpay single page enabled
function bp_redirect_to_checkout( $url ) {
$url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) );
$url.='?payment=bitpay';
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_product = $bitpay_checkout_options['bitpay_checkout_product'];
if($bitpay_checkout_product == 1):
return $url;
endif;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'bp_redirect_to_checkout' );
function bitpay_default_payment_gateway(){
if( is_checkout() && ! is_wc_endpoint_url() ) {
// HERE define the default payment gateway ID
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_product = $bitpay_checkout_options['bitpay_checkout_product'];
$default_payment_id = 'bitpay_checkout_gateway';
if($bitpay_checkout_product == 1 && isset($_GET['payment']) && $_GET['payment'] == 'bitpay'):
WC()->session->set( 'chosen_payment_method', $default_payment_id );
else:
WC()->session->set( 'chosen_payment_method', "false" );
endif;
}
}
function enable_bitpayquickpay_js()
{
wp_enqueue_script('bitpayquickpay-js', plugins_url('/js/bitpayquickpay_js.js', __FILE__));
}
add_action( 'template_redirect', 'bitpay_default_payment_gateway' );
#http://<host>/wp-json/bitpay/ipn/status
add_action('rest_api_init', function () {
register_rest_route('bitpay/ipn', '/status', array(
'methods' => 'POST,GET',
'callback' => 'bitpay_checkout_ipn',
));
register_rest_route('bitpay/cartfix', '/restore', array(
'methods' => 'POST,GET',
'callback' => 'bitpay_checkout_cart_restore',
));
});
function bitpay_checkout_cart_restore(WP_REST_Request $request)
{
// Load cart functions which are loaded only on the front-end.
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
include_once WC_ABSPATH . 'includes/class-wc-cart.php';
if ( is_null( WC()->cart ) ) {
wc_load_cart();
}
$data = $request->get_params();
$order_id = $data['orderid'];
$order = new WC_Order($order_id);
$items = $order->get_items();
BPC_Logger('User canceled order: ' . $order_id . ', removing from WooCommerce', 'USER CANCELED ORDER', true);
$order->add_order_note('User closed the modal, the order will be set to canceled state');
$order->update_status('canceled', __('BitPay payment canceled by user', 'woocommerce'));
//clear the cart first so things dont double up
WC()->cart->empty_cart();
foreach ($items as $item) {
//now insert for each quantity
$item_count = $item->get_quantity();
for ($i = 0; $i < $item_count; $i++):
WC()->cart->add_to_cart($item->get_product_id());
endfor;
}
//delete the previous order
// wp_delete_post($order_id, true);
// bitpay_checkout_delete_order_transaction($order_id);
setcookie("bitpay-invoice-id", "", time() - 3600);
}
//http://<host>/wp-json/bitpay/ipn/status
function bitpay_checkout_ipn(WP_REST_Request $request)
{
global $woocommerce;
WC()->frontend_includes();
WC()->cart = new WC_Cart();
WC()->session = new WC_Session_Handler();
WC()->session->init();
#$hash_key = $_REQUEST['hash_key'];
$data = $request->get_body();
$data = json_decode($data);
$event = $data->event;
$data = $data->data;
//$orderid = $data->orderId;
$invoiceID = $data->id;
$orderid = bitpay_checkout_get_order_id_bitpay_invoice_id($invoiceID);
$order_status = $data->status;
BPC_Logger($data, 'INCOMING IPN', true);
$order = new WC_Order($orderid);
if ($order->get_payment_method() != 'bitpay_checkout_gateway'){
#ignore the IPN when the order payment method is (no longer) bitpay
BPC_Logger("Order id = ".$orderid.", BitPay invoice id = ".$invoiceID.". Current payment method = " . $order->get_payment_method(), 'Ignore IPN', true);
die();
}
#verify the ipn matches the status of the actual invoice
if (bitpay_checkout_get_order_transaction($orderid, $invoiceID)):
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
//dev or prod token
$bitpay_checkout_token = BPC_getBitPayToken($bitpay_checkout_options['bitpay_checkout_endpoint']);
$bitpay_checkout_order_process_status = $bitpay_checkout_options['bitpay_checkout_order_process_status'];
$bitpay_checkout_order_expired_status = $bitpay_checkout_options['bitpay_checkout_order_expired_status'];
$bitpay_checkout_order_complete_status = $bitpay_checkout_options['bitpay_checkout_order_complete_status'];
$config = new BPC_Configuration($bitpay_checkout_token, $bitpay_checkout_options['bitpay_checkout_endpoint']);
$bitpay_checkout_endpoint = $bitpay_checkout_options['bitpay_checkout_endpoint'];
$params = new stdClass();
$params->extension_version = BPC_getBitPayVersionInfo();
$params->invoiceID = $invoiceID;
$item = new BPC_Item($config, $params);
$invoice = new BPC_Invoice($item); //this creates the invoice with all of the config params
$orderStatus = json_decode($invoice->BPC_checkInvoiceStatus($invoiceID));
#update the lookup table
$note_set = null;
bitpay_checkout_update_order_note($orderid, $invoiceID, $order_status);
switch ($event->name) {
case 'invoice_confirmed':
# if($bitpay_checkout_order_process_status == 0 || $bitpay_checkout_order_process_status == ''):
if($bitpay_checkout_order_complete_status != 1):
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . '</a> processing has completed.');
$order_status = "wc-processing";
$order->update_status($order_status, __('BitPay payment ', 'woocommerce'));
WC()->cart->empty_cart();
wc_reduce_stock_levels($orderid);
else:
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . '</a> order has been completed, based on your Woocommerce settings.');
$order_status = "wc-completed";
$order->update_status($order_status, __('BitPay payment ', 'woocommerce'));
WC()->cart->empty_cart();
wc_reduce_stock_levels($orderid);
endif;
break;
case 'invoice_completed':
if($bitpay_checkout_order_process_status == 1):
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . '</a> processing has completed.');
$order_status = "wc-processing";
$order->update_status($order_status, __('BitPay payment ', 'woocommerce'));
// Reduce stock levels
wc_reduce_stock_levels($orderid);
// Remove cart
WC()->cart->empty_cart();
endif;
break;
case 'invoice_failedToConfirm':
if ($orderStatus->data->status == 'invalid'):
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . '</a> has become invalid because of network congestion. Order will automatically update when the status changes.');
$order->update_status('failed', __('BitPay payment invalid', 'woocommerce'));
endif;
break;
case 'invoice_expired':
$order_status = "wc-cancelled";
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . '</a> has expired.');
if($bitpay_checkout_order_expired_status == 1):
$order->update_status($order_status, __('BitPay payment invalid', 'woocommerce'));
endif;
break;
case 'invoice_refundComplete':
$order->add_order_note('BitPay Invoice ID: <a target = "_blank" href = "' . BPC_getBitPayDashboardLink($bitpay_checkout_endpoint, $invoiceID) . '">' . $invoiceID . ' </a> has been refunded.');
$order->update_status('refunded', __('BitPay payment refunded', 'woocommerce'));
break;
default:
break;
}
die();
endif;
}
add_action('template_redirect', 'woo_custom_redirect_after_purchase');
function woo_custom_redirect_after_purchase()
{
global $wp;
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_token = BPC_getBitPayToken($bitpay_checkout_options['bitpay_checkout_endpoint']);
if (is_checkout() && !empty($wp->query_vars['order-received'])) {
$order_id = $wp->query_vars['order-received'];
try {
$order = new WC_Order($order_id);
//this means if the user is using bitpay AND this is not the redirect
$show_bitpay = true;
if (isset($_GET['redirect']) && $_GET['redirect'] == 'false'):
$show_bitpay = false;
$invoiceID = $_COOKIE['bitpay-invoice-id'];
//clear the cookie
setcookie("bitpay-invoice-id", "", time() - 3600);
endif;
if ($order->payment_method == 'bitpay_checkout_gateway' && $show_bitpay == true):
$config = new BPC_Configuration($bitpay_checkout_token, $bitpay_checkout_options['bitpay_checkout_endpoint']);
//sample values to create an item, should be passed as an object'
$params = new stdClass();
$current_user = wp_get_current_user();
#$params->fullNotifications = 'true';
$params->extension_version = BPC_getBitPayVersionInfo();
$params->price = $order->total;
$params->currency = $order->currency; //set as needed
if ($bitpay_checkout_options['bitpay_checkout_capture_email'] == 1):
$current_user = wp_get_current_user();
if ($current_user->user_email):
$buyerInfo = new stdClass();
$buyerInfo->name = $current_user->display_name;
$buyerInfo->email = $current_user->user_email;
$params->buyer = $buyerInfo;
endif;
endif;
//orderid
$params->orderId = $order->get_order_number($order_id);
//redirect and ipn stuff
$checkout_slug = $bitpay_checkout_options['bitpay_checkout_slug'];
if (empty($checkout_slug)):
$checkout_slug = 'checkout';
endif;
$params->redirectURL = get_home_url() . '/' . $checkout_slug . '/order-received/' . $order_id . '/?key=' . $order->order_key . '&redirect=false';
#create a hash for the ipn
$hash_key = $config->BPC_generateHash($params->orderId);
$params->notificationURL = get_home_url() . '/wp-json/bitpay/ipn/status';
#http://<host>/wp-json/bitpay/ipn/status
$params->extendedNotifications = true;
$item = new BPC_Item($config, $params);
$invoice = new BPC_Invoice($item);
//this creates the invoice with all of the config params from the item
$invoice->BPC_createInvoice();
#BPC_Logger(json_decode($invoice->BPC_getInvoiceData()), 'NEW BITPAY INVOICE',true);
$invoiceData = json_decode($invoice->BPC_getInvoiceData());
BPC_Logger($invoiceData, 'NEW BITPAY INVOICE', true);
//now we have to append the invoice transaction id for the callback verification
$invoiceID = $invoiceData->data->id;
//set a cookie for redirects and updating the order status
$cookie_name = "bitpay-invoice-id";
$cookie_value = $invoiceID;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$use_modal = intval($bitpay_checkout_options['bitpay_checkout_flow']);
#insert into the database
bitpay_checkout_insert_order_note($order_id, $invoiceID);
//use the modal if '1', otherwise redirect
if ($use_modal == 2):
wp_redirect($invoice->BPC_getInvoiceURL());
else:
wp_redirect($params->redirectURL);
endif;
exit;
endif;
} catch (Exception $e) {
global $woocommerce;
$cart_url = $woocommerce->cart->get_cart_url();
wp_redirect($cart_url);
exit;
}
}
}
// Replacing the Place order button when total volume exceed 68 m3
add_filter('woocommerce_order_button_html', 'bitpay_checkout_replace_order_button_html', 10, 2);
function bitpay_checkout_replace_order_button_html($order_button, $override = false)
{
if ($override):
return;
else:
return $order_button;
endif;
}
function BPC_getBitPayVersionInfo($clean = null)
{
$plugin_data = get_file_data(__FILE__, array('Version' => 'Version', 'Plugin_Name' => 'Plugin Name'), false);
$plugin_name = $plugin_data['Plugin_Name'];
if ($clean):
$plugin_version = $plugin_name . ' ' . $plugin_data['Version'];
else:
$plugin_name = str_replace(" ", "_", $plugin_name);
$plugin_name = str_replace("_for_", "_", $plugin_name);
$plugin_version = $plugin_name . '_' . $plugin_data['Version'];
endif;
return $plugin_version;
}
#retrieves the invoice token based on the endpoint
function BPC_getBitPayDashboardLink($endpoint, $invoiceID)
{ //dev or prod token
switch ($endpoint) {
case 'test':
default:
return '//test.bitpay.com/dashboard/payments/' . $invoiceID;
break;
case 'production':
return '//bitpay.com/dashboard/payments/' . $invoiceID;
break;
}
}
#retrieves the invoice token based on the endpoint
function BPC_getProcessingLink()
{ //dev or prod token
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$bitpay_checkout_endpoint = $bitpay_checkout_options['bitpay_checkout_endpoint'];
switch ($bitpay_checkout_endpoint) {
case 'test':
default:
return 'https://test.bitpay.com/dashboard/settings/edit/order';
break;
case 'production':
return 'https://test.bitpay.com/dashboard/settings/edit/order';
break;
}
}
function BPC_getBitPayLogo($endpoint = null)
{
if (is_admin() && $_GET['section'] == 'bitpay_checkout_gateway'):
$buttonObj = new BPC_Buttons;
$buttons = $buttonObj->BPC_getButtons();
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$brand = $bitpay_checkout_options['bitpay_checkout_brand'];
if ($brand == '-'):
return null;
elseif ($brand == ''):
return $buttons[0];
else:
return $brand;
endif;
endif;
}
function BPC_getBitPayToken($endpoint)
{
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
//dev or prod token
switch ($bitpay_checkout_options['bitpay_checkout_endpoint']) {
case 'test':
default:
return $bitpay_checkout_options['bitpay_checkout_token_dev'];
break;
case 'production':
return $bitpay_checkout_options['bitpay_checkout_token_prod'];
break;
}
}
function BPC_isValidBitPayToken($bitpay_checkout_token, $bitpay_checkout_endpoint)
{
$api_test = new BPC_Token($bitpay_checkout_endpoint, $bitpay_checkout_token);
$api_response = json_decode($api_test->BPC_checkToken());
if ($api_response->error == 'Object not found'):
#valid token, no invoice
return true;
endif;
BPC_Logger('Invalid token: ' . $bitpay_checkout_token . ' for ' . $bitpay_checkout_endpoint . ' environment', 'token', false, true);
return false;
}
//hook into the order recieved page and re-add to cart of modal canceled
add_action('woocommerce_thankyou', 'bitpay_checkout_thankyou_page', 10, 1);
function bitpay_checkout_thankyou_page($order_id)
{
global $woocommerce;
$order = new WC_Order($order_id);
$bitpay_checkout_options = get_option('woocommerce_bitpay_checkout_gateway_settings');
$use_modal = intval($bitpay_checkout_options['bitpay_checkout_flow']);
$bitpay_checkout_test_mode = $bitpay_checkout_options['bitpay_checkout_endpoint'];
$restore_url = get_home_url() . '/wp-json/bitpay/cartfix/restore';
$cart_url = get_home_url() . '/cart';
$test_mode = false;
$js_script = "https://bitpay.com/bitpay.min.js";
if ($bitpay_checkout_test_mode == 'test'):
$test_mode = true;
$js_script = "https://test.bitpay.com/bitpay.min.js";
endif;
#use the modal
if ($order->payment_method == 'bitpay_checkout_gateway' && $use_modal == 1):
$invoiceID = $_COOKIE['bitpay-invoice-id'];
?>
<script type="text/javascript" src="<?php echo $js_script;?>"></script>
<script type='text/javascript'>