This repository has been archived by the owner on Feb 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
class-wc-gateway-btcpay.php
1815 lines (1510 loc) · 82.1 KB
/
class-wc-gateway-btcpay.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: BTCPay for WooCommerce (Legacy)
Plugin URI: https://wordpress.org/plugins/btcpay-for-woocommerce
Description: Enable your WooCommerce store to accept Bitcoin with BTCPay.
Author: BTCPay
Author URI: https://github.com/btcpayserver
Version: 3.0.16
License: Copyright 2011-2018 BTCPay & BitPay Inc., MIT License
License URI: https://github.com/btcpayserver/woocommerce-plugin/blob/master/LICENSE
GitHub Plugin URI: https://github.com/btcpayserver/woocommerce-plugin
Text Domain: btcpay-for-woocommerce
Domain Path: languages
*/
// Exit if accessed directly
if (false === defined('ABSPATH')) {
exit;
}
define("BTCPAY_VERSION", "3.0.16");
$autoloader_param = __DIR__ . '/lib/Bitpay/Autoloader.php';
// Load up the BitPay library
if (true === file_exists($autoloader_param) &&
true === is_readable($autoloader_param))
{
if(false === class_exists("Bitpay\Autoloader")){
require_once $autoloader_param;
\Bitpay\Autoloader::register();
}
} else {
throw new \Exception('The BTCPay payment plugin was not installed correctly or the files are corrupt. Please reinstall the plugin. If this message persists after a reinstall, contact the BTCPay team through https://chat.btcpayserver.org with this message.');
}
// Exist for quirks in object serialization...
if (false === class_exists('Bitpay\PrivateKey')) {
include_once(__DIR__ . '/lib/Bitpay/PrivateKey.php');
}
if (false === class_exists('Bitpay\PublicKey')) {
include_once(__DIR__ . '/lib/Bitpay/PublicKey.php');
}
if (false === class_exists('Bitpay\Token')) {
include_once(__DIR__ . '/lib/Bitpay/Token.php');
}
/**
* Load translations
*/
function btcpay_load_textdomain() {
$slug = 'btcpay-for-woocommerce';
$locale = get_locale();
$locale = apply_filters('plugin_locale', $locale, $slug);
load_textdomain($slug, WP_LANG_DIR . '/plugins/' . $slug . '-' . $locale . '.mo' );
load_plugin_textdomain($slug, false, dirname(plugin_basename( __FILE__ )) . '/languages/');
}
// Ensures WooCommerce is loaded before initializing the BitPay plugin
add_action('plugins_loaded', 'woocommerce_btcpay_init', 0);
add_action('plugins_loaded', 'btcpay_load_textdomain');
add_action( 'admin_notices', 'fx_admin_notice_show_migration_message' );
register_activation_hook(__FILE__, 'woocommerce_btcpay_activate');
function woocommerce_btcpay_init()
{
if (true === class_exists('WC_Gateway_BtcPay')) {
return;
}
if (false === class_exists('WC_Payment_Gateway')) {
return;
}
// Exist for quirks in object serialization...
if (false === class_exists('Bitpay\PrivateKey')) {
include_once(__DIR__ . '/lib/Bitpay/PrivateKey.php');
}
if (false === class_exists('Bitpay\PublicKey')) {
include_once(__DIR__ . '/lib/Bitpay/PublicKey.php');
}
if (false === class_exists('Bitpay\Token')) {
include_once(__DIR__ . '/lib/Bitpay/Token.php');
}
class WC_Gateway_BtcPay extends WC_Payment_Gateway
{
private $is_initialized = false;
/**
* Constructor for the gateway.
*/
public function __construct()
{
// General
$this->id = 'btcpay';
$this->icon = plugin_dir_url(__FILE__).'assets/img/icon.png';
$this->has_fields = false;
$this->order_button_text = __('Proceed to BTCPay', 'btcpay-for-woocommerce');
$this->method_title = 'BTCPay';
$this->method_description = 'BTCPay allows you to accept bitcoin payments on your WooCommerce store.';
// 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');
$this->order_states = $this->get_option('order_states');
$this->debug = 'yes' === $this->get_option('debug', 'no');
// Define BitPay settings
$this->api_key = get_option('woocommerce_btcpay_key');
$this->api_pub = get_option('woocommerce_btcpay_pub');
$this->api_sin = get_option('woocommerce_btcpay_sin');
$this->api_token = get_option('woocommerce_btcpay_token');
$this->api_token_label = get_option('woocommerce_btcpay_label');
$this->api_url = get_option('woocommerce_btcpay_url');
// Define debugging & informational settings
$this->debug_php_version = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;
$this->debug_plugin_version = constant("BTCPAY_VERSION");
$this->log('BTCPay Woocommerce payment plugin object constructor called. Plugin is v' . $this->debug_plugin_version . ' and server is PHP v' . $this->debug_php_version);
$this->log(' [Info] $this->api_key = ' . $this->api_key);
$this->log(' [Info] $this->api_pub = ' . $this->api_pub);
$this->log(' [Info] $this->api_sin = ' . $this->api_sin);
$this->log(' [Info] $this->api_token = ' . $this->api_token);
$this->log(' [Info] $this->api_token_label = ' . $this->api_token_label);
$this->log(' [Info] $this->api_url = ' . $this->api_url);
// Process Credentials
if (false === empty($this->api_key)) {
try {
$this->api_key = $this->btcpay_decrypt($this->api_key);
if (false === empty($this->api_key)) {
$this->log(' [Info] Private Key decrypted successfully.');
} else {
$this->log(' [Error] Private Key decrypted successfully BUT the value itself is null or empty!');
}
} catch (\Exception $e) {
$this->log(' [Error] Private Key corrupt. Message is: ' . $e->getMessage());
}
} else {
}
if (false === empty($this->api_pub)) {
try {
$this->api_pub = $this->btcpay_decrypt($this->api_pub);
if (false === empty($this->api_pub)) {
$this->log(' [Info] Public Key decrypted successfully.');
} else {
$this->log(' [Error] Public Key decrypted successfully BUT the value itself is null or empty!');
}
} catch (\Exception $e) {
$this->log(' [Error] Public Key corrupt. Message is: ' . $e->getMessage());
}
}
if (false === empty($this->api_token)) {
try {
$this->api_token = $this->btcpay_decrypt($this->api_token);
if (true === isset($this->api_token) && false === empty($this->api_token)) {
$this->log(' [Info] API Token decrypted successfully.');
} else {
$this->log(' [Error] API Token decrypted successfully BUT the value itself is null or empty!');
}
} catch (\Exception $e) {
$this->log(' [Error] API Token corrupt. Message is: ' . $e->getMessage());
}
}
// Check API Credentials
if (!($this->api_key instanceof \Bitpay\PrivateKey)) {
$this->api_key = null;
$this->log(' [Error] The API Key was NOT an instance of PrivateKey! Instead, it appears to be a ' . gettype($this->api_key) . ' value.');
}
if (!($this->api_pub instanceof \Bitpay\PublicKey)) {
$this->api_pub = null;
$this->log(' [Error] The Public Key was NOT an instance of PublicKey! Instead, it appears to be a ' . gettype($this->api_pub) . ' value.');
}
if (!($this->api_token instanceof \Bitpay\Token)) {
$this->api_token = null;
$this->log(' [Error] The API Token was NOT an instance of Token! Instead, it appears to be a ' . gettype($this->api_token) . ' value.');
}
$this->transaction_speed = $this->get_option('transaction_speed');
$this->log(' [Info] Transaction speed is now set to: ' . $this->transaction_speed);
// Actions
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'save_order_states'));
// Valid for use and IPN Callback
if (false === $this->is_valid_for_use()) {
$this->enabled = 'no';
$this->log(' [Info] The plugin is NOT valid for use!');
} else {
$this->enabled = 'yes';
$this->log(' [Info] The plugin is ok to use.');
add_action('woocommerce_api_wc_gateway_btcpay', array($this, 'ipn_callback'));
}
// Additional token initialization.
if (btcpay_get_additional_tokens()) {
$this->initialize_additional_tokens();
}
$this->is_initialized = true;
}
/**
* Initializes additional tokens if any configured.
*/
public function initialize_additional_tokens() {
if ( $additional_tokens = btcpay_get_additional_tokens() ) {
foreach ( $additional_tokens as $token ) {
if ( ! class_exists( $token['classname'] ) ) {
// Build the class structure.
$classcode = "class {$token['classname']} extends WC_Gateway_BtcPay { ";
$classcode .= "public \$token_mode;";
$classcode .= "public \$token_symbol;";
$classcode .= "public function __construct() { ";
$classcode .= "parent::__construct();";
$classcode .= "\$this->id = 'btcpay_{$token['symbol']}';";
$classcode .= "\$this->method_title = 'BTCPay Asset: {$token['symbol']}';";
$classcode .= "\$this->method_description = 'This is an additional asset managed by BTCPay.';";
$classcode .= "\$this->title = '{$token['name']}';";
$classcode .= "\$this->token_mode = '{$token['mode']}';";
$classcode .= "\$this->token_symbol = '{$token['symbol']}';";
$classcode .= "\$this->icon = '{$token['icon']}';";
$classcode .= "\$this->init_settings();";
$classcode .= "}";
$classcode .= "public function ipn_callback() { ";
$classcode .= "return;";
$classcode .= "}";
$classcode .= "}";
// Initialize it on the fly.
eval( $classcode );
}
}
}
}
public function is_btcpay_payment_method($order)
{
$actualMethod = '';
if (method_exists($order, 'get_payment_method')) {
$actualMethod = $order->get_payment_method();
} else {
$actualMethod = get_post_meta( $order->get_id(), '_payment_method', true );
}
return (false !== strpos($actualMethod, 'btcpay'));
}
public function __destruct()
{
}
public function is_valid_for_use()
{
// Check that API credentials are set
if (true === is_null($this->api_key) ||
true === is_null($this->api_pub) ||
true === is_null($this->api_sin) ||
true === is_null($this->api_token))
{
return false;
}
// Ensure the currency is supported by BitPay
try {
$currency = new \Bitpay\CurrencyUnrestricted(get_woocommerce_currency());
if (false === isset($currency) || true === empty($currency)) {
$this->log(' [Error] The BTCPay payment plugin was called to check if it was valid for use but could not instantiate a currency object.');
throw new \Exception('The BTCPay payment plugin was called to check if it was valid for use but could not instantiate a currency object. Cannot continue!');
}
} catch (\Exception $e) {
$this->log(' [Error] In is_valid_for_use: ' . $e->getMessage());
return false;
}
$this->log(' [Info] Plugin is valid for use.');
return true;
}
/**
* Initialise Gateway Settings Form Fields
*/
public function init_form_fields()
{
$this->log(' [Info] Entered init_form_fields()...');
$log_file = 'btcpay-' . sanitize_file_name( wp_hash( 'btcpay' ) ) . '-log';
$logs_href = get_bloginfo('wpurl') . '/wp-admin/admin.php?page=wc-status&tab=logs&log_file=' . $log_file;
$this->form_fields = array(
'title' => array(
'title' => __('Title', 'btcpay-for-woocommerce'),
'type' => 'text',
'description' => __('Controls the name of this payment method as displayed to the customer during checkout.', 'btcpay-for-woocommerce'),
'default' => __('Bitcoin', 'btcpay-for-woocommerce'),
'desc_tip' => true,
),
'description' => array(
'title' => __('Customer Message', 'btcpay-for-woocommerce'),
'type' => 'textarea',
'description' => __('Message to explain how the customer will be paying for the purchase.', 'btcpay-for-woocommerce'),
'default' => 'You will be redirected to BTCPay to complete your purchase.',
'desc_tip' => true,
),
'api_token' => array(
'type' => 'api_token'
),
'transaction_speed' => array(
'title' => __('Invoice pass to "confirmed" state after', 'btcpay-for-woocommerce'),
'type' => 'select',
'description' => 'An invoice becomes confirmed after the payment has...',
'options' => array(
'default' => 'Keep store level configuration',
'high' => '0 confirmation on-chain',
'medium' => '1 confirmation on-chain',
'low-medium' => '2 confirmations on-chain',
'low' => '6 confirmations on-chain',
),
'default' => 'default',
'desc_tip' => true,
),
'order_states' => array(
'type' => 'order_states'
),
'debug' => array(
'title' => __('Debug Log', 'btcpay-for-woocommerce'),
'type' => 'checkbox',
'label' => sprintf(__('Enable logging <a href="%s" class="button">View Logs</a>', 'btcpay-for-woocommerce'), $logs_href),
'default' => 'no',
'description' => sprintf(__('Log BTCPay events, such as IPN requests, inside <code>%s</code>', 'btcpay-for-woocommerce'), wc_get_log_file_path('btcpay')),
'desc_tip' => true,
),
'notification_url' => array(
'title' => __('Notification URL', 'btcpay-for-woocommerce'),
'type' => 'url',
'description' => __('BTCPay will send IPNs for orders to this URL with the BTCPay invoice data', 'btcpay-for-woocommerce'),
'default' => '',
'placeholder' => WC()->api_request_url('WC_Gateway_BtcPay'),
'desc_tip' => true,
),
'redirect_url' => array(
'title' => __('Redirect URL', 'btcpay-for-woocommerce'),
'type' => 'url',
'description' => __('After paying the BTCPay invoice, users will be redirected back to this URL', 'btcpay-for-woocommerce'),
'default' => '',
'placeholder' => $this->get_return_url(),
'desc_tip' => true,
),
'additional_tokens' => array(
'title' => __('Additional token configuration', 'btcpay-for-woocommerce'),
'type' => 'textarea',
'description' => __('You can configure additional tokens here, one per line. e.g. "HAT;Hat Token;promotion" See documentation for details. Each one will be available as their own payment method.', 'btcpay-for-woocommerce'),
'default' => '',
'desc_tip' => true,
),
'additional_tokens_limit_payment' => array(
'title' => __('Additional tokens: Enforce payment tokens', 'btcpay-for-woocommerce'),
'type' => 'checkbox',
'label' => __('Limit default payment methods to listed "payment" tokens.', 'btcpay-for-woocommerce'),
'default' => 'no',
'value' => 'yes',
'description' => __('This will override the default btcpay payment method (defaults to all supported by BTCPay Server) and enforce to tokens of type "payment". This is useful if you want full control on what is available on BTCPay Server payment page.', 'btcpay-for-woocommerce'),
'desc_tip' => true,
),
'support_details' => array(
'title' => __( 'Plugin & Support Information', 'btcpay' ),
'type' => 'title',
'description' => sprintf(__('This plugin version is %s and your PHP version is %s. If you need assistance, please come on our chat https://chat.btcpayserver.org. Thank you for using BTCPay!', 'btcpay-for-woocommerce'), constant("BTCPAY_VERSION"), PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION),
),
);
$this->log(' [Info] Initialized form fields: ' . var_export($this->form_fields, true));
$this->log(' [Info] Leaving init_form_fields()...');
}
/**
* HTML output for form field type `api_token`
*/
public function generate_api_token_html()
{
$this->log(' [Info] Entered generate_api_token_html()...');
ob_start();
// TODO: CSS Imports aren't optimal, but neither is this. Maybe include the css to be css-minimized?
wp_enqueue_style('font-awesome', '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
wp_enqueue_style('btcpay-token', plugins_url('assets/css/style.css', __FILE__));
wp_enqueue_script('btcpay-pairing', plugins_url('assets/js/pairing.js', __FILE__), array('jquery'), null, true);
wp_localize_script( 'btcpay-pairing', 'BtcPayAjax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'pairNonce' => wp_create_nonce( 'btcpay-pair-nonce' ),
'revokeNonce' => wp_create_nonce( 'btcpay-revoke-nonce' )
)
);
$pairing_form = file_get_contents(plugin_dir_path(__FILE__).'templates/pairing.tpl');
$token_format = file_get_contents(plugin_dir_path(__FILE__).'templates/token.tpl');
?>
<tr valign="top">
<th scope="row" class="titledesc">API Token:</th>
<td class="forminp" id="btcpay_api_token">
<div id="btcpay_api_token_form">
<?php
if (true === empty($this->api_token)) {
echo sprintf($pairing_form, 'visible');
echo sprintf($token_format, 'hidden', plugins_url('assets/img/logo.png', __FILE__),'','');
} else {
echo sprintf($pairing_form, 'hidden');
echo sprintf($token_format, 'livenet', plugins_url('assets/img/logo.png', __FILE__), $this->api_token_label, $this->api_sin);
}
?>
</div>
<script type="text/javascript">
var ajax_loader_url = '<?php echo plugins_url('assets/img/ajax-loader.gif', __FILE__); ?>';
</script>
</td>
</tr>
<?php
$this->log(' [Info] Leaving generate_api_token_html()...');
return ob_get_clean();
}
/**
* HTML output for form field type `order_states`
*/
public function generate_order_states_html()
{
$this->log(' [Info] Entered generate_order_states_html()...');
ob_start();
$bp_statuses = array(
'new'=>'New Order',
'paid'=>'Paid',
'confirmed'=>'Confirmed',
'complete'=>'Complete',
'invalid'=>'Invalid',
'expired'=>'Expired',
'event_invoice_paidAfterExpiration'=>'Paid after expiration',
'event_invoice_expiredPaidPartial' => 'Expired with partial payment');
$df_statuses = array(
'new'=>'wc-pending',
'paid'=>'wc-on-hold',
'confirmed'=>'wc-processing',
'complete'=>'wc-processing',
'invalid'=>'wc-failed',
'expired'=>'wc-cancelled',
'event_invoice_paidAfterExpiration' => 'wc-failed',
'event_invoice_expiredPaidPartial' => 'wc-failed');
$wc_statuses = wc_get_order_statuses();
$wc_statuses = array('BTCPAY_IGNORE' => '') + $wc_statuses;
?>
<tr valign="top">
<th scope="row" class="titledesc">Order States:</th>
<td class="forminp" id="btcpay_order_states">
<table cellspacing="0">
<?php
foreach ($bp_statuses as $bp_state => $bp_name) {
?>
<tr>
<th><?php echo $bp_name; ?></th>
<td>
<select name="woocommerce_btcpay_order_states[<?php echo $bp_state; ?>]">
<?php
$order_states = get_option('woocommerce_btcpay_settings');
$order_states = $order_states['order_states'];
foreach ($wc_statuses as $wc_state => $wc_name) {
$current_option = $order_states[$bp_state];
if (true === empty($current_option)) {
$current_option = $df_statuses[$bp_state];
}
if ($current_option === $wc_state) {
echo "<option value=\"$wc_state\" selected>$wc_name</option>\n";
} else {
echo "<option value=\"$wc_state\">$wc_name</option>\n";
}
}
?>
</select>
</td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
<?php
$this->log(' [Info] Leaving generate_order_states_html()...');
return ob_get_clean();
}
/**
* Save order states
*/
public function save_order_states()
{
$this->log(' [Info] Entered save_order_states()...');
$bp_statuses = array(
'new' => 'New Order',
'paid' => 'Paid',
'confirmed' => 'Confirmed',
'complete' => 'Complete',
'invalid' => 'Invalid',
'expired' => 'Expired',
'event_invoice_paidAfterExpiration' => 'Paid after expiration',
'event_invoice_expiredPaidPartial' => 'Expired with partial payment'
);
$wc_statuses = wc_get_order_statuses();
if (true === isset($_POST['woocommerce_btcpay_order_states'])) {
$bp_settings = get_option('woocommerce_btcpay_settings');
$order_states = $bp_settings['order_states'];
foreach ($bp_statuses as $bp_state => $bp_name) {
if (false === isset($_POST['woocommerce_btcpay_order_states'][ $bp_state ])) {
continue;
}
$wc_state = $_POST['woocommerce_btcpay_order_states'][ $bp_state ];
if (true === array_key_exists($wc_state, $wc_statuses)) {
$this->log(' [Info] Updating order state ' . $bp_state . ' to ' . $wc_state);
$order_states[$bp_state] = $wc_state;
}
}
$bp_settings['order_states'] = $order_states;
update_option('woocommerce_btcpay_settings', $bp_settings);
}
$this->log(' [Info] Leaving save_order_states()...');
}
/**
* Validate API Token
*/
public function validate_api_token_field()
{
return '';
}
/**
* Validate Support Details
*/
public function validate_support_details_field()
{
return '';
}
/**
* Validate Order States
*/
public function validate_order_states_field()
{
$order_states = $this->get_option('order_states');
$order_states_key = $this->plugin_id . $this->id . '_order_states';
if ( isset( $_POST[ $order_states_key ] ) ) {
$order_states = $_POST[ $order_states_key ];
}
return $order_states;
}
/**
* Validate Notification URL
*/
public function validate_url_field($key)
{
$url = $this->get_option($key);
if ( isset( $_POST[ $this->plugin_id . $this->id . '_' . $key ] ) ) {
if (filter_var($_POST[ $this->plugin_id . $this->id . '_' . $key ], FILTER_VALIDATE_URL) !== false) {
$url = $_POST[ $this->plugin_id . $this->id . '_' . $key ];
} else {
$url = '';
}
}
return $url;
}
/**
* Validate Redirect URL
*/
public function validate_redirect_url_field()
{
$redirect_url = $this->get_option('redirect_url', '');
if ( isset( $_POST['woocommerce_btcpay_redirect_url'] ) ) {
if (filter_var($_POST['woocommerce_btcpay_redirect_url'], FILTER_VALIDATE_URL) !== false) {
$redirect_url = $_POST['woocommerce_btcpay_redirect_url'];
} else {
$redirect_url = '';
}
}
return $redirect_url;
}
/**
* Output for the order received page.
*/
public function thankyou_page($order_id)
{
$this->log(' [Info] Entered thankyou_page with order_id = ' . $order_id);
// Remove cart
WC()->cart->empty_cart();
// Intentionally blank.
$this->log(' [Info] Leaving thankyou_page with order_id = ' . $order_id);
}
public function get_btcpay_redirect($order_id, $client)
{
$redirect = get_post_meta($order_id, 'BTCPay_redirect', true);
if($redirect)
{
$invoice_id = get_post_meta($order_id, 'BTCPay_id', true);;
$invoice = $client->getInvoice($invoice_id);
$status = $invoice->getStatus();
if($status === 'invalid' || $status === 'expired')
{
$redirect = null;
}
}
return $redirect;
}
/**
* Process the payment and return the result
*
* @param int $order_id
* @return array
*/
public function process_payment($order_id)
{
$this->log(' [Info] Entered process_payment() with order_id = ' . $order_id . '...');
if (true === empty($order_id)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but the order_id was missing.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but the order_id was missing. Cannot continue!');
}
$order = wc_get_order( $order_id);
if (false === $order) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not retrieve the order details for order_id ' . $order_id);
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not retrieve the order details for order_id ' . $order_id . '. Cannot continue!');
}
// The order number can differ from the internal $order_id, when a custom
// order number plugin is used. It is added as a reference for the user.
$order_number = $order->get_order_number();
$notification_url = $this->get_option('notification_url', WC()->api_request_url('WC_Gateway_BtcPay'));
$this->log(' [Info] Generating payment form for order ' . $order_id . ' (Order number ' . $order_number . '). Notify URL: ' . $notification_url);
// Mark new order according to user settings (we're awaiting the payment)
$new_order_states = $this->get_option('order_states');
$new_order_status = $new_order_states['new'];
$this->log(' [Info] Changing order status to: '.$new_order_status);
$order->update_status($new_order_status);
$this->log(' [Info] Changed order status result');
$thanks_link = $this->get_return_url($order);
$this->log(' [Info] The variable thanks_link = ' . $thanks_link . '...');
// Redirect URL & Notification URL
$redirect_url = $this->get_option('redirect_url', $thanks_link);
if($redirect_url !== $thanks_link)
{
$order_received_len = strlen('order-received');
if(substr($redirect_url, -$order_received_len) === 'order-received')
{
$this->log('substr($redirect_url, -$order_received_pos) === order-received');
$redirect_url = $redirect_url . '=' . $order->get_id();
}
else
{
$redirect_url = add_query_arg( 'order-received', $order->get_id(), $redirect_url);
}
$redirect_url = add_query_arg( 'key', $order->get_order_key(), $redirect_url);
}
$this->log(' [Info] The variable redirect_url = ' . $redirect_url . '...');
$this->log(' [Info] Notification URL is now set to: ' . $notification_url . '...');
// Setup the currency
$currency_code = get_woocommerce_currency();
$this->log(' [Info] The variable currency_code = ' . $currency_code . '...');
$currency = new \Bitpay\Currency($currency_code);
if (false === isset($currency) && true === empty($currency)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate a Currency object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate a Currency object. Cannot continue!');
}
// Get a BitPay Client to prepare for invoice creation
$client = new \Bitpay\Client\Client();
if (false === isset($client) && true === empty($client)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate a client object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate a client object. Cannot continue!');
}
$url = $this->api_url;
$client->setUri($url);
$this->log(' [Info] Set url to ' . $this->api_url);
$curlAdapter = new \Bitpay\Client\Adapter\CurlAdapter();
if (false === isset($curlAdapter) || true === empty($curlAdapter)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate a CurlAdapter object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate a CurlAdapter object. Cannot continue!');
}
$client->setAdapter($curlAdapter);
if (false === empty($this->api_key)) {
$client->setPrivateKey($this->api_key);
} else {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not set client->setPrivateKey to this->api_key. The empty() check failed!');
throw new \Exception(' The BTCPay payment plugin was called to process a payment but could not set client->setPrivateKey to this->api_key. The empty() check failed!');
}
if (false === empty($this->api_pub)) {
$client->setPublicKey($this->api_pub);
} else {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not set client->setPublicKey to this->api_pub. The empty() check failed!');
throw new \Exception(' The BTCPay payment plugin was called to process a payment but could not set client->setPublicKey to this->api_pub. The empty() check failed!');
}
if (false === empty($this->api_token)) {
$client->setToken($this->api_token);
} else {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not set client->setToken to this->api_token. The empty() check failed!');
throw new \Exception(' The BTCPay payment plugin was called to process a payment but could not set client->setToken to this->api_token. The empty() check failed!');
}
$redirect = $this->get_btcpay_redirect($order_id, $client);
if($redirect)
{
$this->log(' [Info] Existing BTCPay invoice has already been created, redirecting to it...');
$this->log(' [Info] Leaving process_payment()...');
return array(
'result' => 'success',
'redirect' => $redirect,
);
}
$this->log(' [Info] Key and token empty checks passed. Parameters in client set accordingly...');
// Setup the Invoice
$invoice = new \Bitpay\Invoice();
if (false === isset($invoice) || true === empty($invoice)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate an Invoice object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate an Invoice object. Cannot continue!');
} else {
$this->log(' [Info] Invoice object created successfully...');
}
$order_url = $order->get_edit_order_url();
$pos_data = array(
'WooCommerce' => array(
'Order ID' => $order_id,
'Order Number' => $order_number,
'Order URL' => $order_url,
'Plugin Version' => constant("BTCPAY_VERSION")
)
);
// Use the order number as BTCPay order id, because the ID shows up as a reference in the invoices list
$invoice->setOrderId((string)$order_number);
$invoice->setPosData(json_encode($pos_data));
$invoice->setCurrency($currency);
$invoice->setFullNotifications(true);
$invoice->setExtendedNotifications(true);
// Handle additional tokens and enforce them for invoice payment.
if (!empty($this->token_symbol)) {
$invoice->setPaymentCurrencies(array($this->token_symbol));
}
// For the default BTCPay payment method we enforce payment tokens (if enabled).
if ($this->id === 'btcpay') {
$limit_payment_methods = $this->get_option('additional_tokens_limit_payment');
$payment_tokens = btcpay_get_additional_tokens('payment');
if ($payment_tokens && $limit_payment_methods === 'yes') {
$invoice->setPaymentCurrencies(array_column($payment_tokens, 'symbol'));
}
}
// Add a priced item to the invoice
$item = new \Bitpay\Item();
if (false === isset($item) || true === empty($item)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate an item object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate an item object. Cannot continue!');
} else {
$this->log(' [Info] Item object created successfully...');
}
$order_total = $order->calculate_totals();
if (!empty($order_total)) {
$order_total = (float)$order_total;
if (!is_float($order_total)) {
throw new \Bitpay\Client\ArgumentException("Price must be formatted as a float ". $order_total);
}
// For promotion tokens we need to set the price to 1 (per item quantity).
// The idea is that 1 token is like a voucher.
if (!empty($this->token_symbol) && $this->token_mode === 'promotion') {
// Set the invoice currency to the promotion token.
$invoice->setCurrency(new \Bitpay\CurrencyUnrestricted($this->token_symbol));
// For each of the purchased items quantity we charge 1 token.
$total_quantity = (float) $this->get_order_total_item_quantity($order);
$item->setPrice($total_quantity);
} else {
$item->setPrice($order_total);
}
$taxIncluded = $order->get_cart_tax();
$item->setTaxIncluded($taxIncluded);
} else {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not set item->setPrice to $order->calculate_totals(). The empty() check failed!');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not set item->setPrice to $order->calculate_totals(). The empty() check failed!');
}
// Add buyer's email & country code to the invoice
$buyer = new \Bitpay\Buyer();
$buyer->setEmail($order->get_billing_email());
$buyer->setCountry($order->get_shipping_country());
$invoice->setBuyer($buyer);
$invoice->setItem($item);
// Add the Redirect and Notification URLs
$invoice->setRedirectUrl($redirect_url);
$invoice->setNotificationUrl($notification_url);
$invoice->setTransactionSpeed($this->transaction_speed);
try {
$this->log(' [Info] Attempting to generate invoice for ' . $order_id . ' (Order number ' . $order_number . ') ...');
$invoice = $client->createInvoice($invoice);
if (false === isset($invoice) || true === empty($invoice)) {
$this->log(' [Error] The BTCPay payment plugin was called to process a payment but could not instantiate an invoice object.');
throw new \Exception('The BTCPay payment plugin was called to process a payment but could not instantiate an invoice object. Cannot continue!');
} else {
$this->log(' [Info] Call to generate invoice was successful: ' . $client->getResponse()->getBody());
}
} catch (\Exception $e) {
$this->log(' [Error] Error generating invoice for ' . $order_id . ' (Order number ' . $order_number . '), "' . $e->getMessage() . '"');
error_log($e->getMessage());
return array(
'result' => 'success',
'messages' => 'Sorry, but Bitcoin checkout with BTCPay does not appear to be working.'
);
}
$responseData = json_decode($client->getResponse()->getBody());
// If another BTCPay invoice was created before, returns the original one
$redirect = $this->get_btcpay_redirect($order_id, $client);
if($redirect)
{
$this->log(' [Info] Existing BTCPay invoice has already been created, redirecting to it...');
$this->log(' [Info] Leaving process_payment()...');
return array(
'result' => 'success',
'redirect' => $redirect,
);
}
// Store BTCPay meta data
update_post_meta($order_id, 'BTCPay_redirect', $invoice->getUrl());
update_post_meta($order_id, 'BTCPay_id', $invoice->getId());
update_post_meta($order_id, 'BTCPay_rate', $invoice->getRate());
$formattedRate = number_format($invoice->getRate(), wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator());
update_post_meta($order_id, 'BTCPay_formatted_rate', $formattedRate);
$this->update_btcpay($order_id, $responseData);
// Reduce stock levels
if (function_exists('wc_reduce_stock_levels'))
{
wc_reduce_stock_levels($order_id);
}
else
{
$order->reduce_order_stock();
}
$this->log(' [Info] BTCPay invoice assigned ' . $invoice->getId());
$this->log(' [Info] Leaving process_payment()...');
// Redirect the customer to the BitPay invoice
return array(
'result' => 'success',
'redirect' => $invoice->getUrl(),
);
}
public function ipn_callback()
{
$this->log(' [Info] Entered ipn_callback()...');
// Retrieve the Invoice ID and Network URL from the supposed IPN data
$post = file_get_contents("php://input");
if (true === empty($post)) {
$this->log(' [Error] No post data sent to IPN handler!');
error_log('[Error] BTCPay plugin received empty POST data for an IPN message.');
wp_die('No post data');
} else {
$this->log(' [Info] The post data sent to IPN handler is present...');
}
$json = json_decode($post, true);
$event = "";
if(true === array_key_exists('event', $json) && true === array_key_exists('data', $json)) // extended notification type
{
$this->log(' [Info] Event IPN received...');
$event = $json['event'];
$json = $json['data'];
}
else
{
$this->log(' [Info] Normal IPN received...');
}
if (true === empty($json)) {
$this->log(' [Error] Invalid JSON payload sent to IPN handler: ' . $post);
error_log('[Error] BTCPay plugin received an invalid JSON payload sent to IPN handler: ' . $post);
wp_die('Invalid JSON');
} else {
$this->log(' [Info] The post data was decoded into JSON...');
}
if (false === array_key_exists('id', $json)) {
$this->log(' [Error] No invoice ID present in JSON payload: ' . var_export($json, true));
error_log('[Error] BTCPay plugin did not receive an invoice ID present in JSON payload: ' . var_export($json, true));
wp_die('No Invoice ID');
} else {
$this->log(' [Info] Invoice ID present in JSON payload...');
}
if (false === array_key_exists('url', $json)) {