-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwc-payneteasy.php
More file actions
482 lines (378 loc) · 19.5 KB
/
wc-payneteasy.php
File metadata and controls
482 lines (378 loc) · 19.5 KB
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
<?php
/**
* Plugin Name: Payneteasy payment system
* Plugin URI: https://github.com/payneteasy/php-plugin-woocommerce?tab=readme-ov-file#php-plugin-for-woocommerce-wordpress
* Description: Allows you to use payment system Payneteasy with the WooCommerce.
* Version: 1.2.2
* Author: Payneteasy
* Author URI: https://payneteasy.com/
* Text Domain: wc-payneteasy
* Domain Path: /languages/
* Requires PHP: 7.4
* Requires Plugins: woocommerce/woocommerce
*
* @package Payneteasy
* @version 1.2.2
*/
if (!defined('ABSPATH')) exit; # Exit if accessed directly
require __DIR__.'/vendor/autoload.php';
require __DIR__.'/hooks.php';
define('PAYNETEASY_LIB', true);
include_once('lib'.DIRECTORY_SEPARATOR.'Api.php');
use Payneteasy\lib;
add_action('plugins_loaded', 'hook_init_wc_paynet_payment_gateway');
function hook_init_wc_paynet_payment_gateway(): void {
if (!class_exists('WC_Payment_Gateway') || class_exists('WC_Payneteasy'))
return;
add_filter('plugin_action_links_' .plugin_basename(__FILE__), ['WC_Payneteasy', 'hook_plugin_action_links']);
add_filter('pre_set_site_transient_update_plugins', ['WC_Payneteasy', 'hook_plugin_check_version']);
add_filter('plugins_api', ['WC_Payneteasy', 'hook_plugin_update_info'], 20, 3);
class WC_Payneteasy extends WC_Payment_Gateway {
private const GITHUB_REPO = 'payneteasy/php-plugin-woocommerce';
private bool $require_ssn;
private string $transaction_end;
private string $notify_url;
private $Api;
private object $order;
private static string $admin_error;
function __construct() {
$this->id = 'wc_payneteasy';
$this->icon = apply_filters('woocommerce_payneteasy_icon', plugin_dir_url(__FILE__).'payneteasy.png');
$this->method_title = __('Payneteasy online card payment system v1.2.2', 'wc-payneteasy');
$this->method_description = __('Allows you to use online card payment system by Payneteasy with the WooCommerce.', 'wc-payneteasy');
$this->has_fields = false;
$s = $this->init_payment_settings();
$this->Api = new Payneteasy\lib\Api($s['gate'], $s['login'], $s['control_key'], $s['endpoint_id'], $s['is_direct']);
$this->init_form_fields();
$this->init_settings();
add_filter('wc_order_statuses', [$this, 'order_statuses']);
add_action('woocommerce_update_options_payment_gateways_'.$this->id, [$this, 'process_admin_options']);
add_action('woocommerce_api_'.$this->id.'_return', [$this, 'hook_return_handler']);
add_action('woocommerce_api_'.$this->id.'_webhook', [$this, 'hook_webhook_handler']);
add_action('woocommerce_api_'.$this->id.'_ajax', [$this, 'hook_ajax_handler']);
}
public static function hook_plugin_action_links(array $links): array
{ return array_merge([ 'settings' => '<a href="' .admin_url('admin.php?page=wc-settings&tab=checkout§ion=wc_payneteasy') .'">Settings</a>' ], $links); }
public static function hook_plugin_update_info($rv, $action, $args) {
if ('plugin_information' != $action || plugin_basename(__DIR__) != $args->slug)
return $rv;
return (object)self::fetch_update_json($rv);
}
private static function fetch_update_json($failret = null): ?array {
if (!($json_str = get_transient(self::GITHUB_REPO))) {
if (!empty($json_str = wp_remote_retrieve_body( wp_remote_get(sprintf('https://raw.githubusercontent.com/%s/refs/heads/main/.update.json', self::GITHUB_REPO)) )))
set_transient(self::GITHUB_REPO, $json_str, HOUR_IN_SECONDS);
else
return $failret;
}
return json_decode($json_str, true);
}
public static function hook_plugin_check_version(stdClass $T): stdClass {
if (empty($T->checked))
return $T;
if (empty($json = self::fetch_update_json()))
return $T;
$info = (object)$json;
if ($info->version != $T->checked[$entry = plugin_basename(__FILE__)]) {
$is_pkg_avail = wp_remote_head($pkg_url = sprintf('https://github.com/%s/releases/download/v%s/php-plugin-woocommerce.zip', self::GITHUB_REPO, $info->version));
$T->response[$entry] = (object)[
'plugin' => $entry,
'slug' => $info->slug,
'new_version' => $info->version,
'requires' => $info->requires,
'requires_php' => $info->requires_php,
'package' => (is_wp_error($is_pkg_avail) || !in_array(wp_remote_retrieve_response_code($is_pkg_avail), [ 200, 302 ])) ? '' : $pkg_url,
'url' => 'https://github.com/payneteasy/php-plugin-woocommerce/blob/main/README.md#php-plugin-for-woocommerce-wordpress' ];
}
else
$T->no_update[$entry] = (object)[ 'slug' => $info->slug, 'plugin' => $entry, 'new_version' => $info->version ];
return $T;
}
public static function hook_report_admin_error(): void
{ printf('<div class="notice notice-error"><p>%s</p></div>', self::$admin_error); }
public function order_statuses(array $statuses): array
{ return array_merge($statuses, [ 'wc-chargeback' => _x('Chargeback', 'Order status', 'woocommerce') ]); }
private function init_payment_settings(): array {
foreach (explode(' ', 'endpoint_id login control_key payment_method require_ssn sandbox live_url sandbox_url notify_url transaction_end'
.' title description enabled') as $k) {
$s[$k] = in_array($k, ['sandbox', 'require_ssn'])
? ($this->get_option($k) == 'yes')
: $this->get_option($k);
if (property_exists($this, $k))
$this->$k = $s[$k];
}
$s['is_direct'] = $s['payment_method'] == 'direct';
$s['gate'] = $s['sandbox'] ? $s['sandbox_url'] : $s['live_url'];
return $s;
}
public function init_form_fields(): void
{ $this->form_fields = include 'form_fields.php'; }
private function set_order(int $order_id): void {
if ($order = wc_get_order($order_id))
$this->order = $order;
else
throw new \Exception(__('Order not found.', 'wc-payneteasy'));
}
public function process_payment($order_id): ?array {
try {
$this->set_order($order_id);
if ($this->order->get_payment_method() != $this->id)
throw new \Exception(__('Payment method is not "Payneteasy Payment System".', 'wc-payneteasy'));
$sale = $this->make_sale();
if (isset($sale['redirect-url']))
$this->order->update_status('pending', __('Payment link generated:', 'wc-payneteasy').$sale['redirect-url']);
return $this->Api->is_direct()
? [ 'result' => 'success', 'redirect' => home_url("?wc-api={$this->id}_return&orderId=$order_id") ]
: [ 'result' => 'success', 'redirect' => $sale['redirect-url'] ];
}
catch (\Exception | PayneteasyException $e) {
wc_add_notice($e->getMessage(), 'error');
return null;
}
}
private function make_sale(): array {
[ $order_id, $email, $total ] = [ $this->order->get_id(), $this->order->get_billing_email(), $this->order->get_total() ];
$return_url = home_url("?wc-api={$this->id}_return&orderId=$order_id");
$response = $this->Api->sale([
'client_orderid' => $order_id,
'order_desc' => "Order # $order_id",
'amount' => $total,
'currency' => $this->order->get_currency(),
'address1' => $this->order->get_shipping_address_1() ?: $this->order->get_billing_address_1(),
'city' => $this->order->get_shipping_city() ?: $this->order->get_billing_city(),
'zip_code' => $this->order->get_shipping_postcode() ?: $this->order->get_billing_postcode(),
'country' => $this->order->get_shipping_country() ?: $this->order->get_billing_country(),
'phone' => $this->order->get_shipping_phone() ?: $this->order->get_billing_phone(),
'email' => $email,
'ipaddress' => $_SERVER['REMOTE_ADDR'],
'cvv2' => "{$_POST['cvv2']}",
'ssn' => $_POST['ssn'] ?? '',
'credit_card_number' => "{$_POST['credit_card_number']}",
'card_printed_name' => "{$_POST['card_printed_name']}",
'expire_month' => "{$_POST['expire_month']}",
'expire_year' => "{$_POST['expire_year']}",
'first_name' => $this->order->get_shipping_first_name() ?: $this->order->get_billing_first_name(),
'last_name' => $this->order->get_shipping_last_name() ?: $this->order->get_billing_last_name(),
'redirect_success_url' => $return_url,
'redirect_fail_url' => $return_url, # wc_get_cart_url(),
'redirect_url' => $return_url,
'server_callback_url' => home_url('?wc-api=wc_payneteasy_webhook'), # $return_url,
'notify_url' => sprintf($this->notify_url, $order_id) ]);
global $wpdb;
$wpdb->insert("{$wpdb->prefix}payneteasy_payments",
[ 'paynet_order_id' => $response['paynet-order-id'], 'merchant_order_id' => $response['merchant-order-id'] ]);
return $response;
}
private static function form_cell(?array $cell, string $class): string {
return $cell !== null
? "<div class='form-row-$class'><label>{$cell[0]} <span class='required'>*</span></label>"
."<input id='{$cell[1]}' name='{$cell[1]}' type='text'"
.($cell[2] ? " autocomplete='{$cell[2]}'" : '')
.' '.($cell[3] ?? '').'></div>'
: '';
}
private static function form_row(array $cell1, ?array $cell2): string
{ return '<div class="form-row">'.self::form_cell($cell1, 'first').self::form_cell($cell2, 'last').'</div>'; }
private static function js_luhn_checker(): string {
return '<script>function checkLuhn(ccnS) {
let sum = 0; const parity = (ccnS.length) % 2;
for (let i = 0; i < ccnS.length; i += 1) { let digit = Number(ccnS[i]); if (i % 2 === parity) { digit *= 2;
if (digit > 9) { digit -= 9; } } sum += digit; }
document.getElementById("place_order").disabled = Number(sum % 10) !== 0; }</script>';
}
private static function js_ticker(): string {
return '<script>let t_el = document.getElementById("ticker");let t_s = t_el.innerHTML;let t_pos = 0
setInterval(ticker, 500)
function ticker() {
let a = t_s.split("")
if (a[t_pos] == " ") t_pos++
a[t_pos] = a[t_pos] + "</span>";
t_el.innerHTML = "<span style=\'color:#09C\'>" + a.join("")
if (++t_pos == t_s.length) t_el.click() }</script>';
}
# отображение описания платежной системы PAYNET при оформлении заказа
public function payment_fields(): void {
if (!empty($this->description))
echo wpautop(wptexturize($this->description));
echo '<fieldset id="wc-'.esc_attr($this->id).'-cc-form" class="wc-credit-card-form wc-payment-form" style="background:transparent">';
do_action('woocommerce_credit_card_form_start', $this->id);
echo $this->Api->is_direct()
? self::js_luhn_checker()
.self::form_row(
['Card Number', 'credit_card_number', 'cc-number', 'onkeyup="checkLuhn(this.value)"'],
['Printed name', 'card_printed_name', 'cc-name', 'placeholder="Printed name"'])
.self::form_row(
['Expiry month', 'expire_month', 'off', 'minlength="2" maxlength="2" placeholder="MM" style="max-width:50%"'],
['Expiry year', 'expire_year', 'off', 'minlength="4" maxlength="4" placeholder="YYYY" style="max-width: 50%"'])
.self::form_row(
['CVC', 'cvv2', 'off', 'minlength="3" maxlength="4" type="password" style="max-width:50%"'],
$this->require_ssn ? ['Document Number (CPF)', 'ssn', 'off'] : null)
: ($this->require_ssn ? self::form_cell(['Document Number (CPF)', 'ssn', 'off'], 'wide') : '');
do_action('woocommerce_credit_card_form_end', $this->id);
echo '<div class="clear"></div></fieldset>';
}
public function validate_fields(): void {
if ($this->Api->is_direct())
foreach (explode(' ', 'credit_card_number card_printed_name expire_year expire_month cvv2') as $f)
if (empty($_POST[$f]))
wc_add_notice("$f is required!", 'error');
if (empty($_POST['ssn']) && $this->require_ssn)
wc_add_notice('CPF is required!', 'error');
}
# обработчик return, вызываемый при переходе на страницу return_url, после попытки оплаты.
public function hook_return_handler(): void {
$order_id = $_GET['orderId'] ?? null;
try {
if (empty($order_id))
throw new \Exception(__('Order ID is empty.', 'wc-payneteasy'));
$this->set_order($order_id);
$this->change_payment_status( $payment_status = $this->get_payment_status($three_d_html) );
WC()->cart->empty_cart(); # иначе продолжает слать всё тот же ордер_ид, и гейт отдаёт один и тот же запрос
$js_ticker = self::js_ticker();
switch ($payment_status) {
case 'sale/processing':
echo $three_d_html ?: '<div style="width: 100%; text-align: center"><div><h1>Your payment is being processed.</h1></div><div><a href="'.home_url("?wc-api={$this->id}_return&orderId=$order_id").'" id="ticker">Check status</a></div></div>'.$js_ticker;
die();
case 'sale/approved':
echo '<div style="width: 100%; text-align: center"><div><h1>Your payment was approved. Thank you.</h1></div><div><a href="'.get_site_url().'" id="ticker">Return homepage</a></div></div>'.$js_ticker;
die();
case 'sale/error':
echo '<div style="width: 100%; text-align: center"><div><h1>Your payment was not completed because of an error. Could you try again.</h1></div><div><a href="'.get_site_url().'" id="ticker">Return homepage</a></div></div>'.$js_ticker;
die();
case 'sale/declined':
echo '<div style="width: 100%; text-align: center"><div><h1>Your payment was declined. Could you try again.</h1></div><div><a href="'.get_site_url().'" id="ticker"">Return homepage</a></div></div>'.$js_ticker;
die();
default:
echo '<div style="width: 100%; text-align: center"><div><h1>Transaction is declined but something went wrong, please inform your account manager, final status</h1></div><div><a href="'.get_site_url().'" id="ticker">Return homepage</a></div></div>'.$js_ticker;
die();
}
}
catch (\Exception | PayneteasyException $e)
{ wp_die( $e->getMessage() ); }
}
public function hook_webhook_handler(): void {
[ $order_id, $type, $paynet_id ] = [ $_GET['client_orderid'], $_GET['type'], $_GET['orderid'] ];
try {
if (empty($order_id))
throw new \Exception(__('Order ID is empty.', 'wc-payneteasy'));
$this->set_order($order_id);
if ($this->order->get_status() === $type)
die('OK');
$this->change_payment_status( $this->get_payment_status($dummy, $paynet_id) );
exit;
}
catch (\Exception | PayneteasyException $e)
{ wp_die( $e->getMessage() ); }
}
# проверяем статус платежа, и если он approved, то устанавливаем заказ в CMS как оплаченный.
public function hook_ajax_handler(): void {
[ $order_id, $action ] = [ $_POST['order_id'], $_POST['action'] ];
try {
if (!wp_verify_nonce($_POST['nonce'] ?? '', 'payneteasy-ajax-nonce'))
throw new \Exception(__('Failed ajax validation.', 'wc-payneteasy'));
if (empty($order_id))
throw new \Exception(__('Order ID is empty.', 'wc-payneteasy'));
if (empty($action))
throw new \Exception(__('Required action not specified.', 'wc-payneteasy'));
$this->set_order($order_id);
if ($action == 'refund') { # XXX why action is refund but make_chargeback being called
$this->make_chargeback();
$message = __('Payment refunded.', 'wc-payneteasy');
}
elseif ($action == 'check_status') {
$this->change_payment_status($this->get_payment_status());
$message = __('Status updated.', 'wc-payneteasy');
}
wp_send_json([ 'success' => true, 'message' => $message ]);
}
catch (\Exception | PayneteasyException $e)
{ wp_send_json([ 'success' => false, 'message' => $e->getMessage() ]); }
}
private function change_payment_status(string $payment_status): void {
$method = 'actions_for_'.([
'sale/approved' => 'paid',
'sale/processing' => 'hold',
'chargeback/approved' => 'chargeback',
'reversal/approved' => 'refunded'
][$payment_status] ?? 'unpaid')
.'_order';
$this->$method();
}
private function make_chargeback(): array { # XXX result not used ever
$order_id = $this->order->get_id();
$amount = $_POST['refund_amount'] ?? 0;
if (empty($amount))
throw new \Exception(__('Refund amount not specified.', 'wc-payneteasy'));
$amount = self::parse_amount($amount);
$email = $this->order->get_billing_email();
return $this->Api->return([ 'client_orderid' => $order_id, 'orderid' => $this->paynet_order_id(), 'comment' => 'Order cancel ' ]);
}
private function preparing_items_for_refunds(array $items): array { # XXX function not used ever ?
$refund_order_item_qty = $_POST['refund_order_item_qty'] ?? [];
$refund_line_total = $_POST['refund_line_total'] ?? [];
if (empty($refund_order_item_qty) || empty($refund_line_total))
throw new \Exception(__('The required data for a refund was not transmitted.', 'wc-payneteasy'));
$prepared_items = [];
foreach ($items as $item) {
$item_id = explode('-', $item['code'])[0] ?? '';
$quantity = $refund_order_item_qty[$item_id] ?? 0;
$amount = $refund_line_total[$item_id] ?? 0;
if (empty($quantity) && empty($amount))
continue;
if (!empty($quantity))
$item['quantity'] = (int) $quantity;
$item['amount'] = empty($amount)
? (int) $quantity * $item['price']
: self::parse_amount($amount);
$item['price'] = $item['amount'] / $item['quantity'];
$prepared_items[] = $item;
}
return $prepared_items;
}
private static function parse_amount($amount): float
{ return floatval(str_replace([' ', ','], ['', '.'], $amount)); }
private function actions_for_paid_order(): void {
$completed_status = str_replace('wc-', '', $this->transaction_end);
if ($this->order->get_status() !== $completed_status) {
$this->order->update_status($completed_status, __('Payment completed successfully.', 'wc-payneteasy'));
$this->order->payment_complete();
wc_reduce_stock_levels($this->order->get_id());
}
}
private function actions_for_hold_order(): void {
if ($this->order->get_status() !== 'on-hold')
$this->order->update_status('on-hold', __('Payment received but not confirmed.', 'wc-payneteasy'));
}
private function actions_for_unpaid_order(): void {
if ($this->order->get_status() !== 'failed')
$this->order->update_status('failed', __('Payment not paid.', 'wc-payneteasy'));
wc_add_notice(__('Payment not paid. Your order has been canceled.', 'wc-payneteasy'), 'error');
}
private function actions_for_chargeback_order(): void {
if ($this->order->get_status() !== 'chargeback')
$this->order->update_status('chargeback', __('Chargeback of payment.', 'wc-payneteasy'));
wc_add_notice(__('The payment was charged back.', 'wc-payneteasy'), 'notice');
}
private function actions_for_refunded_order(): void {
if ($this->order->get_status() !== 'refunded')
$this->order->update_status('refunded', __('Refund of payment.', 'wc-payneteasy'));
wc_add_notice(__('The payment was refunded.', 'wc-payneteasy'), 'notice');
}
private function actions_for_partially_refunded_order(): void {
$completed_status = str_replace('wc-', '', $this->transaction_end);
if ($this->order->get_status() !== $completed_status)
$this->order->update_status($completed_status, __('Partial refund of payment.', 'wc-payneteasy'));
wc_add_notice(__('The payment was partially refunded.', 'wc-payneteasy'), 'notice');
}
private function get_payment_status(&$three_d_html = null, $paynet_id = null): string {
$response = $this->Api->status([ 'client_orderid' => $this->order->get_id(), 'orderid' => $paynet_id ?: $this->paynet_order_id() ]);
$three_d_html = $response['html'] ?? null;
return "{$response['transaction-type']}/{$response['status']}";
}
private function paynet_order_id(): string {
global $wpdb;
return $wpdb->get_var("SELECT paynet_order_id FROM {$wpdb->prefix}payneteasy_payments WHERE merchant_order_id=".$this->order->get_id()
.' ORDER BY id DESC LIMIT 1');
}
}
}