forked from blockonomics/easy-digital-downloads-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedd-blockonomics.php
861 lines (731 loc) · 30.1 KB
/
edd-blockonomics.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
<?php
/**
* Plugin Name: EDD - Blockonomics
* Description: Accept Bitcoin Payments on your Easy Digital Downloads powered website with Blockonomics
* Version: 1.3.8
* Author: Blockonomics
* Author URI: https://www.blockonomics.co
* License: MIT
* Text Domain: edd-blockonomics
* Domain Path: /languages/
*/
/* Copyright 2017 Blockonomics Inc.
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
class EDD_Blockonomics
{
public function __construct()
{
if( ! function_exists( 'edd_get_option' ) )
{
return;
}
if( class_exists( 'EDD_License' ) && is_admin() )
{
$license = new EDD_License( __FILE__, 'Blockonomics Payment Gateway', '1.0.0', 'Blockonomics' );
}
$this->includes();
$this->generate_secret_and_callback();
add_action( 'edd_gateway_blockonomics', array( $this, 'process_payment' ) );
add_action( 'init', array( $this, 'listener' ) );
add_action( 'edd_blockonomics_cc_form', '__return_false' );
add_action( 'wp_ajax_testsetup', array( $this,'edd_blockonomics_testsetup') );
add_filter( 'edd_payment_gateways', array( $this, 'register_gateway' ) );
add_filter( 'edd_currencies', array( $this, 'currencies' ) );
add_filter( 'edd_sanitize_amount_decimals', array( $this, 'btc_decimals' ) );
add_filter( 'edd_format_amount_decimals', array( $this, 'btc_decimals' ) );
add_filter( 'edd_settings_gateways', array( $this, 'settings' ) );
add_filter( 'edd_settings_sections_gateways', array( $this, 'register_gateway_section') );
add_filter( 'edd_accepted_payment_icons', array($this, 'pw_edd_payment_icon'));
add_filter( 'edd_view_order_details_payment_meta_after', array( $this, 'action_edd_view_order_details_payment_meta_after'), 10, 1 );
}
public function includes()
{
if( ! class_exists( 'BlockonomicsAPI' ) )
{
require_once( plugin_dir_path( __FILE__ ) . 'php/Blockonomics.php' );
}
}
public function action_edd_view_order_details_payment_meta_after( $payment_id )
{
$payment = new EDD_Payment( $payment_id );
$meta_data = $payment->get_meta();
if ( !empty($meta_data['blockonomics_txid']) )
{
?>
<div class="edd-order-tx-id edd-admin-box-inside">
<p>
<span class="label"><?php _e( 'Bitcoin Transaction ID:', 'edd-blockonomics' ); ?></span>
<span><?php echo $meta_data['blockonomics_txid']; ?></span>
</p>
</div>
<?php
}
if ( !empty($meta_data['bitcoin_address']) )
{
?>
<div class="edd-order-tx-id edd-admin-box-inside">
<p>
<span class="label"><?php _e( 'Bitcoin Address:', 'edd-blockonomics' ); ?></span>
<span><?php echo $meta_data['bitcoin_address']; ?></span>
</p>
</div>
<?php
}
if ( !empty($meta_data['expected_btc_amount']) )
{
?>
<div class="edd-order-tx-id edd-admin-box-inside">
<p>
<span class="label"><?php _e( 'Expected BTC Amount:', 'edd-blockonomics' ); ?></span>
<span><?php echo $meta_data['expected_btc_amount']; ?></span>
</p>
</div>
<?php
}
if ( !empty($meta_data['paid_btc_amount']) )
{
?>
<div class="edd-order-tx-id edd-admin-box-inside">
<p>
<span class="label"><?php _e( 'Actual BTC Amount:', 'edd-blockonomics' ); ?></span>
<span><?php echo $meta_data['paid_btc_amount']; ?></span>
</p>
</div>
<?php
}
}
public function edd_blockonomics_testsetup(){
$setup_errors = $this->testSetup();
$return = new stdClass();
if($setup_errors)
{
$return->type = 'error';
$return->message = $setup_errors;
echo json_encode($return);
}
else
{
$return->type = 'updated';
$return->message = __('Congrats ! Setup is all done', 'edd-blockonomics');
echo json_encode($return);
}
wp_die();
}
public function register_gateway( $gateways )
{
$gateways['blockonomics'] = array(
'checkout_label' => __( 'Bitcoin', 'edd-blockonomics' ),
'admin_label' => __( 'Blockonomics', 'edd-blockonomics' ),
'supports' => array( 'buy_now' )
);
return $gateways;
}
function pw_edd_payment_icon($icons)
{
$icon_url = plugins_url('img/bitcoin.png', __FILE__);
$icons[$icon_url] = 'Bitcoin';
return $icons;
}
public function register_gateway_section( $gateway_sections )
{
$gateway_sections['blockonomics'] = __( 'Blockonomics', 'edd-blockonomics' );
return $gateway_sections;
}
function generate_secret_and_callback($generate_new = false)
{
$callback_secret = edd_get_option('edd_blockonomics_callback_secret', '');
if ( empty( $callback_secret) || $generate_new )
{
$callback_secret = sha1(openssl_random_pseudo_bytes(20));
edd_update_option("edd_blockonomics_callback_secret", $callback_secret);
}
$callback_url = add_query_arg( array( 'edd-listener' => 'blockonomics', 'secret' => $callback_secret ), home_url() );
edd_update_option('edd_blockonomics_callback_url', $callback_url);
}
public function process_payment( $purchase_data )
{
global $edd_options;
$api_key = trim(edd_get_option('edd_blockonomics_api_key', ''));
// Collect payment data
$payment_data = array(
'price' => $purchase_data['price'],
'date' => $purchase_data['date'],
'user_email' => $purchase_data['user_email'],
'purchase_key' => $purchase_data['purchase_key'],
'currency' => edd_get_currency(),
'downloads' => $purchase_data['downloads'],
'user_info' => $purchase_data['user_info'],
'cart_details' => $purchase_data['cart_details'],
'gateway' => 'blockonomics',
'status' => 'pending'
);
// Record the pending payment
$payment_id = edd_insert_payment( $payment_data );
// Check payment
if ( ! $payment_id )
{
// Record the error
edd_record_gateway_error( __( 'Payment Error', 'edd-blockonomics' ), sprintf( __( 'Payment creation failed, Payment data: %s', 'edd-blockonomics' ), json_encode( $payment_data ) ), $payment_id );
// Problems? send back
edd_send_back_to_checkout( '?payment-mode=blockonomics' );
}
else
{
try
{
$callback_secret = trim(edd_get_option('edd_blockonomics_callback_secret', ''));
$blockonomics = new BlockonomicsAPI;
$responseObj = $blockonomics->new_address($api_key, $callback_secret);
if($responseObj->response_code != 200)
{
edd_record_gateway_error( __( 'Error while getting BTC Address', 'edd-blockonomics' ) );
$this->displayError();
return;
}
$address = $responseObj->address;
$blockonomics_orders = edd_get_option('edd_blockonomics_orders');
$order = array(
'value' => $purchase_data['price'],
'satoshi' => NULL,
'currency' => NULL,
'order_id' => $payment_id,
'status' => -1,
'timestamp' => time(),
'txid' => ''
);
$order = $this->calculate_order_price_params($order);
$this->update_order($address, $order);
//Update post parameters to make them available in the listner method.
update_post_meta($payment_id, 'blockonomics_address', $address);
$invoice_url = add_query_arg( array( 'edd-listener' => 'blockonomics', 'show_order' => $address ), home_url() );
wp_redirect($invoice_url);
exit;
}
catch ( Blockonomics_Exception $e )
{
$error = json_decode( $e->getResponse() );
if ( isset( $error->errors ) && is_array( $error->errors ) )
{
foreach( $error->errors as $error )
{
edd_set_error( 'edd_blockonomics_exception', sprintf( __( 'Error: %s', 'edd-blockonomics' ), $error ) );
}
}
elseif( isset( $error->error ) )
{
edd_set_error( 'edd_blockonomics_exception', $error->error );
}
edd_send_back_to_checkout( '?payment-mode=blockonomics' );
}
}
}
private function displayError(){
$unable_to_generate = __('<h1>Unable to generate bitcoin address</h1><p> Note for site webmaster: ', 'edd-blockonomics');
$error_msg = 'Please login to your admin panel, navigate to Downloads > Settings > Payment Gateways [ Blockonomics ] and click <i>Test Setup</i> to diagnose the issue</p>';
$error_message = $unable_to_generate . $error_msg;
echo $error_message;
}
function update_callback_url($callback_url, $xPub, $blockonomics)
{
$blockonomics->update_callback(
edd_get_option('edd_blockonomics_api_key'),
$callback_url,
$xPub
);
}
private function testSetup()
{
$blockonomics = new BlockonomicsAPI;
$error_str = $blockonomics->testSetup();
if($error_str) {
$error_str = $error_str . __('<p>For more information, please consult <a href="https://blockonomics.freshdesk.com/support/solutions/articles/33000215104-troubleshooting-unable-to-generate-new-address" target="_blank">this troubleshooting article</a></p>', 'edd-blockonomics');
return $error_str;
}
// No errors
return false;
}
public function is_order_underpaid($order, $paid_amount){
// Return TRUE only if there has been a payment which is less than required.
$underpayment_slack = edd_get_option("edd_blockonomics_underpayment_slack", 0)/100 * $order['satoshi'];
$is_order_underpaid = ($order['satoshi'] - $underpayment_slack > $paid_amount && !empty($paid_amount)) ? TRUE : FALSE;
return $is_order_underpaid;
}
public function listener()
{
$listener = htmlspecialchars(isset($_GET['edd-listener']) ? $_GET['edd-listener'] : '');
if( $listener != 'blockonomics' )
{
return;
}
$action = htmlspecialchars(isset($_REQUEST['action']) ? $_REQUEST['action'] : '');
if( !empty($action) )
{
$settings_page = admin_url( 'edit.php?post_type=download&page=edd-settings&tab=gateways§ion=blockonomics');
if($action == "update_callback")
{
$this->generate_secret_and_callback(true);
wp_redirect($settings_page);
exit;
}
}
$address = isset($_REQUEST['show_order']) ? $_REQUEST['show_order'] : '';
if ($address)
{
// Define required context here so that it can be accessed in the included template
$order = $this->process_order($address);
/**
* TODO: Crypto below will be replaced by selected crypto when BCH support is added, adding it here
* now allows us to swap it in future without changing the template.
**/
$crypto = array(
'code' => 'btc',
'name' => 'Bitcoin',
'uri' => 'bitcoin'
);
$order_amount = $this->fix_displaying_small_values($order["satoshi"]);
$context = array(
"order_id" => $order["order_id"],
"order" => $order,
"address" => $address,
"crypto" => $crypto,
"order_amount" => $order_amount,
"payment_uri" => $this->get_crypto_payment_uri($crypto, $address, $order_amount),
"crypto_rate_str" => $this->get_crypto_rate_from_params($order['value'], $order['satoshi'])
);
$this->enqueue_stylesheets();
$this->enqueue_scripts();
$context['script'] = $this->get_checkout_script($context);
include plugin_dir_path(__FILE__)."templates/blockonomics_checkout.php";
exit();
}
$address = isset($_REQUEST['finish_order']) ? $_REQUEST['finish_order'] : '';
if ($address)
{
$order = $this->get_order($address);
wp_redirect(edd_get_success_page_uri());
exit;
}
$address = isset($_REQUEST['get_amount']) ? $_REQUEST['get_amount'] : '';
if ($address)
{
$this->get_order_amount_info($address);
}
try
{
$callback_secret = edd_get_option("edd_blockonomics_callback_secret");
$secret = htmlspecialchars(isset($_REQUEST['secret']) ? $_REQUEST['secret'] : '');
if ($callback_secret && $callback_secret == $secret)
{
$addr = htmlspecialchars(isset($_REQUEST['addr']) ? $_REQUEST['addr'] : '');
$order = $this->get_order($addr);
$order_id = $order['order_id'];
if ($order_id)
{
$status = intval(htmlspecialchars(isset($_REQUEST['status']) ? $_REQUEST['status'] : ''));
$existing_status = $order['status'];
$time_period = edd_get_option("edd_blockonomics_timeperiod", 10) *60;
$payment = new EDD_Payment( $order_id );
$meta_data = $payment->get_meta();
$network_confirmations = edd_get_option("edd_blockonomics_confirmations", 2);
if($network_confirmations == 'zero'){
$network_confirmations = 0;
}
if ($status >= $network_confirmations && !isset($meta_data['paid_btc_amount']))
{
$value = intval(htmlspecialchars(isset($_REQUEST['value']) ? $_REQUEST['value'] : ''));
$meta_data['paid_btc_amount'] = $value/1.0e8;
$payment->update_meta( '_edd_payment_meta', $meta_data );
if ($order['satoshi'] > $value && $this->is_order_underpaid($order, $value))
{
$status = -2; //Payment error , amount not matching
edd_insert_payment_note($order_id, __('Paid BTC amount less than expected.','edd-blockonomics'));
edd_update_payment_status($order_id, 'failed');
}
else
{
if ($order['satoshi'] < $value)
{
edd_insert_payment_note($order_id, __('Overpayment of BTC amount', 'edd-blockonomics'));
}
edd_insert_payment_note($order_id, __('Payment completed', 'edd-blockonomics'));
edd_update_payment_status($order_id, 'publish' );
}
}
$order['txid'] = htmlspecialchars(isset($_REQUEST['txid']) ? $_REQUEST['txid'] : '');
$order['status'] = $status;
if ($existing_status == -1)
{
$payment = new EDD_Payment( $order_id );
$meta_data = $payment->get_meta();
$meta_data['blockonomics_txid'] = $order['txid'];
$meta_data['expected_btc_amount'] = $order['satoshi']/1.0e8;
$meta_data['bitcoin_address'] = $addr;
$payment->update_meta( '_edd_payment_meta', $meta_data );
}
$this->update_order($addr, $order);
}
} else {
die('Incorrect Secret');
}
}
catch ( Blockonomics_Exception $e )
{
$error = json_decode( $e->getResponse() );
if( isset( $error->errors ) )
{
foreach( $error->errors as $error )
{
edd_record_gateway_error( __( 'Blockonomics Error', 'edd-blockonomics' ), 'Message: ' . $error );
}
} elseif( isset( $error->error ) )
{
edd_record_gateway_error( __( 'Blockonomics Error', 'edd-blockonomics' ), 'Message: ' . $error->error );
}
die('blockonomics exception error');
}
}
public function currencies( $currencies )
{
$currencies['BTC'] = __( 'Bitcoin', 'edd-blockonomics' );
return $currencies;
}
function btc_decimals( $decimals = 2 )
{
global $edd_options;
$currency = edd_get_currency();
switch ( $currency )
{
case 'BTC' :
$decimals = 8;
break;
}
return $decimals;
}
public function settings( $settings )
{
$callback_update_url = add_query_arg(array( 'edd-listener' => 'blockonomics', 'action' => 'update_callback') ,home_url());
$callback_refresh = __( 'CALLBACK URL', 'edd-blockonomics' ).'<a href="'.$callback_update_url.'"
id="generate-callback" style="font:400 20px/1 dashicons;margin-left: 7px; top: 4px;position:relative;text-decoration: none;" title="Generate New Callback URL"><a>';
//$settings_page_testsetup = add_query_arg(array( 'edd-listener' => 'blockonomics', 'action' => 'test_setup') ,home_url());
$settings_page = admin_url( 'edit.php?post_type=download&page=edd-settings&tab=gateways§ion=blockonomics');
$test_setup = '<p id="testsetup_msg"><b><i>'.__('Use below button to test the configuration.', 'edd-blockonomics').'</i></b></p>
<p> <a id="edd-blockonomics-test-setup" href="javascript:testSetupFunc();" class="button button-small" style="max-width:90px;">Test Setup</a> </p>
<script type="text/javascript">
var api_key = document.getElementsByName("edd_settings[edd_blockonomics_api_key]")[0].getAttribute(\'value\');
if(api_key.length == 0)
{
var p_element = document.createElement( "p" );
p_element.innerHTML = "You are few clicks away from accepting bitcoin payments</p><p>Click on <b>Get Started for Free</b> on <a href=\'https://www.blockonomics.co/merchants\' target=\'_blank\'>Blockonomics Merchants</a>. Complete the Wizard, Copy the API Key when shown here";
var setting_table = document.getElementsByTagName("table")[0];
setting_table.insertBefore(p_element, setting_table.childNodes[0]);
}
var testSetupFunc = function()
{
var current_api_key = document.getElementsByName("edd_settings[edd_blockonomics_api_key]")[0].value;
if( (current_api_key == api_key && api_key.length == 0 )
|| current_api_key != api_key )
{
if(document.getElementById("setting-error-edd_blockonomics_api_key_changed") == null)
{
/* create notice div */
var div = document.createElement( "div" );
div.classList.add( "error", "settings-warning", "notice", "is-dismissible" );
div.setAttribute( "id", "setting-error-edd_blockonomics_api_key_changed" );
/* create paragraph element to hold message */
var p = document.createElement( "p" );
/* Add message text */
if( current_api_key == api_key && api_key.length == 0)
{
p.innerHTML = "<b>'.__('Please enter your Blockonomics API key and save changes.', 'edd-blockonomics').'</b>";
}
else
{
p.innerHTML = "<b>'.__('API Key has changed. Click on Save Changes first.', 'edd-blockonomics').'</b>";
}
div.appendChild( p );
/* Create Dismiss icon */
var b = document.createElement( "button" );
b.setAttribute( "type", "button" );
b.classList.add( "notice-dismiss" );
/* Add screen reader text to Dismiss icon */
var bSpan = document.createElement( "span" );
bSpan.classList.add( "screen-reader-text" );
bSpan.appendChild( document.createTextNode( "Dismiss this notice." ) );
b.appendChild( bSpan );
/* Add Dismiss icon to notice */
div.appendChild( b );
/* Insert notice in test msg div */
var test_msg = document.getElementById( "testsetup_msg" );
test_msg.appendChild(div);
/* Make the notice dismissable when the Dismiss icon is clicked */
b.addEventListener( "click", function ()
{
div.parentNode.removeChild( div );
});
}
}
else
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "'. admin_url('admin-ajax.php') .'", true);
xhr.setRequestHeader(\'Content-Type\', \'application/x-www-form-urlencoded;\');
xhr.send("action=testsetup");
xhr.onload = function() {
response = JSON.parse(this.response);
/* create notice div */
var div = document.createElement( "div" );
div.classList.add( response.type, "settings-warning", "notice", "is-dismissible" );
div.setAttribute( "id", "setting-error-edd_blockonomics_api_key_changed" );
/* create paragraph element to hold message */
var p = document.createElement( "p" );
/* Add message text */
p.innerHTML = "<b>"+response.message+"</b>";
div.appendChild( p );
/* Create Dismiss icon */
var b = document.createElement( "button" );
b.setAttribute( "type", "button" );
b.classList.add( "notice-dismiss" );
/* Add screen reader text to Dismiss icon */
var bSpan = document.createElement( "span" );
bSpan.classList.add( "screen-reader-text" );
bSpan.appendChild( document.createTextNode( "Dismiss this notice." ) );
b.appendChild( bSpan );
/* Add Dismiss icon to notice */
div.appendChild( b );
/* Insert notice in test msg div */
var test_msg = document.getElementById( "testsetup_msg" );
test_msg.appendChild(div);
/* Make the notice dismissable when the Dismiss icon is clicked */
b.addEventListener( "click", function ()
{
div.parentNode.removeChild( div );
});
}
}
};
</script>
';
$advanced_settings = '<p id="advanced_title_closed" class="bnomics-options-bold">
<a href="javascript:show_advanced()">'.__('Advanced Settings', 'edd-blockonomics').'▼</a>
</p>
<p id="advanced_title_open" class="bnomics-options-bold">
<a href="javascript:show_basic()">'.__('Advanced Settings', 'blockonomics-bitcoin-payments').' ▲</a>
</p>
<script>
let advanced_title_closed = document.getElementById("advanced_title_closed");
let advanced_title_open = document.getElementById("advanced_title_open");
function show_advanced() {
advanced_title_closed.style.display = "none";
advanced_title_open.style.display = "block";
document.querySelectorAll(".edd-blockonomics-advanced").forEach(ele => ele.style.display = "table-row");
}
function show_basic() {
advanced_title_closed.style.display = "block";
advanced_title_open.style.display = "none";
document.querySelectorAll(".edd-blockonomics-advanced").forEach(ele => ele.style.display = "none");
}
document.addEventListener("DOMContentLoaded", function(event) {
show_basic();
});
</script>
';
$blockonomics_settings = array(
array(
'id' => 'edd_blockonomics_api_key',
'name' => __( 'BLOCKONOMICS API KEY', 'edd-blockonomics' ),
'type' => 'text'
),
array(
'id' => 'edd_blockonomics_callback_url',
'name' => $callback_refresh,
'readonly' => true,
'type' => 'text'
),
array(
'id' => 'edd_blockonomics_advanced_settings',
'name' => $advanced_settings,
'readonly' => true,
'type' => 'advanced_settings',
),
array(
'id' => 'edd_blockonomics_timeperiod',
'name' => __('Time period of countdown timer on payment page (in minutes)', 'edd-blockonomics'),
'type' => 'select',
'options' => array(
'10' => '10',
'15' => '15',
'20' => '20',
'25' => '25',
'30' => '30'
),
'class' => 'edd-blockonomics-advanced'
),
array(
'id' => 'edd_blockonomics_margin',
'name' => __('Extra Currency Rate Margin % (Increase live fiat to BTC rate by small percent)', 'edd-blockonomics'),
'type' => 'number',
'max' => 20,
'class' => 'edd-blockonomics-advanced'
),
array(
'id' => 'edd_blockonomics_confirmations',
'name' => __('Network Confirmations required for payment to complete', 'edd-blockonomics'),
'type' => 'select',
'options' => array(
'2' => '2 (recommended)',
'1' => '1',
'zero' => '0'
),
'class' => 'edd-blockonomics-advanced'
),
array(
'id' => 'edd_blockonomics_underpayment_slack',
'name' => __('Underpayment Slack % (Allow payments that are off by a small percentage)', 'edd-blockonomics'),
'type' => 'number',
'max' => 20,
'class' => 'edd-blockonomics-advanced'
),
array(
'id' => 'edd_blockonomics_testsetup',
'name' => $test_setup,
'readonly' => true,
'type' => 'testsetup',
)
);
$blockonomics_settings = apply_filters('edd_blockonomics_settings', $blockonomics_settings);
$settings['blockonomics'] = $blockonomics_settings;
return $settings;
}
public function enqueue_stylesheets(){
wp_enqueue_style('bnomics-style', plugin_dir_url(__FILE__) . "css/order.css");
}
public function enqueue_scripts(){
wp_enqueue_script( 'reconnecting-websocket', plugins_url('js/vendors/reconnecting-websocket.min.js', __FILE__), array(), NULL, true);
wp_enqueue_script( 'qrious', plugins_url('js/vendors/qrious.min.js', __FILE__), array(), NULL, true);
wp_enqueue_script( 'bnomics-checkout', plugins_url('js/checkout.js', __FILE__), array('reconnecting-websocket', 'qrious'), NULL, true);
}
public function get_checkout_script($context) {
$script = "const blockonomics_data = '" . json_encode( array (
'crypto' => $context['crypto'],
'crypto_address' => $context['address'],
'time_period' => edd_get_option('edd_blockonomics_timeperiod', 10),
//Todo: Remove this comment when BCH support is added. The crypto parameter in the end is passed to make it usable for BCH when it comes without making changes
'finish_order_url' => $this->get_edd_url(array('finish_order'=>$context['address'], 'crypto'=> $context['crypto']['code'])),
'get_order_amount_url' => $this->get_edd_url(array('get_amount'=>$context['address'], 'crypto'=> $context['crypto']['code'])),
'payment_uri' => $context['payment_uri']
)). "'";
return $script;
}
public function get_crypto_payment_uri($crypto, $address, $order_amount) {
return $crypto['uri'] . ":" . $address . "?amount=" . $order_amount;
}
public function fix_displaying_small_values($satoshi){
if ($satoshi < 10000){
return rtrim(number_format($satoshi/1.0e8, 8),0);
} else {
return $satoshi/1.0e8;
}
}
public function get_edd_url($query) {
$final_query = array_merge($query, array('edd-listener' => 'blockonomics'));
return add_query_arg($final_query, home_url());
}
public function get_crypto_rate_from_params($value, $satoshi) {
// Crypto Rate is re-calculated here and may slightly differ from the rate provided by Blockonomics
// This is required to be recalculated as the rate is not stored anywhere in $order, only the converted satoshi amount is.
// This method also helps in having a constant conversion and formatting for both JS and NoJS Templates avoiding the scientific notations.
return number_format($value*1.0e8/$satoshi, 2, '.', '');
}
public function get_order_amount_info($address){
$order = $this->process_order($address);
$order_amount = $this->fix_displaying_small_values($order['satoshi']);
$crypto_obj = array(
'code' => 'btc',
'name' => 'Bitcoin',
'uri' => 'bitcoin'
);
$response = array(
"payment_uri" => $this->get_crypto_payment_uri($crypto_obj, $address, $order_amount),
"order_amount" => $order_amount,
"crypto_rate_str" => $this->get_crypto_rate_from_params($order['value'], $order['satoshi'])
);
header("Content-Type: application/json");
exit(json_encode($response));
}
public function process_order($address) {
// Get Order by Address
$order = $this->get_order($address);
if (!isset($order)) {
// Todo: Do Something if the order is not found
}
// Update the order Prices
$order = $this->calculate_order_price_params($order);
// Update the order
$this->update_order($address, $order);
return $order;
}
public function calculate_order_price_params($order){
// Check if order is unused or new
$blockonomics = new BlockonomicsAPI;
if ( $order['status'] == -1) {
$currency = edd_get_currency();
if($currency == 'RIAL'){
$currency = 'IRR';
}
if($currency != 'BTC'){
$price = $blockonomics->get_price($currency);
$price = $price * 100/(100 + edd_get_option('edd_blockonomics_margin', 0));
}else{
$price = 1;
}
$order['currency'] = $currency;
$order['satoshi'] = intval(1.0e8*$order['value']/$price);
}
return $order;
}
public function get_order($address) {
$blockonomics_orders = edd_get_option('edd_blockonomics_orders');
if (isset($blockonomics_orders[$address])) {
return $blockonomics_orders[$address];
}
return NULL;
}
public function update_order($address, $order) {
$blockonomics_orders = edd_get_option('edd_blockonomics_orders');
$blockonomics_orders[$address] = $order;
edd_update_option('edd_blockonomics_orders', $blockonomics_orders);
}
}
/*Call back method for the setting 'testsetup'*/
function edd_testsetup_callback()
{
printf("");
}
function edd_advanced_settings_callback()
{
printf("");
}
function edd_blockonomics_init()
{
$edd_blockonomics = new EDD_Blockonomics;
}
add_action( 'plugins_loaded', 'edd_blockonomics_init' );