-
Notifications
You must be signed in to change notification settings - Fork 1
/
wc-oplatamd.php
651 lines (551 loc) · 20.5 KB
/
wc-oplatamd.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
<?php
/*
Plugin Name: OPLATA.MD Payment Gateway for WooCommerce
Plugin URI: https://github.com/Fruitware/fruitware-woocommerce-oplatamd
Description: Allows you to use Oplata.md payment gateway with the WooCommerce plugin.
Version: 0.1.3
Author: Coroliov Oleg, Fruitware SRL
Author URI: http://fruitware.ru
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/* Add a MDL currency to WooCommerce currencies
------------------------------------------------------------ */
add_filter( 'woocommerce_currencies', 'add_mdl_currency' );
if ( ! function_exists( 'add_mdl_currency' ) ) {
function add_mdl_currency( $currencies ) {
if ( ! isset( $currencies['MDL'] ) ) {
$currencies['MDL'] = __( 'Leu moldovenesc', 'woocommerce' );
}
return $currencies;
}
}
add_filter( 'woocommerce_currency_symbol', 'add_mdl_currency_symbol', 10, 2 );
if ( ! function_exists( 'add_mdl_currency_symbol' ) ) {
function add_mdl_currency_symbol( $currency_symbol, $currency ) {
switch ( $currency ) {
case 'MDL':
$currency_symbol = 'MDL';
break;
}
return $currency_symbol;
}
}
/* Add a custom payment class to WC
------------------------------------------------------------ */
add_action( 'plugins_loaded', 'fruitware_woocommerce_oplatamd', 0 );
function fruitware_woocommerce_oplatamd() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
return;
} // if the WC payment gateway class is not available, do nothing
if ( class_exists( 'WC_Fruitware_Oplatamd_Gateway' ) ) {
return;
}
class WC_Fruitware_Oplatamd_Gateway extends WC_Payment_Gateway {
/**
* @var integer
*/
protected $transaction_id;
/**
* @var WC_Logger
*/
public $log;
public function __construct() {
$plugin_dir = plugin_dir_url( __FILE__ );
$this->supports = array( 'products', 'default_credit_card_form' );
$this->id = 'oplatamd';
$this->icon = apply_filters( 'fruitware_woocommerce_oplatamd_icon', '' . $plugin_dir . 'oplatamd.png' );
$this->has_fields = false;
$this->liveurl = 'https://oplata.md';
$this->testurl = 'https://dev.oplata.md';
// Load the settings
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = $this->get_option( 'title' );
$this->oplatamd_merchant = $this->get_option( 'oplatamd_merchant' );
$this->secret_key = $this->get_option( 'secret_key' );
$this->testmode = 'yes' === $this->get_option( 'testmode', 'no' );
$this->debug = 'yes' === $this->get_option( 'debug', 'no' );
$this->sslverify = 'yes' === $this->get_option( 'sslverify', 'yes' );
$this->description = $this->get_option( 'description' );
$this->instructions = $this->get_option( 'instructions' );
$this->view_transaction_url = $this->get_gateway_url( '/' . $this->get_lang() . '/invoice/%s' );
// Actions
add_action( 'woocommerce_receipt_' . strtolower( $this->id ), array( $this, 'receipt_page' ) );
// Save options
add_action( 'woocommerce_update_options_payment_gateways_' . strtolower( $this->id ), array(
$this,
'process_admin_options'
) );
// Payment listener/API hook
add_action( 'woocommerce_api_wc_' . strtolower( $this->id ), array( $this, 'check_ipn_response' ) );
// Add custom email fields
// add_filter('woocommerce_email_order_meta_fields', array( $this, 'email_order_meta_fields' ), 10, 3);
if ( ! $this->is_valid_for_use() ) {
$this->enabled = false;
}
}
/**
* @param array $fields
* @param $sent_to_admin
* @param WC_Order $order
*
* @return array
*/
// public function email_order_meta_fields( array $fields, $sent_to_admin, WC_Order $order ) {
// $transaction_url = $this->get_transaction_url($order);
// $fields['transaction_id'] = array(
// 'label' => __( 'Oplata.md invoice', 'woocommerce' ),
// 'value' => '<a href="'.$transaction_url.'">'.$transaction_url.'</a>'
// );
//
// return $fields;
// }
/**
* Get a link to the transaction on the 3rd party gateway size (if applicable)
*
* @param WC_Order $order the order object
*
* @return string transaction URL, or empty string
*/
public function get_transaction_url( $order ) {
$return_url = '';
$transaction_id = $order->get_transaction_id();
if ( ! $transaction_id ) {
$transaction_id = get_post_meta( $order->id, 'oplatamd_transaction_id', true );
}
if ( ! empty( $this->view_transaction_url ) && ! empty( $transaction_id ) ) {
$return_url = sprintf( $this->view_transaction_url, $transaction_id );
}
return apply_filters( 'woocommerce_get_transaction_url', $return_url, $order, $this );
}
/**
* Logging method
*
* @param string $message
*/
public function log( $message ) {
if ( ! $this->debug ) {
return;
}
if ( ! $this->log ) {
global $woocommerce;
if ( version_compare( WOOCOMMERCE_VERSION, '2.1', '<' ) ) {
$this->log = $woocommerce->logger();
} else {
$this->log = new WC_Logger();
}
}
$this->log->add( 'oplatamd', $message );
}
/**
* Check if this gateway is enabled and available in the user's country
*/
function is_valid_for_use() {
if ( ! in_array( get_option( 'woocommerce_currency' ), array( 'MDL' ) ) ) {
return false;
}
return true;
}
/**
* Admin Panel Options
* - Options for bits like 'title' and availability on a country-by-country basis
*
* @since 0.1
**/
public function admin_options() {
?>
<h3><?php _e( 'OPLATA.MD', 'woocommerce' ); ?></h3>
<p><?php _e( 'Настройка приема электронных платежей через Merchant OPLATA.MD.', 'woocommerce' ); ?></p>
<?php if ( $this->is_valid_for_use() ) : ?>
<table class="form-table">
<?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?>
</table><!--/.form-table-->
<?php else : ?>
<div class="inline error"><p><strong><?php _e( 'Шлюз отключен',
'woocommerce' ); ?></strong>: <?php _e( 'OPLATA.MD не поддерживает валюты Вашего магазина.', 'woocommerce' ); ?>
</p>
</div>
<?php
endif;
} // End admin_options()
/**
* Initialise Gateway Settings Form Fields
*
* @access public
* @return void
*/
function init_form_fields() {
$debug = __( 'Включить логирование (<code>woocommerce/logs/' . $this->id . '.txt</code>)', 'woocommerce' );
if ( ! version_compare( WOOCOMMERCE_VERSION, '2.0', '<' ) ) {
if ( version_compare( WOOCOMMERCE_VERSION, '2.2.0', '<' ) ) {
$debug = str_replace( $this->id, $this->id . '-' . sanitize_file_name( wp_hash( $this->id ) ), $debug );
} elseif ( function_exists( 'wc_get_log_file_path' ) ) {
$debug = str_replace( 'woocommerce/logs/' . $this->id . '.txt', wc_get_log_file_path( $this->id ), $debug );
}
}
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Включить/Выключить', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Включен', 'woocommerce' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Название', 'woocommerce' ),
'type' => 'text',
'description' => __( 'Это название, которое пользователь видит во время проверки.', 'woocommerce' ),
'default' => __( 'OPLATA.MD', 'woocommerce' )
),
'testmode' => array(
'title' => __( 'Тест режим', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Включен', 'woocommerce' ),
'description' => __( 'В этом режиме плата за товар не снимается.<br>Для тестового режима: <label style="font-weight: 700;" for="fruitware_woocommerce_oplatamd_oplatamd_merchant">Название проекта</label>: "demoshop" и <label style="font-weight: 700;" for="fruitware_woocommerce_oplatamd_secret_key">Секретный ключ</label>: "950856916534772"',
'woocommerce' ),
'default' => 'no'
),
'oplatamd_merchant' => array(
'title' => __( 'Название проекта', 'woocommerce' ),
'type' => 'text',
'description' => __( 'Пожалуйста введите Название проекта (projectsTitle).', 'woocommerce' ),
'default' => 'demoshop'
),
'secret_key' => array(
'title' => __( 'Секретный ключ', 'woocommerce' ),
'type' => 'password',
'description' => __( 'Пожалуйста введите Секретный ключ (secretKey).<br />', 'woocommerce' ),
'default' => ''
),
'debug' => array(
'title' => __( 'Debug', 'woocommerce' ),
'type' => 'checkbox',
'label' => $debug,
'default' => 'no'
),
'sslverify' => array(
'title' => __( 'Verify ssl certificate', 'woocommerce' ),
'type' => 'checkbox',
'label' => __( 'Включен', 'woocommerce' ),
'description' => __( 'Выключать проверку, только если есть проблема с проверкой сертификатов', 'woocommerce' ),
'default' => 'yes'
),
'description' => array(
'title' => __( 'Description', 'woocommerce' ),
'type' => 'textarea',
'description' => __( 'Описанием метода оплаты которое клиент будет видеть на вашем сайте.', 'woocommerce' ),
'default' => 'Оплата с помощью oplata.md.'
),
'instructions' => array(
'title' => __( 'Instructions', 'woocommerce' ),
'type' => 'textarea',
'description' => __( 'Инструкции, которые будут добавлены на страницу благодарностей.', 'woocommerce' ),
'default' => 'Оплата с помощью oplata.md.'
),
);
}
/**
* There are no payment fields for sprypay, but we want to show the description if set.
**/
function payment_fields() {
if ( $this->description ) {
echo wpautop( wptexturize( $this->description ) );
}
}
/**
* Generate the dibs button link
*
* @param WC_Order $order
*
* @return bool|string
*/
public function generate_form( WC_Order $order ) {
$invoice = $this->create_invoice( $order );
// $invoice = '2cd7eaf4-576b-7db4-dfe1-26005a951e81'; // test
if ( is_wp_error( $invoice ) ) {
return '<a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __( 'Отказаться от оплаты & вернуться в корзину',
'woocommerce' ) . '</a>';
}
return
'<a class="button alt" href="' . $this->get_gateway_url( '/' . $this->get_lang() . '/invoice/' . $invoice ) . '">' . __( 'Оплатить',
'woocommerce' ) . '</a>
<a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __( 'Отказаться от оплаты & вернуться в корзину',
'woocommerce' ) . '</a>';
}
/**
* Process the payment and return the result
*
* @param int $order_id
*
* @return array|bool
*/
public function process_payment( $order_id ) {
if ( ! $order = $this->get_order_by_id( $order_id ) ) {
return false;
}
return array(
'result' => 'success',
'redirect' => add_query_arg( 'order',
$order->id,
add_query_arg( 'key', $order->order_key, $order->get_checkout_payment_url( true ) ) )
);
}
/**
* receipt_page
**/
function receipt_page( $order_id ) {
if ( ! $order = $this->get_order_by_id( $order_id ) ) {
return false;
}
$transaction_id = get_post_meta( $order->id, 'oplatamd_transaction_id', true );
if ( ! $transaction_id ) {
$transaction_id = $this->create_invoice( $order );
}
do_action( 'woocommerce_api_wc_' . strtolower( $this->id ), $order );
// $transaction_id = '2cd7eaf4-576b-7db4-dfe1-26005a951e81'; // test
if ( is_wp_error( $transaction_id ) ) {
echo '<p>' . __( 'Произошка ошибка. Перезагрузите страницу что бы попробовать ещё раз.', 'woocommerce' ) . '</p>';
} else {
echo '<p>' . __( 'Спасибо за Ваш заказ, пожалуйста, нажмите кнопку ниже, чтобы заплатить.', 'woocommerce' ) . '</p>';
echo ' <a class="button alt" href="' . $this->get_gateway_url( '/' . $this->get_lang() . '/invoice/' . $transaction_id ) . '">' . __( 'Оплатить', 'woocommerce' ) . '</a>';
}
echo
' <a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __( 'Отказаться от оплаты & вернуться в корзину', 'woocommerce' ) . '</a>';
}
/**
* Check Response
**/
public function check_transaction( WC_Order $order ) {
$invoice = $this->view_invoice( $order );
// $invoice = json_decode('{"ordersId":"174","invoiceId":"33961","invoiceAmount":"150.00","invoiceEmail":"email@email.email","invoiceDate":null,"invoiceStatus":"10"}', true); // test
if ( is_wp_error( $invoice ) ) {
$this->log( 'View invoice failed: ' . $invoice->get_error_message() );
return false;
}
switch ( $invoice['invoiceStatus'] ) {
case '0': // Not paid
return false;
break;
case '1': // Created
return false;
break;
case '5': // Error
$order->update_status( 'failed', __( 'Ошибка оплаты', 'woocommerce' ) );
return $order->get_cancel_order_url();
break;
case '10': // Paid
WC()->cart->empty_cart();
$transaction_id = get_post_meta( $order->id, 'oplatamd_transaction_id', true );
$order->payment_complete( $transaction_id );
add_post_meta( $order->id, 'is_payed', 1 );
delete_post_meta( $order->id, 'oplatamd_transaction_id' );
return $this->get_return_url( $order );
break;
case '20': // Money Return
$order->update_status( 'refunded', __( 'Платеж возвращён', 'woocommerce' ) );
delete_post_meta( $order->id, 'is_payed' );
return $order->get_cancel_order_url();
break;
}
}
/**
* Check Response with redirect to front
**/
public function check_ipn_response( WC_Order $order ) {
$url = $this->check_transaction( $order );
if ( $url !== false ) {
wp_redirect( $url );
} else {
return false;
}
}
/**
* Create an invoice for order via OPLATA.MD
*
* @param WC_Order $order
*
* @return array|wp_error The parsed response from OPLATA.MD, or a WP_Error object
*/
protected function create_invoice( WC_Order $order ) {
$url = $this->get_gateway_url( '/invoice/createInvoice' );
$args = $this->get_invoice_args_by_order( $order, 'create' );
$args['checksum'] = $this->generate_checksum( $order, 'create' );
//var_dump(http_build_query($args));die;
apply_filters( 'fruitware_woocommerce_oplatamd_args', $args );
$response = wp_safe_remote_post(
$url,
array(
'method' => 'POST',
'body' => $args,
'timeout' => 30,
'user-agent' => 'WooCommerce',
'httpversion' => '1.1',
'sslverify' => $this->sslverify,
)
);
if ( is_wp_error( $response ) ) {
$this->log( 'Create invoice request error >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . $response->get_error_message() );
return $response;
}
if ( empty( $response['body'] ) ) {
$this->log( 'Create invoice request error >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . json_encode( $response ) );
return new WP_Error( 'oplatamd-create-invoice', 'Empty Response' );
}
$transaction_id = $response['body'];
$this->log( 'Create invoice request success >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . $transaction_id );
update_post_meta( $order->id, 'oplatamd_transaction_id', sanitize_text_field( $transaction_id ) );
return $transaction_id;
}
/**
* Create an invoice for order via OPLATA.MD
*
* @param WC_Order $order
*
* @return array|wp_error The parsed response from OPLATA.MD, or a WP_Error object
*/
protected function view_invoice( WC_Order $order ) {
$url = $this->get_gateway_url( '/invoice/viewInvoice' );
$args = $this->get_invoice_args_by_order( $order, 'view' );
$args['checksum'] = $this->generate_checksum( $order, 'view' );
//var_dump(http_build_query($args));die;
apply_filters( 'fruitware_woocommerce_oplatamd_args', $args );
$response = wp_safe_remote_post(
$url,
array(
'method' => 'POST',
'body' => $args,
'timeout' => 30,
'user-agent' => 'WooCommerce',
'httpversion' => '1.1',
'sslverify' => $this->sslverify,
)
);
if ( is_wp_error( $response ) ) {
$this->log( 'View invoice request error >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . $response->get_error_message() );
return $response;
}
if ( empty( $response['body'] ) ) {
$this->log( 'View invoice request error >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . json_encode( $response ) );
return new WP_Error( 'oplatamd-view-invoice', 'Empty Response' );
}
$answer = json_decode( $response['body'], true );
if ( ! isset( $answer['invoiceStatus'] ) ) {
$this->log( 'View invoice request error >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . json_encode( $answer ) );
$data = array( 'request' => $args, 'response' => $answer );
return new WP_Error( 'oplatamd-view-invoice', 'View invoice request error', json_encode( $data ) );
}
$this->log( 'View invoice request success >>>>>>: ' . json_encode( $args ) . ' <<<<<<< ' . json_encode( $answer ) );
return $answer;
}
/**
* @param WC_Order $order
*
* @return string
*/
protected function generate_checksum( WC_Order $order, $type ) {
$args = $this->get_invoice_args_by_order( $order, $type );
$args['secretKey'] = $this->secret_key;
return md5( implode( '::', $args ) );
}
/**
* @param WC_Order $order
* @param string $type
*
* @return string
*/
protected function get_invoice_args_by_order( WC_Order $order, $type ) {
switch ( $type ) {
case 'create':
// checksum = md5(ordersId::projectsTitle::ordersAmount::ordersStatusLink::cartEmail::timestamp::secretKey)
$args = array(
'ordersId' => $order->id,
'projectsTitle' => $this->oplatamd_merchant,
'ordersAmount' => $this->number_format( $order->order_total ),
'ordersStatusLink' => $order->get_checkout_payment_url( true ),
//get_permalink( woocommerce_get_page_id( 'thanks' ) ),
'cartEmail' => $order->billing_email,
'timestamp' => strtotime( $order->order_date ),
);
break;
case 'view':
// checksum = md5(ordersId::projectsTitle::ordersAmount::timestamp::secretKey)
$args = array(
'ordersId' => $order->id,
'projectsTitle' => $this->oplatamd_merchant,
'ordersAmount' => $this->number_format( $order->order_total ),
'timestamp' => strtotime( $order->order_date ),
);
break;
default:
throw new \RuntimeException( 'Invalid type' );
break;
}
return $args;
}
/**
* Get current wp lang
*
* @return string
*/
protected function get_lang() {
if ( function_exists( 'qtrans_getLanguage' ) ) {
$lang = qtrans_getLanguage();
} elseif ( function_exists( 'qtranxf_getLanguage' ) ) {
$lang = qtranxf_getLanguage();
} else {
$locale = explode( '_', get_locale() );
$lang = @$locale[0];
}
return $lang == 'ru' ? 'ru' : 'ro';
}
/**
* @param integer $order_id
*
* @return bool|WC_Order
*/
protected function get_order_by_id( $order_id ) {
$order = new WC_Order( $order_id );
if ( ! $order ) {
$this->log->add( 'oplatamd', 'Error: Order ID not found.' );
return false;
}
return $order;
}
/**
* Format prices
*
* @param float|int $price
*
* @return float|int
*/
protected function number_format( $price ) {
$decimals = 2;
return number_format( $price, $decimals, '.', '' );
}
/**
* @param string $path
*
* @return string
*/
protected function get_gateway_url( $path = '' ) {
return ( $this->testmode ? $this->testurl : $this->liveurl ) . $path;
}
}
/**
* Add the gateway to WooCommerce
*
* @param array $methods
*
* @return array
*/
function add_gateway( array $methods ) {
$methods[] = 'WC_Fruitware_Oplatamd_Gateway';
return $methods;
}
add_filter( 'woocommerce_payment_gateways', 'add_gateway' );
}