-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathclass-woo-kyber-payment-gateway.php
684 lines (587 loc) · 21.6 KB
/
class-woo-kyber-payment-gateway.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
<?php
require_once dirname(__DIR__, 1) . '/vendor/autoload.php';
use Web3\Utils;
use chillerlan\QRCode\QRCode;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
*
* @link developer.kyber.network
* @since 0.0.1
*
* @package Woo_Kyber_Payment
* @subpackage Woo_Kyber_Payment/includes
*/
class WC_Kyber_Payment_Gateway extends WC_Payment_Gateway {
protected $supported_tokens = array();
public function __construct() {
$this->id = 'kyber';
$this->method_title = __( 'Kyber', 'woocommerce-gateway-kyber' );
$this->method_description = sprintf( __('Kyber allow user to pay by using tokens', 'woocommerce-gateway-kyber') );
$this->order_button_text = __( 'Place order', 'woocommerce-gateway-kyber' );
$this->has_fields = true;
$this->supports = array(
'products',
'refunds',
'tokenization',
'add_payment_method'
);
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option( 'title' );
$this->enabled = $this->get_option( 'enabled' );
$this->description = $this->get_option( 'description' );
$this->network = $this->get_option( 'network' );
$this->description = $this->get_option( 'description' );
if ( $this->network == "ropsten" ) {
$this->description .= sprintf( __(" TESTMODE is enabled. The payment by this method now will not be proceed.", "woocommerce-gateway-kyber") );
}
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_api_kyber_callback', array( $this, 'handle_kyber_callback' ) );
add_action( 'woocommerce_order_details_after_order_table_items', array( $this, 'add_tx_hash_to_order' ) );
add_action( 'woocommerce_thankyou', array( $this, 'embed_kyber_widget_button' ) );
// add_action( 'woocommerce_admin_order_totals_after_total', array( $this, 'kyber_price_filter' ) );
add_action( 'woocommerce_email_order_meta', array( $this, 'add_tx_hash_to_email' ), 10, 3 );
}
/**
* Init admin settings fields
*
* @since 0.0.1
*/
public function init_form_fields() {
$this->form_fields = require( plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/kyber-settings.php' );
}
/**
* Processes and saves options.
* If there is an error thrown, will continue to save and validate fields, but will leave the erroring field out.
* @return bool was anything saved?
*/
public function process_admin_options() {
$this->init_settings();
$post_data = $this->get_post_data();
foreach ( $this->get_form_fields() as $key => $field ) {
if ( 'title' !== $this->get_field_type( $field ) ) {
try {
$this->settings[ $key ] = $this->get_field_value( $key, $field, $post_data );
} catch ( Exception $e ) {
$this->add_error( $e->getMessage() );
}
}
}
return update_option( $this->get_option_key(), apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings ) );
}
/**
* Validate title field
*
* @param $key string title
* @param $value string
*
* @return $value if valid
*
* @since 0.0.3
*/
public function validate_title_field( $key, $value ) {
$value = trim( $value );
if ( $value == "" ) {
$this->add_error( "title should not be empty" );
// $this->display_errors();
} else {
return $value;
}
}
/**
* Validate receive address
*
* @param $key string receive_addr
* @param $value string
*
* @return $value if valid else display error
*
* @since 0.0.3
*/
public function validate_receive_addr_field( $key, $value ) {
if ( !Utils::isAddress($value) ) {
$this->add_error( "receive address is not valid" );
// $this->display_errors();
} else {
return $value;
}
}
/**
* Validate receive token symbold
*
* @param $key string receive_token_symbol
* @param $value string|null
* @return $value if valid else display error
*
* @since 0.0.3
*/
public function validate_receive_token_symbol_field( $key, $value ) {
$support_tokens = $this->get_list_token_supported();
if ( !in_array( $value, $support_tokens ) ) {
$this->add_error( "receive token is not supported" );
// $this->display_errors();
} else {
return $value;
}
}
/**
* Validate mode field
* @param $key string mode
* @param $value string
*
* @return $value if valid
* @since 0.0.3
*/
public function validate_mode_field( $key, $value ) {
$modes = array("iframe", "tab", "popup");
if ( !in_array( $value, $modes ) ) {
$this->add_error( "Widget mode is not valid" );
// $this->display_errors();
} else {
return $value;
}
}
/**
* Validate block confirmation field
*
* $key block_confirmation
* $value input value
*
* return $value if valid/display error if not valid
* @since 0.0.3
*/
public function validate_block_confirmation_field( $key, $value ) {
if ( $value < 1 ) {
$this->add_error( "block confirmation must greater than 0" );
$this->display_errors();
} else {
$this->display_errors();
return $value;
}
}
/**
* Insert Kyber logo into checkout page
*
* @param null
* @return string gateway icon
*
* @since 0.0.1
*/
public function get_icon() {
$icons_str = '<img src="' . WC_KYBER_PLUGIN_URL . '/admin/images/kyber.svg" class="kyber-icon" alt="Kyber" />';
return apply_filters( 'woocommerce_gateway_icon', $icons_str, $this->id );
}
/**
* Get list token supported from kyber
*
* @param null
* @return array list of supported token
*
* @since 0.0.1
*/
public function get_list_token_supported() {
$network = $this->get_option('network');
if ( $network == "ropsten" ) {
$tracker_url = 'https://ropsten-api.kyber.network/currencies';
} else {
$tracker_url = 'https://api.kyber.network/currencies';
}
$response = wp_remote_get( $tracker_url );
$response_body= $response['body'];
$data = json_decode( $response_body );
$result = array();
for ( $index = 0; $index < count( $data->data ); $index++ ) {
$result[$data->data[$index]->symbol] = $data->data[$index]->symbol;
}
return $result;
}
public function get_token_rate( $token, $base ) {
$network = $this->get_option('network');
if ( $network == "ropsten" ) {
$tracker_url = sprintf('https://ropsten-api.kyber.network/token_price?currency=%s', $base);
} else {
$tracker_url = sprintf('https://api.kyber.network/token_price?currency=%s', $base);
}
$response = wp_remote_get( $tracker_url );
$response_body= $response['body'];
$data = json_decode( $response_body );
$rate = 0;
for ( $index = 0; $index < count( $data->data ); $index++ ) {
if ( $data->data[$index]->symbol == $token ) {
$rate = $data->data[$index]->price;
break;
}
}
return $rate;
}
/**
* Override process_payment from WC_Payment_Gateway class
*
* @param integer order id
* @return array redirect to place order payment
*
* @since 0.0.1
*/
public function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
// check if setting is correct for payment
$setting_ok = $this->validate_gateway_settings();
if ( !$setting_ok ) {
return;
}
// update order network is current network setting
$order->update_meta_data( 'network', $this->get_option( 'network' ) );
// update order receive address is current receive address
$order->add_meta_data( 'receive_addr', $this->get_option( 'receive_addr' ), true );
// update order receive symbol is current receive symbol
$order->add_meta_data( 'receive_symbol', $this->get_option( 'receive_token_symbol' ), true );
$order->save();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
/**
* Display transaction hash on order detail page
*
* @param WC_Abstract_Order order
* @return string transaction hash
*
* @since 0.0.1
*/
public function add_tx_hash_to_order( $order ) {
$order_tx = $order->get_meta("tx");
$network = $order->get_meta( 'network' );
$tx_status = $order->get_meta( 'tx_status' );
$response = '';
if ( $order_tx != "" ) {
if ( $network == "ropsten" ) {
$etherscan_url = sprintf("https://%s.etherscan.io/tx/%s", $network, $order_tx);
} else {
$etherscan_url = sprintf("https://etherscan.io/tx/%s", $order_tx);
};
$response .= sprintf("<tr class='woocommerce-table__line-item order_item' >
<td class='woocommerce-table__product-name product-name'>
%s </td>
<td class='woocommerce-table__product-total product-total order-tx-hash'>
<a href='%s' target='_blank'>%s</a>
</td></tr>", __('Order transaction hash', 'woocommerce-gateway-kyber'), $etherscan_url, $order_tx);
}
if ( $tx_status != "" ) {
$response .= sprintf("<tr class='woocommerce-table__line-item order_item' >
<td class='woocommerce-table__product-name product-name'>
%s </td>
<td class='woocommerce-table__product-total product-total'>
%s
</td></tr>", __('Tx Status', 'woocommerce-gateway-kyber'), $tx_status);
}
if ( $network != "" ) {
$response .= sprintf("<tr class='woocommerce-table__line-item order_item' >
<td class='woocommerce-table__product-name product-name'>
%s </td>
<td class='woocommerce-table__product-total product-total'>
%s
</td></tr>", __('Network', 'woocommerce-gateway-kyber'), $network);
}
echo $response;
}
/**
* Check if Kyber g,ateway config is correct
*
* @return bool
*
* @since 0.0.1
*/
public function validate_gateway_settings() {
$receiveAddr = $this->get_option( 'receive_addr' );
if ( !$receiveAddr ) {
wc_add_notice( __('Receive address is empty. You cannot use pay by token, please contact your shop about this issue', 'woocommerce-gateway-kyber'), 'error' );
return false;
}
$receiveToken = $this->get_option( 'receive_token_symbol' );
if ( !$receiveToken ) {
wc_add_notice( __('Receive token is not supported.', 'woocommerce-gateway-kyber'), 'error' );
return false;
}
$network = $this->get_option( 'network' );
if ( $network != 'ropsten' && $network != 'mainnet' ) {
wc_add_notice( __('Network is not valid.', 'woocommerce-gateway-kyber'), 'error' );
return false;
}
$mode = $this->get_option( 'mode' );
if ( $mode != 'tab' && $mode != 'iframe' && $mode != 'popup' ) {
wc_add_notice( __('Widget mode is not valid.', 'woocommerce-gateway-kyber'), 'error' );
return false;
}
return true;
}
/**
* Build Kyber widget redirect url
*
* @param WC_Abstract_Order $order
* @return string checkout url for widget
*
* @since 0.0.1
*/
public function get_checkout_url( $order ) {
// $version = $this->get_option( 'version' );
$endpoint = "https://widget.kyber.network/v0.6.2/?type=pay&theme=light¶mForwarding=true&";
$callback_url = get_site_url() . '/wc-api/kyber_callback';
if ( !$this->validate_gateway_settings() ) {
return;
}
$receiveAddr = $this->get_option( 'receive_addr' );
$receiveToken = $this->get_option( 'receive_token_symbol' );
$network = $order->get_meta( 'network' );
if ( !$network ) {
return;
}
$mode = $this->get_option( 'mode' );
$receiveAmount = $order->get_meta( 'token_price' );
if ( !$receiveAmount ) {
$receiveAmount = $this->get_token_price( $order );
error_log( print_r( sprintf("cannot get token price from order meta data, try to get from blockchain: %s", $receiveAmount), 1 ) );
$order->add_meta_data( "token_price", $receiveAmount, true );
$order->save();
}
$endpoint .= 'mode='. $mode .'&receiveAddr=' . $receiveAddr . '&receiveToken=' . $receiveToken . '&callback=' . $callback_url . '&receiveAmount=' . $receiveAmount;
$endpoint .= '&network=' . $network;
// commission id is optional
$commissionID = $this->get_option( 'commission_id' );
if ( $commissionID ) {
$endpoint .= '&commissionId=' . $commissionID;
}
// add custom params
$order_id = $order->get_id();
$endpoint .= '&order_id=' . strval($order_id);
// paymentData will be store on blockchain
$endpoint .= '&paymentData=' . strval($order_id);
return $endpoint;
}
/**
* Handle callback from Kyber widget
*
* @since 0.0.1
*
*/
public function handle_kyber_callback() {
if ( ( 'POST' !== $_SERVER['REQUEST_METHOD'] )) {
return;
}
$request_body = file_get_contents( 'php://input' );
$request_header = $this->get_request_headers();
if ( strpos($request_header['Content-Type'], 'application/x-www-form-urlencoded') !== false ) {
parse_str( $request_body, $dataStr );
$dataJSON = json_encode($dataStr);
$data = json_decode($dataJSON);
}
$valid = $this->validate_callback_params($data);
header( "Access-Control-Allow-Origin: *", true );
if ( !$valid ) {
status_header( 403 );
die();
}
// get data from callback
$order_id = $data->order_id;
$tx = $data->tx;
$network = $data->network;
$order = wc_get_order( $order_id );
// check if network from callback is match with order network
// if not the pay is not valid - ignore
if ( $network != $order->get_meta( 'network' ) ) {
return;
}
// Reduce stock levels
wc_reduce_stock_levels($order_id);
// Save transaction hash to order
$order->update_meta_data("tx", $tx);
$order->update_meta_data("network", $network);
$order->add_meta_data("tx_status", "pending", true);
$order->update_meta_data("payment_time", time());
$order->save();
// Mark as on-hold (we're awaiting cheque)
$order->update_status('on-hold', __("Awaiting cheque payment", "woocommerce-gateway-kyber"));
}
/**
* Check if transaction hash already saved in db
*
* @param string tx
* @return bool
*
* @since 0.0.1
*/
public function transaction_exists($tx, $order_id) {
$args = array(
'post_type' => 'shop_order',
'post_status' => array('wc-cancelled','wc-on-hold', 'wc-processing', 'wc-pending-payment', 'wc-completed', 'wc-refunded', 'wc-failed'),
'numberposts' => 5,
'meta_key' => 'tx',
'meta_value' => $tx,
);
$current_post = get_posts($args);
if( $current_post && $current_post[0]->ID != $order_id ) {
return true;
} else {
return false;
}
}
/**
* Validate callback params
*
* @since 0.0.1
*/
private function validate_callback_params( $request ) {
$order_id = $request->order_id;
$tx = $request->tx;
if ( $this->transaction_exists($tx, $order_id) ) {
return false;
}
return true;
}
/**
* Gets the incoming request headers. Some servers are not using
* Apache and "getallheaders()" will not work so we may need to
* build our own headers.
*
* @since 0.0.1
* @version 0.0.1
*/
public function get_request_headers() {
if ( ! function_exists( 'getallheaders' ) ) {
$headers = array();
foreach ( $_SERVER as $name => $value ) {
if ( 'HTTP_' === substr( $name, 0, 5 ) ) {
$headers[ str_replace( ' ', '-', ucwords( strtolower( str_replace( '_', ' ', substr( $name, 5 ) ) ) ) ) ] = $value;
}
}
return $headers;
} else {
return getallheaders();
}
}
/**
*
* Embed widget into order received page
*
* @param integer order id
* @return string widget button
*
* @since 0.0.1
*/
public function embed_kyber_widget_button( $order_id ) {
$order = wc_get_order($order_id);
$order_status = $order->get_status();
if ( $order->get_payment_method() == 'kyber' && ( $order_status == "pending" || $order_status == "failed" ) ) {
$endpoint = $this->get_checkout_url( $order );
$widget_text = apply_filters( 'kyber_widget_text', __('Pay by tokens', 'woocommerce-gateway-kyber') );
$qr = (new QRCode)->render($endpoint);
printf("
<div class='kyber-payment-button-wrap'>
<div class='kyber-payment-link-wrap'>
<a href='%s' class='theme-emerald kyber-widget-button' name='KyberWidget - Powered by KyberNetwork' title='Pay by tokens' target='_blank'>%s</a>
</div>
<div class='kyber-payment-qr-wrap'>
<img src='%s' class='kyber-payment-qr' />
</div>
</div>", $endpoint, $widget_text, $qr);
}
}
/**
* Get token rate from dai to receive token and return it in payment method description
*
* @return string token price for cart
* @since 0.2
*/
public function payment_fields() {
$description = $this->description;
if ( $description ) {
echo $description;
}
$total = WC()->cart->total;
if (!$total) {
global $wp;
$order_id = $wp->query_vars['order-pay'];
$order = new WC_Order( $order_id );
$total = $order->get_total();
}
$receiveToken = $this->get_option( "receive_token_symbol" );
$rate = $this->get_token_rate( $receiveToken, "USD" );
$token_price = 0;
if ( $rate != 0 ) {
$token_price = $total / $rate;
}
if ( $receiveToken != "ETH" ) {
$rate_eth = $this->get_token_rate( $receiveToken, "ETH" );
} else {
$rate_eth = 1;
}
if ( $token_price*$rate_eth < 0.001 ) {
$token_price_html = sprintf(
"<br><br>
<p>Total value of token is <strong>%f%s</strong> which is smaller than <strong>0.001ETH</strong>.
Kyber Widget only can handle amount which is equal or bigger than <strong>0.001ETH</strong> equivalent. Please add more items or choose another payment method.</p>", $token_price, $receiveToken);
echo $token_price_html;
return;
};
$token_price_html = sprintf('</br><p></p>
<div class="kyber-cart-token-price">
<img style="float:left; margin-right: 5px;" src="%s" height="24px" width="24px">
<strong>%.5f</strong>
<span class="receive-token"><strong>%s</strong></span>
</div>',
esc_html(sprintf("https://files.kyber.network/DesignAssets/tokens/%s.svg", strtolower($receiveToken))),
esc_html($token_price),
esc_html($receiveToken));
echo $token_price_html;
}
/**
* Get token price for order
*
* @return float token price
*
* @since 0.2
*/
public function get_token_price( $order ) {
$receiveToken = $this->get_option( "receive_token_symbol" );
$rate = $this->get_token_rate( $receiveToken, "USD" );
$token_price = 0;
if ( $rate != 0 ) {
$token_price = $order->get_total() / $rate;
}
$order->add_meta_data( "token_price", $token_price, true );
$order->save();
return $token_price;
}
/**
* Add tx hash to email
*
* @return string order meta data
*
* @since 0.3
*/
public function add_tx_hash_to_email( $order, $sent_to_admin, $plain_text ) {
$tx_hash = $order->get_meta( "tx" );
if ( empty($tx_hash) ) {
return;
}
$network = $order->get_meta( "network" );
$etherscan_url = "https://etherscan.io/tx/" + $tx_hash;
if ( $network == "ropsten" ) {
$etherscan_url = sprintf("https://%s.etherscan.io/tx/%s", $network, $tx_hash);
}
$metadata = "";
if ($plain_text) {
$metadata = sprintf("Transaction hash: %s", $tx_hash);
} else {
$metadata = "<h3>Transaction hash: </h3>";
$metadata .= sprintf("<a href='%s'>
%s
</a>", $etherscan_url, $tx_hash);
}
echo $metadata;
}
}