PluginProbe ʕ •ᴥ•ʔ
Trust Payments Gateway for WooCommerce / 1.1.4
Trust Payments Gateway for WooCommerce v1.1.4
trunk 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 2.0.0 2.0.1 2.1.0 2.1.1 2.1.2
trust-payments-hosted-payment-pages-integration / woocommerce-securetrading-gateway.php
trust-payments-hosted-payment-pages-integration Last commit date
Firebase 1 year ago admin 1 year ago assets 1 year ago includes 1 year ago templates 1 year ago vendor 1 year ago CHANGELOG.md 1 year ago README.md 1 year ago composer.json 1 year ago composer.lock 1 year ago constants.php 1 year ago readme.txt 1 year ago woocommerce-securetrading-gateway.php 1 year ago
woocommerce-securetrading-gateway.php
2569 lines
1 <?php
2 /**
3 * Plugin Name: Trust Payments Gateway for WooCommerce
4 * Plugin URI: https://www.securetrading.com/
5 * Description: Allow payment by credit card on your store with Trust Payments.
6 * Version: 1.1.4
7 * Author: Trust Payments
8 * Author URI: https://www.securetrading.com/
9 *
10 * Requires Plugins: woocommerce
11 *
12 */
13 if ( ! defined( 'ABSPATH' ) ) {
14 exit;
15 } // Exit if accessed directly
16
17 if ( ! defined( 'SECURETRADING_TEXT_DOMAIN' ) ) {
18 define( 'SECURETRADING_TEXT_DOMAIN', 'securetrading' );
19 }
20
21 // Plugin Folder URL
22 if ( ! defined( 'SECURETRADING_URL' ) ) {
23 define( 'SECURETRADING_URL', untrailingslashit( plugins_url( basename( plugin_dir_path( __FILE__ ) ), basename( __FILE__ ) ) ) );
24 }
25
26 // Plugin Root File
27 if ( ! defined( 'SECURETRADING_FILE' ) ) {
28 define( 'SECURETRADING_FILE', plugin_basename( __FILE__ ) );
29 }
30
31 // Plugin Folder Path
32 if ( ! defined( 'SECURETRADING_PATH' ) ) {
33 define( 'SECURETRADING_PATH', plugin_dir_path( __FILE__ ) );
34 }
35
36 // Plugin Version
37 if ( ! defined( 'SECURETRADING_VERSION' ) ) {
38 define( 'SECURETRADING_VERSION', '1.1.4' );
39 }
40 include_once SECURETRADING_PATH . '/constants.php';
41
42 /**
43 * WooCommerce fallback notice.
44 *
45 * @return string
46 * @since 1.0.0
47 */
48 function woocommerce_securetrading_missing_wc_notice() {
49 /* translators: 1. URL link. */
50 echo '<div class="error"><p><strong>' . sprintf(esc_html__('Trust Payments Gateway for WooCommerce API requires WooCommerce to be installed and active. You can download %s here.', 'securetrading-api'), '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>') . '</strong></p></div>';
51 }
52
53 class WC_SecureTrading_Main {
54 /**
55 * @var
56 */
57 private static $securetrading_instance;
58
59 /** plugin version number */
60 const VERSION = SECURETRADING_VERSION;
61
62 /**
63 * @var
64 */
65 protected $helper;
66
67 /**
68 * @var
69 */
70 protected $tpApiGateway;
71
72 /**
73 * @var
74 */
75 protected $tpHppGateway;
76
77 /**
78 * @var
79 */
80 protected $tpGoogleGateway;
81
82 /**
83 * @var
84 */
85 protected $tpAppleGateway;
86
87 /**
88 * @var
89 */
90 protected $tpPaypalGateway;
91
92 /**
93 * @var
94 */
95 protected $wcCheckout;
96
97 /**
98 * WC_SecureTrading_Main constructor.
99 */
100 public function __construct() {
101 register_activation_hook( SECURETRADING_FILE, array( $this, 'install' ) );
102 add_filter( 'plugin_action_links_' . SECURETRADING_FILE, array( $this, 'plugin_action_links' ) );
103 add_action( 'plugins_loaded', array($this, 'init' ));
104 //woocommerce_get_order_item_totals
105 add_filter( 'woocommerce_get_order_item_totals', array( $this, 'show_payment_method' ), 2, 3);
106 add_filter( 'plugin_row_meta', array( $this, 'tp_plugin_row_meta' ), 10, 2 );
107 add_action( 'woocommerce_init', function() {
108 $this->wcCheckout = WC()->checkout();
109 } );
110 }
111
112 /**
113 * @param $links
114 *
115 * @return array|string[]
116 */
117 public static function plugin_action_links( $links ) {
118 $action_links = array(
119 'settings' => '<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout' ) . '" aria-label="' . esc_attr__( 'View Trust Payments settings', SECURETRADING_TEXT_DOMAIN) . '">' . esc_html__( 'Settings', 'woocommerce' ) . '</a>',
120 );
121
122 return array_merge( $action_links, $links );
123 }
124
125 public function init() {
126 /* Check WooCommerce active */
127 if (!class_exists('WooCommerce')) {
128 add_action('admin_notices', 'woocommerce_securetrading_missing_wc_notice');
129 return;
130 }
131
132 add_action( 'init', array( $this, 'load_text_domain' ), 1 );
133 add_action( 'init', array( $this, 'create_post_type' ), 5 );
134 add_action( 'wp_enqueue_scripts', array( $this, 'load_script' ) );
135 add_action( 'admin_enqueue_scripts', array( $this, 'admin_styles' ) );
136 require_once( SECURETRADING_PATH . '/includes/class-securetrading-iframe-form.php' );
137 require_once( SECURETRADING_PATH . '/includes/class-securetrading-helper.php' );
138 require_once( SECURETRADING_PATH . '/includes/class-securetrading-api-form.php' );
139 require_once( SECURETRADING_PATH . '/includes/class-securetrading-google-payment.php' );
140 require_once( SECURETRADING_PATH . '/includes/class-securetrading-apple-payment.php' );
141 require_once( SECURETRADING_PATH . '/includes/class-securetrading-paypal-payment.php' );
142 require_once( SECURETRADING_PATH . '/includes/class-securetrading-a2a-payment.php' );
143 require_once( SECURETRADING_PATH . '/includes/class-rest-api-controller.php' );
144 require_once( SECURETRADING_PATH . '/admin/securetrading-transaction-columns.php' );
145 require_once( SECURETRADING_PATH . '/Firebase/JWT/src/JWT.php' );
146 require_once realpath( SECURETRADING_PATH . '/vendor/autoload.php' );
147 if ( is_admin() ) {
148 require_once( SECURETRADING_PATH . '/includes/class-securetrading-moto-payment.php' );
149 }
150
151 /* Dependency Injection */
152 $this->helper = new WC_SecureTrading_Helper();
153 $this->tpApiGateway = new WC_SecureTrading_API_Gateway();
154 $this->tpHppGateway = new WC_SecureTrading_iFrame_Gateway();
155 $this->tpGoogleGateway = new WC_SecureTrading_Google_Gateway();
156 $this->tpAppleGateway = new WC_SecureTrading_Apple_Gateway();
157 $this->tpPaypalGateway = new WC_SecureTrading_Paypal_Gateway();
158
159 add_filter( 'woocommerce_payment_gateways', array( $this, 'add_securetrading_gateways' ),5 );
160 add_shortcode( 'securetrading_iframe', array( $this, 'securetrading_iframe'));
161 add_filter( 'woocommerce_order_actions', array( $this, 'add_order_action' ),5 );
162 add_filter( 'theme_page_templates', array( $this, 'hide_templates' ), 10, 3 );
163
164 /* Save card */
165 add_action( 'wp_ajax_nopriv_webservices_save_card_token', array( $this, 'mgn_webservices_save_card_token' ) );
166 add_action( 'wp_ajax_webservices_save_card_token', array( $this, 'mgn_webservices_save_card_token' ) );
167
168 /* Credit/Debit card */
169 add_action( 'wp_ajax_st_api_update_address_myst', array( $this, 'st_api_update_address_myst' ) );
170 add_action( 'wp_ajax_nopriv_st_api_update_address_myst', array( $this, 'st_api_update_address_myst' ) );
171
172 /* API MOTO update JWT */
173 add_action( 'wp_ajax_st_moto_api_update_jwt_myst', array( $this, 'st_moto_api_update_jwt_myst' ) );
174 add_action( 'wp_ajax_nopriv_st_moto_api_update_jwt_myst', array( $this, 'st_moto_api_update_jwt_myst' ) );
175
176 /* Order Pay update JWT */
177 add_action( 'wp_ajax_tp_order_pay_update_jwt', array( $this, 'tp_order_pay_update_jwt' ) );
178 add_action( 'wp_ajax_nopriv_tp_order_pay_update_jwt', array( $this, 'tp_order_pay_update_jwt' ) );
179
180 /* Process payment */
181 add_action( 'wp_ajax_nopriv_tp_process_order', array( $this, 'tp_process_order' ) );
182 add_action( 'wp_ajax_tp_process_order', array( $this, 'tp_process_order' ) );
183
184 /* Log note order */
185 add_action( 'wp_ajax_nopriv_tp_log_note_order', array( $this, 'tp_log_note_order' ) );
186 add_action( 'wp_ajax_tp_log_note_order', array( $this, 'tp_log_note_order' ) );
187
188 /* Migrate refunds tp_gateway */
189 add_action( 'wp_ajax_mgn_migrate_refund_purchase', array( $this, 'mgn_migrate_refund_purchase' ) );
190 add_action( 'wp_ajax_nopriv_mgn_migrate_refund_purchase', array( $this, 'mgn_migrate_refund_purchase' ) );
191
192 /* Loader JWT */
193 add_filter( 'woocommerce_update_order_review_fragments', array( $this, 'tp_refresh_jwt' ));
194
195 /* Modify Apple Pay request */
196 add_filter( 'woocommerce_checkout_posted_data', array( $this, 'tp_checkout_posted_data' ));
197
198 /* Apple process payment */
199 add_action( 'wp_ajax_nopriv_tp_apple_query_transaction', array( $this, 'tp_apple_query_transaction' ) );
200 add_action( 'wp_ajax_tp_apple_query_transaction', array( $this, 'tp_apple_query_transaction' ) );
201
202 /* Apple process payment */
203 add_action( 'wp_ajax_nopriv_tp_pay_for_order', array( $this, 'tp_pay_for_order' ) );
204 add_action( 'wp_ajax_tp_pay_for_order', array( $this, 'tp_pay_for_order' ) );
205
206 /* Append button */
207 add_action( 'woocommerce_review_order_after_submit', array( $this, 'mgn_button_after_submit' ) );
208 add_action( 'woocommerce_pay_order_after_submit', array( $this, 'mgn_button_after_submit' ) );
209
210 /* Set payment card selected on checkout */
211 add_action( 'init', array( $this, 'mgn_select_saved_payment_card' ) );
212
213 /* Reset saved purchase card. */
214 add_action( 'wp', array( $this, 'mgn_reset_purchase_card' ) );
215
216 /* Unset payment Apple pay when brower not support */
217 add_filter( 'woocommerce_available_payment_gateways', array($this, 'disable_apple_pay') );
218
219 /* Migrate ST Transactions */
220 add_filter( 'pre_get_posts', array( $this, 'mgn_migrate_st_transactions' ) );
221
222 /* Migrate tp_gateway order detail */
223 add_action( 'admin_menu', array($this, 'mgn_migrate_order_detail') );
224
225 /* Change format save card */
226 add_filter( 'woocommerce_payment_gateway_get_saved_payment_method_option_html', array( $this, 'change_format_savecard' ), 10, 3 );
227
228 /* Endpoint HPP */
229 add_action( 'woocommerce_api_trust-payments', array( $this, 'mgn_create_payment' ) );
230 add_action( 'woocommerce_api_trust-moto-payments', array( $this, 'mgn_create_moto_payment' ) );
231 add_action( 'woocommerce_api_trust-confirm', array( $this, 'mgn_confirm_payment' ) );
232 add_action( 'woocommerce_api_trust-iframe', array( $this, 'mgn_iframe_payment' ) );
233
234 /* Remove checkout ZIP code validation */
235 add_filter( 'woocommerce_checkout_fields', array($this, 'mgn_gpay_no_zip_validation'), 100 );
236
237 //processing order with Trust Payments a2a payment for payment pages
238 add_action('securetrading_processed', array($this, 'processing_order_a2a'), 10, 2);
239
240 /* Apple process payment */
241 add_action( 'wp_ajax_nopriv_tp_apple_order_jwt', array( $this, 'tp_apple_order_jwt' ) );
242 add_action( 'wp_ajax_tp_apple_order_jwt', array( $this, 'tp_apple_order_jwt' ) );
243
244 /* Trust Payments detail in Order */
245 add_action( 'add_meta_boxes', array( $this, 'tp_order_details' ) );
246 }
247
248 /**
249 * Show row meta on the plugin screen.
250 *
251 * @param mixed $links Plugin Row Meta.
252 *
253 * @return array
254 */
255 public function tp_plugin_row_meta( $links, $file ) {
256 if ( SECURETRADING_FILE !== $file ) {
257 return $links;
258 }
259
260 /**
261 * The Trust Payments documentation URL.
262 *
263 * @since 2.7.0
264 */
265 $docs_url = 'https://help.trustpayments.com/hc/en-us/sections/9682549422353-WooCommerce';
266
267 /**
268 * The Trust Payments API documentation URL.
269 *
270 * @since 2.2.0
271 */
272 $api_docs_url = 'https://help.trustpayments.com/hc/en-us/articles/4402754655761-Getting-started-with-Webservices-API';
273
274 /**
275 * The community Trust Payments support URL.
276 *
277 * @since 2.2.0
278 */
279 $community_support_url = 'https://wordpress.org/support/plugin/trust-payments-hosted-payment-pages-integration/';
280
281 $row_meta = array(
282 'docs' => '<a href="' . esc_url( $docs_url ) . '" aria-label="' . esc_attr__( 'View Trust Payments documentation', SECURETRADING_TEXT_DOMAIN ) . '">' . esc_html__( 'Docs', SECURETRADING_TEXT_DOMAIN ) . '</a>',
283 'apidocs' => '<a href="' . esc_url( $api_docs_url ) . '" aria-label="' . esc_attr__( 'View Trust Payments API docs', SECURETRADING_TEXT_DOMAIN ) . '">' . esc_html__( 'API docs', SECURETRADING_TEXT_DOMAIN ) . '</a>',
284 'support' => '<a href="' . esc_url( $community_support_url ) . '" aria-label="' . esc_attr__( 'Visit community forums', SECURETRADING_TEXT_DOMAIN ) . '">' . esc_html__( 'Community support', SECURETRADING_TEXT_DOMAIN ) . '</a>',
285 );
286
287 return array_merge( $links, $row_meta );
288 }
289
290 /**
291 * @param $order_id
292 * @param $params
293 */
294 public function processing_order_a2a( $order_id, $params ) {
295 if( $order_id ) {
296 $order = wc_get_order( $order_id );
297 $payment_method = $order->get_payment_method();
298
299 if ( $params['paymenttypedescription'] == 'ATA' ) {
300 $gateway_a2a = WC()->payment_gateways->payment_gateways()[SECURETRADING_A2A];
301 if ( $gateway_a2a ) {
302 $webservices_username = $gateway_a2a->webservices_username;
303 $webservices_password = $gateway_a2a->webservices_password;
304 $site_reference = $gateway_a2a->sitereference;
305
306 $api = \Securetrading\api(array(
307 'username' => $webservices_username,
308 'password' => $webservices_password
309 ));
310
311 $transaction = $params['transactionreference'] ?: '';
312
313 if ( ! empty( $transaction ) ) {
314 $requestData = array(
315 'requesttypedescriptions' => array('TRANSACTIONQUERY'),
316 'filter' => array(
317 'sitereference' => array(
318 array(
319 'value' => $site_reference
320 )
321 ),
322 'transactionreference' => array(
323 array(
324 'value' => $transaction
325 )
326 )
327 )
328 );
329
330 $this->helper->securetrading_a2a_logs( 'A2A Request: '.wc_print_r( $requestData, true), true );
331
332 $response = $api->process($requestData);
333 $results = $response->toArray();
334
335 $this->helper->securetrading_a2a_logs( 'A2A Response: '.wc_print_r( $results['responses'][0], true), true );
336
337 $error_code = isset($results['responses'][0]['errorcode']) ? $results['responses'][0]['errorcode'] : '';
338 $message = isset($results['responses'][0]['errormessage']) ? $results['responses'][0]['errormessage'] : '';
339 $les_status = isset($results['responses'][0]['records'][0]['settlestatus']) ? $results['responses'][0]['records'][0]['settlestatus'] : '';
340 $transactionstartedtimestamp = isset($results['responses'][0]['records'][0]['transactionstartedtimestamp']) ? $results['responses'][0]['records'][0]['transactionstartedtimestamp'] : '';
341 $acquirerresponsemessage = isset($results['responses'][0]['records'][0]['acquirerresponsemessage']) ? $results['responses'][0]['records'][0]['acquirerresponsemessage'] : '';
342 $settleduedate = isset($results['responses'][0]['records'][0]['settleduedate']) ? $results['responses'][0]['records'][0]['settleduedate'] : '';
343 $settledtimestamp = isset($results['responses'][0]['records'][0]['settledtimestamp']) ? $results['responses'][0]['records'][0]['settledtimestamp'] : '';
344 $orderreference = isset($results['responses'][0]['records'][0]['orderreference']) ? $results['responses'][0]['records'][0]['orderreference'] : '';
345 $status_order = 'pending';
346 $title = __( 'Account to Account (A2A)', SECURETRADING_TEXT_DOMAIN ) ;
347 $note_order = sprintf(__('Trust Payments via %s (Transaction ID: %s)', SECURETRADING_TEXT_DOMAIN), $title, $transaction);
348
349 switch ($les_status) {
350 case SECURE_TRADING_CANCELLED:
351 $status_order = 'cancelled';
352 break;
353 case SECURE_TRADING_SETTLED:
354 $status_order = 'completed';
355 break;
356 default:
357 $status_order = 'processing';
358 break;
359 }
360
361 //create_transaction
362 if ( $error_code == "0" ) {
363 $raw_data = array(
364 'transaction_id' => $transaction,
365 'transaction_parent_id' => '',
366 'transaction_type' => 'Capture',
367 'transaction_status' => $les_status ?: '',
368 'order_id' => $order_id,
369 'customer_email' => $order->get_billing_email(),
370 'payment_type_description' => 'ATA',
371 'request_reference' => isset($results['requestreference']) ? $results['requestreference'] : '',
372 );
373 $this->helper->create_transaction($raw_data);
374 }
375
376 update_post_meta( $order_id, '_transaction_id', $transaction );
377 update_post_meta( $order_id, '_' . $payment_method . '_payment_type_description', 'ATA' );
378 update_post_meta( $order_id, '_' . $payment_method . '_settle_status', $les_status );
379 update_post_meta( $order_id, '_' . $payment_method . '_site_reference', $site_reference );
380 update_post_meta( $order_id, '_' . $payment_method . '_operator_name', $webservices_username );
381 update_post_meta( $order_id, '_' . $payment_method . '_account_type_description', 'ECOM' );
382 update_post_meta( $order_id, '_' . $payment_method . '_message', $message );
383 update_post_meta( $order_id, '_' . $payment_method . '_errorcode', $error_code );
384 update_post_meta( $order_id, '_' . $payment_method . '_transactionstartedtimestamp', $transactionstartedtimestamp );
385 update_post_meta( $order_id, '_' . $payment_method . '_settleduedate', $settleduedate );
386 update_post_meta( $order_id, '_' . $payment_method . '_settledtimestamp', $settledtimestamp );
387 update_post_meta( $order_id, '_' . $payment_method . '_acquirerresponsemessage', $acquirerresponsemessage );
388 update_post_meta( $order_id, '_' . $payment_method . '_orderreference', $orderreference );
389
390 $order->update_status( $status_order );
391 $order->add_order_note( $note_order );
392 }
393 }
394 }
395 }
396 }
397
398 /**
399 * Change format card.
400 *
401 * @param $html amount to charge
402 * @param $token order details
403 */
404 public function change_format_savecard( $html, $token, $that ) {
405 $get_display_name = sprintf(
406 /* translators: 1: credit card type 2: last 4 digits 3: expiry month 4: expiry year */
407 __( '%1$s ending in %2$s (Expires %3$s/%4$s)', 'woocommerce' ),
408 strtoupper(wc_get_credit_card_type_label( $token->get_card_type() )),
409 $token->get_last4(),
410 $token->get_expiry_month(),
411 substr( $token->get_expiry_year(), 2 )
412 );
413
414 $html = sprintf(
415 '<li class="woocommerce-SavedPaymentMethods-token">
416 <input id="wc-%1$s-payment-token-%2$s" type="radio" name="wc-%1$s-payment-token" value="%2$s" style="width:auto;" class="woocommerce-SavedPaymentMethods-tokenInput" %4$s />
417 <label for="wc-%1$s-payment-token-%2$s">%3$s</label>
418 </li>',
419 esc_attr( $this->id ),
420 esc_attr( $token->get_id() ),
421 esc_html( $get_display_name ),
422 checked( $token->is_default(), true, false )
423 );
424
425 return $html;
426 }
427
428 public function load_script() {
429 if ( is_checkout() || is_page(get_option('securetradingsecuretrading_page_id'))) {
430 wp_register_style( 'tp_payment_style', SECURETRADING_URL . '/assets/css/style.css', array());
431 wp_enqueue_style( 'tp_payment_style' );
432
433 wp_register_script( 'securetrading_jwt', plugins_url( '/assets/js/st_jwt.js', SECURETRADING_FILE ), array(), self::VERSION, true );
434 wp_localize_script('securetrading_jwt', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
435 wp_enqueue_script( 'securetrading_jwt');
436
437 /* Platform */
438 $st_api_setting = get_option('woocommerce_securetrading_api_settings');
439 $platform = isset($st_api_setting['platform']) ? $st_api_setting['platform'] : 'eu';
440
441 $webservices = SECURETRADING_EU_WEBSERVICES;
442 if ( $platform == 'us' ) {
443 $webservices = SECURETRADING_US_WEBSERVICES;
444 }
445
446 wp_enqueue_script(
447 'webservices-js',
448 $webservices,
449 [],
450 self::VERSION,
451 true
452 );
453 }
454
455 if ( is_checkout() && is_wc_endpoint_url() ) {
456 global $wp;
457 $order_id = !empty($wp->query_vars['order-pay']) ? absint($wp->query_vars['order-pay']) : '';
458 if ( !empty($order_id) && ( 'yes' === $this->tpApiGateway->settings['enabled'] || 'yes' === $this->tpHppGateway->settings['enabled'] ) ) {
459 $order = wc_get_order( $order_id );
460 $isGuest = false;
461 if ( !$order->get_user_id() && is_user_logged_in() && ( $order->get_billing_email() !== wp_get_current_user()->user_email ) ) {
462 $isGuest = true;
463 }
464 $order_pay = array(
465 'order_id' => $order_id,
466 'ajax_url' => esc_url(admin_url('admin-ajax.php')),
467 'tp_oder_pay_nonce' => wp_create_nonce('tp_oder_pay_create_nonce'),
468 'currency' => get_woocommerce_currency(),
469 'total' => wc_get_order( $order_id )->get_total(),
470 'is_guest' => $isGuest,
471 'tp_api_gateway' => array(
472 'enabled' => $this->tpApiGateway->enabled,
473 'id' => SECURETRADING_API_ID,
474 'jwt' => esc_html($this->helper->mgn_update_jwt_address_details( $order_id, '', [], [], 0, 0, 0, SECURETRADING_API_ID, 0, $isGuest )),
475 'testmode' => $this->tpApiGateway->testmode
476 ),
477 'tp_hpp_gateway' => array(
478 'enabled' => $this->tpHppGateway->enabled,
479 'id' => SECURETRADING_ID,
480 'jwt' => esc_html($this->helper->mgn_update_jwt_address_details( $order_id, '', [], [], 0, 0, 0, SECURETRADING_ID, 0, $isGuest )),
481 'testmode' => $this->tpHppGateway->testmode
482 ),
483 'tp_google_gateway' => array(
484 'enabled' => $this->tpGoogleGateway->enabled,
485 'id' => SECURETRADING_GOOGLE_PAY,
486 'site_reference' => $this->tpApiGateway->site_reference,
487 'merchant_id' => $this->tpGoogleGateway->merchant_id,
488 'merchant_name' => $this->tpGoogleGateway->merchant_name,
489 'testmode' => $this->tpApiGateway->testmode
490 ),
491 'tp_apple_gateway' => array(
492 'enabled' => $this->tpAppleGateway->enabled,
493 'id' => SECURETRADING_APPLE_PAY,
494 'site_reference' => $this->tpApiGateway->site_reference,
495 'merchant_id' => $this->tpAppleGateway->merchant_id,
496 'merchant_name' => $this->tpAppleGateway->merchant_name,
497 'button_style' => $this->tpAppleGateway->button_style,
498 'testmode' => $this->tpApiGateway->testmode
499 ),
500 'tp_paypal_gateway' => array(
501 'enabled' => $this->tpPaypalGateway->enabled,
502 'id' => SECURETRADING_PAYPAL
503 ),
504 );
505
506 wp_register_script( 'checkout_order_pay', plugins_url( '/assets/js/order-pay.js', SECURETRADING_FILE ), array(), self::VERSION, true );
507 wp_localize_script('checkout_order_pay', 'tp_order_pay', $order_pay);
508 wp_enqueue_script( 'checkout_order_pay');
509 wp_register_style( 'tp_order_pay_style', SECURETRADING_URL . '/assets/css/order-pay.css', array());
510 wp_enqueue_style( 'tp_order_pay_style' );
511 }
512 }
513
514 if ( is_checkout() && !is_wc_endpoint_url() ) {
515 if ( !empty($order_id) ) {
516 $order = wc_get_order($order_id);
517 $pay_now_url = $order->get_checkout_payment_url();
518 } else {
519 $pay_now_url = esc_url( wc_get_checkout_url() );
520 }
521
522 if ( 'yes' === $this->tpApiGateway->settings['enabled'] || 'yes' === $this->tpHppGateway->settings['enabled'] ) {
523 $order_pay_page = [
524 'ajax_url' => esc_url(admin_url('admin-ajax.php')),
525 'checkout_url' => $pay_now_url,
526 'page_id_setting' => !empty(strpos(wc_get_checkout_url(), 'page_id') ) ? true : false,
527 'datacenterurl' => SECURE_TRADING_US_WEBSERVICES_JWT,
528 'is_login' => is_user_logged_in(),
529 'currencyCode' => get_woocommerce_currency(),
530 'tp_api_gateway' => array(
531 'id' => SECURETRADING_API_ID,
532 'jwt' => esc_html($this->helper->mgn_update_jwt_address_details( '0', '', [], [], 0, 0, 0, SECURETRADING_API_ID, 0 )),
533 'tp_update_jwt_nonce' => wp_create_nonce('tp_api_update_jwt_nonce'),
534 'site_reference' => $this->tpApiGateway->site_reference,
535 '_tp_transaction_saved_card_id' => $this->tpApiGateway->_tp_transaction_saved_card_id,
536 'testmode' => $this->tpApiGateway->testmode,
537 'platform' => $this->tpApiGateway->platform,
538 'use_users_saved_credit_card_details' => $this->tpApiGateway->use_users_saved_credit_card_details,
539 'is_config' => ( empty( $this->tpApiGateway->site_reference ) || empty( $this->tpApiGateway->user_jwt ) || empty( $this->tpApiGateway->password_jwt ) ) ? false : true
540 ),
541 'tp_hpp_gateway' => array(
542 'id' => SECURETRADING_ID,
543 'jwt' => esc_html($this->helper->mgn_update_jwt_address_details( '0', '', [], [], 0, 0, 0, SECURETRADING_ID, 0 )),
544 '_tp_transaction_saved_card_id' => $this->tpHppGateway->_tp_transaction_saved_card_id,
545 'testmode' => $this->tpHppGateway->testmode,
546 'platform' => $this->tpHppGateway->platform,
547 'is_config' => ( empty( $this->tpHppGateway->sitereference ) || empty( $this->tpHppGateway->user_jwt ) || empty( $this->tpHppGateway->password_jwt ) ) ? false : true,
548 ),
549 'tp_google_gateway' => array(
550 'enabled' => $this->tpGoogleGateway->enabled,
551 'id' => SECURETRADING_GOOGLE_PAY,
552 'site_reference' => $this->tpApiGateway->site_reference,
553 'merchant_id' => $this->tpGoogleGateway->merchant_id,
554 'merchant_name' => $this->tpGoogleGateway->merchant_name,
555 'testmode' => $this->tpApiGateway->testmode,
556 'environment' => ( '1' === $this->tpApiGateway->testmode ) ? 'TEST' : 'PRODUCTION'
557 ),
558 'tp_apple_gateway' => array(
559 'enabled' => $this->tpAppleGateway->enabled,
560 'id' => SECURETRADING_APPLE_PAY,
561 'site_reference' => $this->tpApiGateway->site_reference,
562 'tp_apple_query_nonce' => wp_create_nonce('tp_apple_query_transaction_nonce'),
563 'merchant_id' => $this->tpAppleGateway->merchant_id,
564 'merchant_name' => $this->tpAppleGateway->merchant_name,
565 'button_style' => $this->tpAppleGateway->button_style,
566 'testmode' => $this->tpApiGateway->testmode,
567 'label' => ( !empty( $this->tpAppleGateway->merchant_name ) ) ? $this->tpAppleGateway->merchant_name : __( 'Trust Payments Merchant', SECURETRADING_TEXT_DOMAIN )
568 ),
569 'tp_paypal_gateway' => array(
570 'enabled' => $this->tpPaypalGateway->enabled,
571 'id' => SECURETRADING_PAYPAL
572 ),
573 ];
574
575 if ( !empty($order_id) ) {
576 $order_pay_page['pay_for_order'] = true;
577 }
578
579 $fieldsBilling = $this->wcCheckout->get_checkout_fields( 'billing' );
580 $fieldsShipping = $this->wcCheckout->get_checkout_fields( 'shipping' );
581 foreach ( $fieldsBilling as $key => $field ) {
582 if ( $field['required'] ) {
583 $order_pay_page['required_checkout']['billing'][$key] = $field['label'].__( ' is a required field.', SECURETRADING_TEXT_DOMAIN );
584 }
585 }
586 foreach ( $fieldsShipping as $key => $field ) {
587 if ( $field['required'] ) {
588 $order_pay_page['required_checkout']['shipping'][$key] = __( 'Shipping ', SECURETRADING_TEXT_DOMAIN ).$field['label'].__( ' is a required field.', SECURETRADING_TEXT_DOMAIN );
589 }
590 }
591 if ( wc_terms_and_conditions_checkbox_enabled() ) {
592 $order_pay_page['required_checkout']['terms'] = __( 'Please read and accept the terms and conditions to proceed with your order.', SECURETRADING_TEXT_DOMAIN );
593 }
594
595 wp_register_script( 'checkout_pay_page', plugins_url( '/assets/js/order-pay-page.js', SECURETRADING_FILE ), array(), self::VERSION, true );
596 wp_localize_script('checkout_pay_page', 'tp_pay_page', $order_pay_page);
597 wp_enqueue_script( 'checkout_pay_page');
598
599 // if ( 'yes' === $this->tpHppGateway->enabled &&
600 // empty($this->tpHppGateway->use_users_saved_credit_card_details) &&
601 // 'no' === $this->tpApiGateway->enabled &&
602 // 'no' === $this->tpGoogleGateway->enabled &&
603 // 'no' === $this->tpAppleGateway->enabled ) {
604 // wp_dequeue_script( 'checkout_pay_page');
605 // }
606 }
607 }
608 }
609
610 public function hide_templates($page_templates, $theme, $post ) {
611 $pageId = get_option('securetradingsecuretrading_page_id');
612
613 if ( $post && absint( $post->ID ) === $pageId ) {
614 $page_templates = array();
615 }
616
617 return $page_templates;
618 }
619
620 public function admin_styles() {
621 wp_register_style( 'st_admin_menu_styles', SECURETRADING_URL . '/assets/css/menu.css', array());
622 wp_enqueue_style( 'st_admin_menu_styles' );
623
624 $suffix = '';
625 wp_register_script( 'st_moto_payment', SECURETRADING_URL . '/assets/js/st_moto_payment'.$suffix.'.js', array(), self::VERSION, true );
626 wp_localize_script('st_moto_payment', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
627 }
628
629 public function securetrading_missing_wc_notice() {
630 echo '<div class="error"><p><strong>' . sprintf( esc_html__( 'Trust Payments requires WooCommerce to be installed and active. You can download %s here.', SECURETRADING_TEXT_DOMAIN), '<a href="https://woocommerce.com/" target="_blank">WooCommerce</a>' ) . '</strong></p></div>';
631 }
632
633 public function load_text_domain() {
634 load_plugin_textdomain( SECURETRADING_TEXT_DOMAIN, false, 'woocommerce-securetrading-gateway/languages/' );
635 }
636
637 public function add_securetrading_gateways($methods){
638 $methods[] = 'WC_SecureTrading_iFrame_Gateway';
639 $methods[] = 'WC_SecureTrading_API_Gateway';
640 $methods[] = 'WC_SecureTrading_Google_Gateway';
641 $methods[] = 'WC_SecureTrading_Apple_Gateway';
642 $methods[] = 'WC_SecureTrading_Paypal_Gateway';
643 $methods[] = 'WC_SecureTrading_A2A_Gateway';
644
645 return $methods;
646 }
647 public function install()
648 {
649 $this->create_pages();
650 }
651 /**
652 * create gift registry pages for plugin
653 */
654 public function create_pages() {
655 if (!function_exists('wc_create_page')) {
656 include_once dirname(__DIR__) . '/woocommerce/includes/admin/wc-admin-functions.php';
657 }
658 $pages = array(
659 'securetrading' => array(
660 'name' => _x('securetrading', 'Page slug', 'woocommerce'),
661 'title' => _x('Trust Payments', 'Page title', 'woocommerce'),
662 'content' => '[securetrading_iframe]'
663 )
664 );
665 foreach ($pages as $key => $page) {
666 wc_create_page(esc_sql($page ['name']), 'securetrading' . $key . '_page_id', $page ['title'], $page ['content'], !empty ($page ['parent']) ? wc_get_page_id($page ['parent']) : '');
667 }
668 }
669
670 public function create_post_type() {
671 $post_type = SECURETRADING_TRANSACTION_TYPE;
672 $args = array(
673 'labels' => array(
674 'name' => __('Trust Payments Transactions', SECURETRADING_TEXT_DOMAIN),
675 'singular_name' => 'st_transaction',
676 'all_items' => __( 'All transactions', SECURETRADING_TEXT_DOMAIN),
677 'menu_name' => _x( 'ST Transactions', 'Admin menu name', SECURETRADING_TEXT_DOMAIN),
678 'new_item' => false,
679 'view_item' => __( 'View transaction', SECURETRADING_TEXT_DOMAIN),
680 'view_items' => __( 'View transactions', SECURETRADING_TEXT_DOMAIN),
681 'search_items' => __( 'Search transactions', SECURETRADING_TEXT_DOMAIN),
682 'not_found' => __( 'No Transactions found', SECURETRADING_TEXT_DOMAIN),
683 'not_found_in_trash' => __( 'No transactions found in trash', SECURETRADING_TEXT_DOMAIN),
684 'parent' => __( 'Parent transaction', SECURETRADING_TEXT_DOMAIN),
685 'filter_items_list' => __( 'Filter transactions', SECURETRADING_TEXT_DOMAIN),
686 'items_list_navigation' => __( 'Transaction navigation', SECURETRADING_TEXT_DOMAIN),
687 'items_list' => __( 'Transactions list', SECURETRADING_TEXT_DOMAIN),
688 ),
689 'description' => __('This is where you can manage transactions of secure Trust Payments on your store.', SECURETRADING_TEXT_DOMAIN),
690 'public' => false,
691 'hierarchical' => false,
692 'show_ui' => true,
693 'show_in_menu' => true,
694 'menu_position' => 18,
695 'can_export' => true,
696 'has_archive' => true,
697 'exclude_from_search' => false,
698 'publicly_queryable' => false,
699 'supports' => array(
700 'id',
701 'transaction_id',
702 'transaction_type',
703 'transaction_status',
704 'card_secure',
705 'status_detail',
706 'order_id',
707 'customer_email',
708 'response_data',
709 ),
710 'capabilities' => array(
711 'create_posts' => false
712 ),
713 'map_meta_cap' => true
714 );
715 register_post_type($post_type, $args);
716 }
717
718 public function securetrading_iframe() {
719 $params = $this->helper->get_params();
720 $order_id = isset($params['order_id']) ? $params['order_id'] : null;
721 $rule = isset($params['rule']) ? $params['rule'] : null;
722 $st_iframe_setting = get_option('woocommerce_securetrading_iframe_settings');
723 if(!empty($order_id) && !empty($rule)) {
724 $order = wc_get_order($order_id);
725 if ( 'yes' !== $st_iframe_setting['site_notification'] || ( 'yes' === $st_iframe_setting['site_notification'] && 'ATA' === $params['paymenttypedescription'] ) ) {
726 if ( 'ATA' === $params['paymenttypedescription'] ) {
727 update_post_meta($order_id, '_checkout_complete_ata', 'completed');
728 }
729 // Debug log
730 $this->helper->securetrading_iframe_logs( 'Pay by HPP Response: '.wc_print_r($params, true), true );
731 $this->helper->response_return($order_id);
732 }
733 $url = $this->helper->get_return_url($order);
734 echo '<div class="blockUI blockOverlay" style="z-index: 100000; border: none; margin: 0px; padding: 0px; width: 100%; height: 100%; top: 0px; left: 0px; background: rgb(255, 255, 255); opacity: 1; cursor: default; position: absolute;"></div>';
735 echo '<style>body{ overflow: hidden; }.woo-multi-currency { display: none; }</style>';
736 echo "<script>document.addEventListener('DOMContentLoaded', function(){ window.top.location.href = '".$url."'; }); </script>";
737 } else {
738 $template_path = SECURETRADING_PATH . 'templates/';
739 $default_path = SECURETRADING_PATH . 'templates/';
740 $iFrame_width = $st_iframe_setting['width'] != null ? $st_iframe_setting['width'] : '100%';
741 $iFrame_height = $st_iframe_setting['height'] != null ? $st_iframe_setting['height'] : '600px';
742 if ( $order_id != null ) {
743 $order = wc_get_order($order_id);
744 if ( !empty($order) ) {
745 $payment_method = $order->get_payment_method();
746 $get_status = $order->get_status();
747 if ( 'pending' === $get_status && SECURETRADING_ID === $payment_method ) {
748 $url = $this->helper->prepare_required_fields($order_id);
749 $params = array(
750 'order_id' => $order_id,
751 'iFrame_width' => $iFrame_width,
752 'iFrame_height' => $iFrame_height,
753 'rule' => 'order',
754 'url' => $url
755 );
756 } else {
757 echo '<div class="blockUI blockOverlay" style="z-index: 100000; border: none; margin: 0px; padding: 0px; width: 100%; height: 100%; top: 0px; left: 0px; background: rgb(255, 255, 255); opacity: 1; cursor: default; position: absolute;"></div>';
758 echo '<style>body{overflow: hidden;}</style>';
759 echo "<script>document.addEventListener('DOMContentLoaded', function(){ window.top.location.href = '".wc_get_cart_url()."'; }); </script>";
760 }
761 } else {
762 wc_print_notice( __( 'Make your payments simpler.', SECURETRADING_TEXT_DOMAIN ), 'notice' );
763 }
764 } elseif ($rule == 'accountcheck_url') {
765 $url = $this->helper->prepare_data_save_card();
766 $params = array(
767 'order_id' => $order_id,
768 'iFrame_width' => $iFrame_width,
769 'iFrame_height' => $iFrame_height,
770 'rule' => 'accountcheck_url',
771 'url' => $url
772 );
773 }
774
775 ob_start();
776 wc_get_template('iframe-form.php', $params, $template_path, $default_path);
777 return ob_get_clean();
778 }
779 }
780
781 /**
782 * Process check brower ISO
783 */
784 public function disable_apple_pay( $available_gateways ) {
785 if ( is_admin() ) return $available_gateways;
786 $check_brower = $this->helper->check_brower();
787 if ( !$check_brower ) {
788 unset( $available_gateways[SECURETRADING_APPLE_PAY] );
789 }
790 return $available_gateways;
791 }
792
793 /**
794 * Save card JWT.
795 *
796 * @return $jwt_token
797 */
798 public function mgn_webservices_save_card_token() {
799 try{
800 $jwt_helper = new \Firebase\JWT\JWT();
801 $params = $this->helper->get_params();
802 $jwt = $params['jwt'];
803
804 /* User ID */
805 $current_user = wp_get_current_user();
806 $user_id = (!empty($current_user->ID)) ? $current_user->ID : 0;
807 $woocommerce_currency = get_option( 'woocommerce_currency' );
808
809 /* Check method */
810 $method = $params['method'];
811 if ( SECURETRADING_API_ID === $method ) {
812 $st_trustpayment_setting = get_option('woocommerce_securetrading_api_settings');
813 $secret = $st_trustpayment_setting['password_jwt'];
814 $webservices_Username = $st_trustpayment_setting['webservices_username'];
815 $webservies_Password = $st_trustpayment_setting['webservices_password'];
816 $site_reference = $st_trustpayment_setting['site_reference'];
817 $platform = $st_trustpayment_setting['platform'];
818 } elseif ( SECURETRADING_ID === $method ) {
819 $st_trustpayment_setting = get_option('woocommerce_securetrading_iframe_settings');
820 $secret = $st_trustpayment_setting['password_jwt'];
821 $webservices_Username = $st_trustpayment_setting['username'];
822 $webservies_Password = $st_trustpayment_setting['password'];
823 $site_reference = $st_trustpayment_setting['sitereference'];
824 $platform = $st_trustpayment_setting['platform'];
825 }
826
827 $jwt_decode = (array)$jwt_helper::decode($jwt, $secret,['HS256']);
828 if(is_array($jwt_decode) && isset($jwt_decode['payload'])) {
829 // ST API config.
830 $configData = array(
831 'username' => $webservices_Username,
832 'password' => $webservies_Password
833 );
834 if ( 'us' === $platform ) {
835 $configData['datacenterurl'] = SECURETRADING_US_WEBAPP;
836 }
837 $api = \Securetrading\api($configData);
838 $transactionArr = array();
839 $values = (array) $jwt_decode['payload'];
840 $responses = $values['response'];
841 foreach ($responses as $respons){
842 $respons = (array)$respons;
843 $transactionArr[] = array(
844 'value' => $respons['transactionreference']
845 );
846 }
847 $requestData = array(
848 'requesttypedescriptions' => array('TRANSACTIONQUERY'),
849 'filter' => array(
850 'sitereference' => array(
851 array(
852 'value' => $site_reference
853 )
854 ),
855 'currencyiso3a' => array(
856 array('value' => $woocommerce_currency)
857 ),
858 'transactionreference' => $transactionArr
859 )
860 );
861 $responses = $api->process($requestData)->toArray();
862 $payment_method_endpoint = get_option('woocommerce_myaccount_payment_methods_endpoint', true);
863 $url = wc_get_account_endpoint_url( $payment_method_endpoint );
864 $output = array(
865 'success' => true,
866 'url' => $url
867 );
868
869 if(is_array($responses) && isset($responses['responses']) && count($responses['responses']) > 0 && isset($responses['responses'][0]['records'])) {
870 $records = $responses['responses'][0]['records'];
871 if ( !empty($records) ) {
872 $save = '';
873 foreach ($records as $record) {
874 if ( 'ACCOUNTCHECK' === $record['requesttypedescription'] ) {
875 $save = true;
876 $token = array(
877 'transaction_reference' => $record['transactionreference'],
878 'payment_type_description' => $record['paymenttypedescription'],
879 'maskedpan' => $record['maskedpan'],
880 'expiry_date' => $record['expirydate']
881 );
882
883 if ( SECURETRADING_API_ID === $method ) {
884 $this->helper->save_card( $user_id, $token, SECURETRADING_API_ID);
885 } elseif ( SECURETRADING_ID === $method ) {
886 $this->helper->save_card( $user_id, $token, SECURETRADING_ID);
887 }
888 }
889 }
890 if ( true === $save ) {
891 $message = __('Save payment method success.', SECURETRADING_TEXT_DOMAIN);
892 wc_add_notice($message);
893 } else {
894 $message = __('ACCOUNTCHECK not found.', SECURETRADING_TEXT_DOMAIN);
895 wc_add_notice($message, 'error');
896 }
897 } else {
898 $message = __('No records found.', SECURETRADING_TEXT_DOMAIN);
899 wc_add_notice($message, 'error');
900 }
901 } else {
902 $message = __('Save payment method error. ', SECURETRADING_TEXT_DOMAIN);
903 $message .= __('Error: ', SECURETRADING_TEXT_DOMAIN);
904 $message .= $responses['responses'][0]['errorcode'].' - ';
905 $message .= $responses['responses'][0]['errormessage'];
906 wc_add_notice($message, 'error');
907 }
908 } else {
909 $message = __('Save payment method error. ', SECURETRADING_TEXT_DOMAIN);
910 $message .= __('Error: JWT decode error.', SECURETRADING_TEXT_DOMAIN);
911 wc_add_notice($message, 'error');
912 }
913 } catch (\Exception $exception) {
914 $output = array(
915 'success' => false,
916 'url' => ''
917 );
918 }
919
920 echo json_encode($output);
921 wp_die();
922 }
923
924 public function add_order_action($actions) {
925 global $theorder;
926 $payment_method = $theorder->get_payment_method();
927 $orderId = $theorder->get_id();
928 $payment_action = get_post_meta( $orderId,'securetrading_transaction_type',true );
929 $status = $theorder->get_status();
930 $tpMarkedCancelled = get_post_meta( $orderId, '_tp_marked_cancelled', true );
931 $tpMarkedCapture = get_post_meta( $orderId, '_tp_marked_capture', true );
932
933 if ( SECURETRADING_ID == $payment_method ) {
934 if( 'authorize' == $payment_action && 'on-hold' == $status ) {
935 $actions['st_capture_payment'] =__("Capture transaction via Trust Payments", SECURETRADING_TEXT_DOMAIN);
936 }
937
938 if( 'cancelled' != $status && 'refunded' != $status && 'failed' != $status ) {
939 $actions['st_cancel_payment'] =__("Cancel payment via Trust Payments", SECURETRADING_TEXT_DOMAIN);
940 }
941 }
942
943 if ( SECURETRADING_API_ID == $payment_method ) {
944 if( 'authorize' == $payment_action && 'on-hold' == $status && empty($tpMarkedCapture) ) {
945 $actions['st_api_capture_payment'] =__("Capture transaction via Trust Payments", SECURETRADING_TEXT_DOMAIN);
946 }
947
948 if( 'cancelled' != $status && 'refunded' != $status && 'failed' != $status && empty($tpMarkedCancelled) ) {
949 $actions['st_api_cancel_payment'] =__("Cancel payment via Trust Payments", SECURETRADING_TEXT_DOMAIN);
950 }
951 }
952
953 if ( SECURETRADING_GOOGLE_PAY == $payment_method ) {
954 if( 'authorize' == $payment_action && 'on-hold' == $status ) {
955 $actions['st_google_capture_payment'] =__("Capture transaction via Trust Payments", SECURETRADING_TEXT_DOMAIN);
956 }
957
958 if( 'cancelled' != $status && 'refunded' != $status && 'failed' != $status ) {
959 $actions['st_google_cancel_payment'] =__("Cancel payment via Trust Payments", SECURETRADING_TEXT_DOMAIN);
960 }
961 }
962
963 if ( SECURETRADING_APPLE_PAY == $payment_method ) {
964 if( 'authorize' == $payment_action && 'on-hold' == $status ) {
965 $actions['st_apple_capture_payment'] =__("Capture transaction via Trust Payments", SECURETRADING_TEXT_DOMAIN);
966 }
967
968 if( 'cancelled' != $status && 'refunded' != $status && 'failed' != $status ) {
969 $actions['st_apple_cancel_payment'] =__("Cancel payment via Trust Payments", SECURETRADING_TEXT_DOMAIN);
970 }
971 }
972
973 if ( 'tp_gateway' == $payment_method ) {
974 // if($payment_action == 'authorize' && $status == 'on-hold') {
975 // $actions['tp_gateway_capture_payment'] =__("Capture transaction via Trust Payments", SECURETRADING_TEXT_DOMAIN);
976 // }
977
978 if($status != 'cancelled' && $status != 'refunded' && $status != 'failed') {
979 $actions['tp_gateway_cancel_payment'] =__("Cancel payment via Trust Payments", SECURETRADING_TEXT_DOMAIN);
980 }
981 }
982
983 return $actions;
984 }
985
986 public function show_payment_method($total_rows, $order, $tax_display)
987 {
988 if($order->get_payment_method() == SECURETRADING_ID){
989 if ( $order->get_total() > 0 && $order->get_payment_method_title() && 'other' !== $order->get_payment_method_title() ) {
990 $orderId = $order->get_id();
991 $cardType = get_post_meta( $orderId, '_' . SECURETRADING_ID . '_card_type', true);
992 $cardNumber = get_post_meta( $orderId, '_' . SECURETRADING_ID . '_card_number', true);
993 $cardNumberArr = explode('#', $cardNumber);
994 $last4Digits = end($cardNumberArr);
995 if(strlen($last4Digits) > 4) {
996 $last4Digits = substr($last4Digits, -4);
997 }
998 $value = $order->get_payment_method_title();
999 if($cardType != null && $last4Digits != null){
1000 $value = $order->get_payment_method_title() ." - " .$cardType .", last 4 digits: " .$last4Digits;
1001 }
1002 $total_rows['payment_method'] = array(
1003 'label' => __( 'Payment method:', 'woocommerce' ),
1004 'value' => $value,
1005 );
1006 }
1007 } elseif ($order->get_payment_method() == SECURETRADING_API_ID) {
1008 if ( $order->get_total() > 0 && $order->get_payment_method_title() && 'other' !== $order->get_payment_method_title() ) {
1009 $orderId = $order->get_id();
1010 $cardType = get_post_meta( $orderId, '_' . SECURETRADING_API_ID . '_card_type', true);
1011 $cardNumber = get_post_meta( $orderId, '_' . SECURETRADING_API_ID . '_card_number', true);
1012 $cardNumberArr = explode('#', $cardNumber);
1013 $last4Digits = end($cardNumberArr);
1014 if(strlen($last4Digits) > 4) {
1015 $last4Digits = substr($last4Digits, -4);
1016 }
1017 $value = $order->get_payment_method_title();
1018 if($cardType != null && $last4Digits != null){
1019 $value = $order->get_payment_method_title() ." - " .$cardType .", last 4 digits: " .$last4Digits;
1020 }
1021 $total_rows['payment_method'] = array(
1022 'label' => __( 'Payment method:', 'woocommerce' ),
1023 'value' => $value,
1024 );
1025 }
1026 }
1027 return $total_rows;
1028 }
1029
1030 public static function getInstance(){
1031 if ( ! self::$securetrading_instance ) {
1032 self::$securetrading_instance = new self();
1033 }
1034 return self::$securetrading_instance;
1035 }
1036
1037 /**
1038 * @snippet Process order
1039 * @sourcecode https://magenest.com/
1040 * @author Minh Hung
1041 */
1042 public function tp_process_order() {
1043 // POST data
1044 $transactionreference = isset($_POST['transactionreference']) ? $_POST['transactionreference'] : '';
1045 $post_transactiondata = (!empty($_POST['transactiondata'])) ? sanitize_text_field(wp_unslash($_POST['transactiondata'])) : null;
1046 $moto = (!empty($_POST['is_moto'])) ? $_POST['is_moto'] : null;
1047 $is_order_pay = (!empty($_POST['is_order_pay'])) ? $_POST['is_order_pay'] : null;
1048 $json_str_array = json_decode($post_transactiondata, true);
1049 $walletsource = (!empty($_POST['walletsource'])) ? $_POST['walletsource'] : null;
1050 $order_id = !empty( $json_str_array['orderreference'] ) ? (int)$json_str_array['orderreference'] : (int)WC()->session->get('order_awaiting_payment');
1051
1052 if (empty($order_id)) {
1053 /* Logger */
1054 $this->helper->securetrading_api_logs( 'I tried hard, but no order was found for confirmation.', true);
1055
1056 $message = __('I tried hard, but no order was found for confirmation.', SECURETRADING_TEXT_DOMAIN);
1057 $output = array(
1058 'success' => false,
1059 'url' => esc_url( wc_get_checkout_url() ),
1060 'message' => $message
1061 );
1062 wc_add_notice($message,'error' );
1063
1064 echo json_encode($output);
1065 wp_die();
1066 }
1067
1068 // Payment method
1069 $order = wc_get_order($order_id);
1070 $payment_method = $order->get_payment_method();
1071
1072 if ( null === $payment_method && 'GOOGLEPAY' === $walletsource ) {
1073 // Update Payment method
1074 $payment_method = SECURETRADING_GOOGLE_PAY;
1075 }
1076
1077 // Checkout area
1078 if ( $is_order_pay ) {
1079 $checkout_url = $order->get_checkout_payment_url();
1080 } else {
1081 $checkout_url = esc_url( wc_get_checkout_url() );
1082 }
1083
1084 // Setting
1085 if ( $payment_method === SECURETRADING_ID ) {
1086 $settings = get_option('woocommerce_securetrading_iframe_settings');
1087 } else {
1088 $settings = get_option('woocommerce_securetrading_api_settings');
1089 }
1090
1091 if ( $moto ) {
1092 $payment_method = SECURETRADING_API_ID;
1093 }
1094
1095 // Check Notification URL
1096 if ( 'yes' == $settings['site_notification'] ) {
1097 if ( $moto ) {
1098 $url = get_edit_post_link( $order_id, 'url' );
1099 $output = array(
1100 'success' => true,
1101 'url' => $url
1102 );
1103 } else {
1104 $output = array(
1105 'success' => true,
1106 'notification' => true,
1107 'url' => $order->get_checkout_order_received_url()
1108 );
1109 }
1110
1111 echo json_encode($output);
1112 wp_die();
1113 }
1114
1115 if (!empty($post_transactiondata)) {
1116 // Get transaction data.
1117 $json_str_array = json_decode($post_transactiondata, true);
1118
1119 // If we have a result.
1120 if (!empty($json_str_array)) {
1121 $order->update_meta_data( '_billing_address_index', $json_str_array );
1122 }
1123 } else {
1124 // Save to woocommerce log.
1125 $this->helper->securetrading_api_logs( 'Order POST Error: Order ID '.$order_id.' Transaction Ref '.$transactionreference.' - Result: Post transaction data is empty.', true);
1126 // We shouldn't go any further.
1127 // echo 'error: post transaction null';
1128 $message = sprintf( __('Order ID %s Transaction Ref %s - Result: Post transaction data is empty.', SECURETRADING_TEXT_DOMAIN), $order_id, $transactionreference );
1129 $output = array(
1130 'success' => false,
1131 'url' => $checkout_url,
1132 'message' => $message
1133 );
1134 wc_add_notice($message,'error' );
1135
1136 echo json_encode($output);
1137 wp_die();
1138 }
1139
1140 $subscriptiondata = json_decode( $post_transactiondata );
1141 if ( ! empty( $subscriptiondata->subscriptionnumber ) && $subscriptiondata->subscriptionnumber != "1" && $subscriptiondata->errorcode === "0"
1142 || empty( $subscriptiondata->subscriptionnumber ) && $subscriptiondata->errorcode === "0" ) {
1143 // Add woocommerce order id to myst.
1144 $myst_updated = $this->helper->mgn_add_woocommerce_order_id_to_myst($transactionreference, $order_id, $payment_method);
1145 // If myst isn't updated.
1146 if (empty($myst_updated)) {
1147 // Debug.
1148 // Save to woocommerce log.
1149 $this->helper->securetrading_api_logs( 'Order Update Failed: Order ID '.$order_id.' Transaction Ref '.$transactionreference.' - Result: Add Woocommerce Order ID to MyST failed.', true);
1150 // We shouldn't go any further.
1151 // echo "error: order id rejected";
1152 $message = sprintf( __('Order ID %s Transaction Ref %s - Result: Add Woocommerce Order ID to MyST failed.', SECURETRADING_TEXT_DOMAIN), $order_id, $transactionreference );
1153 $output = array(
1154 'success' => false,
1155 'url' => $checkout_url,
1156 'message' => $message
1157 );
1158 wc_add_notice($message,'error' );
1159
1160 echo json_encode($output);
1161 wp_die();
1162 }
1163 }
1164
1165 // Confirm post order data.
1166 $payment_confirmed = $this->helper->mgn_confirm_post_order_data($transactionreference, $payment_method);
1167 if (empty($payment_confirmed) || true !== $payment_confirmed['success']) {
1168 // We shouldn't go any further.
1169 // echo "error: order id rejected";
1170 $message = __('Order ID not comfirm.', SECURETRADING_TEXT_DOMAIN);
1171 $output = array(
1172 'success' => false,
1173 'url' => $checkout_url,
1174 'message' => $message
1175 );
1176 wc_add_notice($message,'error' );
1177 } else {
1178 // WordPress process
1179 $arr = (array) $subscriptiondata;
1180 // Debug log
1181 if ( $payment_method === SECURETRADING_API_ID ) {
1182 $this->helper->securetrading_api_logs( 'Pay by JS Response: '.wc_print_r($arr, true), true );
1183 } elseif ( $payment_method === SECURETRADING_ID ) {
1184 $this->helper->securetrading_iframe_logs( 'Pay by HPP Response: '.wc_print_r($arr, true), true );
1185 } elseif ( $payment_method === SECURETRADING_GOOGLE_PAY ) {
1186 $this->helper->securetrading_google_pay_logs( 'Pay by Google Pay Response: '.wc_print_r($arr, true), true );
1187 } elseif ( $payment_method === SECURETRADING_APPLE_PAY ) {
1188 $this->helper->securetrading_apple_pay_logs( 'Pay by Apple Pay Response: '.wc_print_r($arr, true), true );
1189 } elseif ( $payment_method === SECURETRADING_A2A ) {
1190 $this->helper->securetrading_a2a_logs( 'Pay by A2A Pay Response: '.wc_print_r($arr, true), true );
1191 }
1192 $customer_email = $order->get_billing_email();
1193 $raw_data = array(
1194 'transaction_id' => isset($arr['transactionreference']) ? $arr['transactionreference'] : '',
1195 'transaction_parent_id' => isset($arr['parenttransactionreference']) ? $arr['parenttransactionreference'] : '',
1196 'transaction_type' => 'Capture',
1197 'transaction_status' => isset($arr['settlestatus']) ? $arr['settlestatus'] : '',
1198 'order_id' => $order_id,
1199 'customer_email' => $customer_email,
1200 'payment_type_description' => isset($arr['paymenttypedescription']) ? $arr['paymenttypedescription'] : '',
1201 'request_reference' => isset($arr['requestreference']) ? $arr['requestreference'] : '',
1202 );
1203
1204 $this->helper->create_transaction($raw_data);
1205 if ( $payment_method === SECURETRADING_APPLE_PAY ) {
1206 $orderAppleData = (array)$payment_confirmed['response'][0];
1207 $this->helper->process_response_api($order_id, $arr, $payment_method, $orderAppleData);
1208 } else {
1209 $this->helper->process_response_api($order_id, $arr, $payment_method);
1210 }
1211
1212 if((isset($arr['errorcode']) && $arr['errorcode'] == "70000") || (isset($arr['authcode']) && $arr['authcode'] == 'DECLINED')) {
1213 $order->update_meta_data( '_payment_is_declined', true );
1214 $output = array(
1215 'success' => false,
1216 'url' => $checkout_url,
1217 'message' => __("Transaction declined by card issuer. Please re-attempt with another card or contact your card issuer.", SECURETRADING_TEXT_DOMAIN)
1218 );
1219 wc_add_notice( __("Transaction declined by card issuer. Please re-attempt with another card or contact your card issuer."),'error' );
1220 } elseif( isset($arr['errorcode']) && '0' == $arr['errorcode'] ) {
1221 if ( $moto ) {
1222 $url = get_edit_post_link( $order_id, 'url' );
1223 } else {
1224 $url = $this->helper->get_return_url($order);
1225 }
1226
1227 $output = array(
1228 'success' => true,
1229 'url' => $url
1230 );
1231 $order->update_meta_data( '_payment_is_declined', false );
1232
1233 /* Save card */
1234 if ( $payment_method === SECURETRADING_API_ID ) {
1235 $save_card = get_post_meta($order_id, '_' . SECURETRADING_API_ID . '_save_card', true);
1236 if ('AUTH' === $arr['requesttypedescription'] && $save_card) {
1237 $records = (array)$payment_confirmed['response'];
1238 /* Save user meta */
1239 $current_user = wp_get_current_user();
1240 $userid = (!empty($current_user->ID)) ? $current_user->ID : 0;
1241 foreach ($records as $value) {
1242 $record = (array)$value;
1243 if ('AUTH' === $record['requesttypedescription']) {
1244 $token = array(
1245 'transaction_reference' => $record['transactionreference'],
1246 'payment_type_description' => $record['paymenttypedescription'],
1247 'maskedpan' => $record['maskedpan'],
1248 'expiry_date' => $record['expirydate']
1249 );
1250 $this->helper->save_card($userid, $token, SECURETRADING_API_ID);
1251
1252 /* Save expiry */
1253 $expiry = explode('/', $record['expirydate']);
1254 $expiry_month = $expiry_year = '';
1255 if (is_array($expiry) && count($expiry) == 2) {
1256 $expiry_month = $expiry[0];
1257 $expiry_year = $expiry[1];
1258 }
1259 $order->update_meta_data( '_' . SECURETRADING_API_ID . '_card_month', $expiry_month );
1260 $order->update_meta_data( '_' . SECURETRADING_API_ID . '_card_year', $expiry_year );
1261 }
1262 }
1263 }
1264 }
1265 }
1266 }
1267
1268 echo json_encode($output);
1269 wp_die();
1270 }
1271
1272 /**
1273 * @snippet Apple Pay query transaction
1274 * @sourcecode https://magenest.com/
1275 * @author Minh Hung
1276 */
1277 public function tp_apple_query_transaction() {
1278 // Verify nonce.
1279 check_ajax_referer( 'tp_apple_query_transaction_nonce', 'tp_apple_query_nonce' );
1280
1281 $transactionreference = isset($_POST['transactionreference']) ? $_POST['transactionreference'] : '';
1282 // If we have a transaction reference.
1283 if (!empty($transactionreference)) {
1284 $payment_method = SECURETRADING_APPLE_PAY;
1285 $transaction_data = $this->helper->mgn_confirm_post_order_data($transactionreference, $payment_method);
1286 if (empty($transaction_data) || true !== $transaction_data['success']) {
1287 // We shouldn't go any further.
1288 // echo "error: order id rejected";
1289 $message = __('Incorrect Webservices details - Invalid data has been submitted. Please contact the merchant.', SECURETRADING_TEXT_DOMAIN);
1290 $output = array(
1291 'success' => false,
1292 'url' => esc_url( wc_get_checkout_url() ),
1293 'message' => $message
1294 );
1295 wc_add_notice($message,'error' );
1296 } else {
1297 $output = array(
1298 'success' => true,
1299 'data' => (array)$transaction_data['response'][0]
1300 );
1301 }
1302 } else {
1303 // We shouldn't go any further.
1304 // echo "error: order id rejected";
1305 $message = __('No transaction found.', SECURETRADING_TEXT_DOMAIN);
1306 $output = array(
1307 'success' => false,
1308 'url' => esc_url( wc_get_checkout_url() ),
1309 'message' => $message
1310 );
1311 wc_add_notice($message,'error' );
1312 }
1313
1314 echo json_encode($output);
1315 wp_die();
1316 }
1317
1318 /**
1319 * @snippet Process order
1320 * @sourcecode https://magenest.com/
1321 * @author Minh Hung
1322 */
1323 public function tp_log_note_order() {
1324 $transactionreference = isset($_POST['transactionreference']) ? $_POST['transactionreference'] : '';
1325 $post_transactiondata = (!empty($_POST['transactiondata'])) ? sanitize_text_field(wp_unslash($_POST['transactiondata'])) : null;
1326 $payment_method = (!empty($_POST['payment_method'])) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : null;
1327 $walletsource = (!empty($_POST['walletsource'])) ? sanitize_text_field(wp_unslash($_POST['walletsource'])) : null;
1328
1329 if ( $payment_method === SECURETRADING_API_ID || !empty($walletsource) ) {
1330 // get tp gateway settings.
1331 $settings = get_option('woocommerce_securetrading_api_settings');
1332
1333 // get purchase details.
1334 $userpwd = $settings['webservices_username'].':'.$settings['webservices_password'];
1335 $alias = $settings['webservices_username'];
1336 $sitereference = $settings['site_reference'];
1337 } elseif ( $payment_method === SECURETRADING_ID ) {
1338 $settings = get_option('woocommerce_securetrading_iframe_settings');
1339
1340 // get purchase details.
1341 $userpwd = $settings['username'].':'.$settings['password'];
1342 $alias = $settings['username'];
1343 $sitereference = $settings['sitereference'];
1344 }
1345
1346 // Create args for transaction data.
1347 $args = [
1348 'headers' => [
1349 'Authorization' => 'Basic '.base64_encode($userpwd),
1350 ],
1351 'body' => '{
1352 "alias":"'.$alias.'",
1353 "version":"1.0",
1354 "request":[
1355 {
1356 "requesttypedescriptions":[
1357 "TRANSACTIONQUERY"
1358 ],
1359 "filter":{
1360 "sitereference":[
1361 {
1362 "value":"'.$sitereference.'"
1363 }
1364 ],
1365 "transactionreference":[
1366 {
1367 "value":"'.$transactionreference.'"
1368 }
1369 ]
1370 }
1371 }
1372 ]
1373 }',
1374 ];
1375 // Get response.
1376 $platform = $settings['platform'];
1377 if ( 'eu' === $platform ) {
1378 $response = wp_remote_post(SECURE_TRADING_EU_WEBSERVICES_JSON, $args);
1379 } elseif ( 'us' === $platform ) {
1380 $response = wp_remote_post(SECURE_TRADING_US_WEBSERVICES_JSON, $args);
1381 }
1382 $response_body = wp_remote_retrieve_body($response);
1383 $json_response = json_decode($response_body);
1384
1385 // If response error message is OK ( alls good ), payment is confirmed.
1386 if (!empty($json_response->response[0]->errormessage) && 'Ok' === $json_response->response[0]->errormessage) {
1387 $responseRecords = (array) $json_response->response[0];
1388 $records = ( array_key_exists('records', $responseRecords) && !empty($responseRecords['records']) ) ? $responseRecords['records'] : [];
1389 if ( empty( $records ) ) {
1390 wp_die();
1391 }
1392
1393 /* Logger */
1394 $this->helper->securetrading_api_logs( print_r($records, true), true);
1395
1396 $order_id = (int)$records[0]->orderreference;
1397 if ( !empty($order_id) && is_int($order_id) ) {
1398 if (!empty($post_transactiondata)) {
1399 // Get transaction data.
1400 $json_str_array = json_decode($post_transactiondata, true);
1401
1402 // If we have a result.
1403 if (!empty($json_str_array)) {
1404 update_post_meta($order_id, '_billing_address_index', $json_str_array);
1405 }
1406 }
1407
1408 if (!empty($transactionreference)) {
1409 $order = wc_get_order($order_id);
1410 $message = sprintf(__('Trust Payments return status: Decline payment (Transaction ID: %s)', SECURETRADING_TEXT_DOMAIN), $transactionreference);
1411 $order->add_order_note($message);
1412 }
1413 }
1414 }
1415
1416 wp_die();
1417 }
1418
1419 /**
1420 * @snippet Add billing/customer address for MyST.
1421 * @sourcecode https://magenest.com/
1422 * @author Minh Hung
1423 */
1424 public function st_api_update_address_myst() {
1425 // Verify nonce.
1426 // If nonce is not valid we should exit here.
1427 $nonce = (!empty($_POST['_wpnonce'])) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
1428 if (!empty($_POST) && !wp_verify_nonce($nonce, 'st-api-update-address-myst-nonce')) {
1429 echo '['.SECURETRADING_VERSION.'] Invalid Update Address MyST Nonce';
1430 exit();
1431 }
1432
1433 // Set $_POST update address value.
1434 $post_update_address = (!empty($_POST['update_address'])) ? sanitize_text_field(wp_unslash($_POST['update_address'])) : '';
1435 // Set $_POST orderid value.
1436 $post_orderid = (!empty($_POST['orderid'])) ? (int) $_POST['orderid'] : 0;
1437
1438 if (empty($post_orderid)) {
1439 $post_orderid = (int)WC()->session->get('order_awaiting_payment');
1440 }
1441
1442 // Set $_POST billing values.
1443 $post_billing_first_name = (!empty($_POST['billing_first_name'])) ? sanitize_text_field(wp_unslash($_POST['billing_first_name'])) : '';
1444 $post_billing_last_name = (!empty($_POST['billing_last_name'])) ? sanitize_text_field(wp_unslash($_POST['billing_last_name'])) : '';
1445 $post_billing_address_1 = (!empty($_POST['billing_address_1'])) ? sanitize_text_field(wp_unslash($_POST['billing_address_1'])) : '';
1446 $post_billing_address_2 = (!empty($_POST['billing_address_2'])) ? sanitize_text_field(wp_unslash($_POST['billing_address_2'])) : '';
1447 $post_billing_city = (!empty($_POST['billing_city'])) ? sanitize_text_field(wp_unslash($_POST['billing_city'])) : '';
1448 $post_billing_company = (!empty($_POST['billing_company'])) ? sanitize_text_field(wp_unslash($_POST['billing_company'])) : '';
1449 $post_billing_state = (!empty($_POST['billing_state'])) ? sanitize_text_field(wp_unslash($_POST['billing_state'])) : '';
1450 $post_billing_postcode = (!empty($_POST['billing_postcode'])) ? sanitize_text_field(wp_unslash($_POST['billing_postcode'])) : '';
1451 $post_billing_country = (!empty($_POST['billing_country'])) ? sanitize_text_field(wp_unslash($_POST['billing_country'])) : '';
1452 $post_billing_phone = (!empty($_POST['billing_phone'])) ? sanitize_text_field(wp_unslash($_POST['billing_phone'])) : '';
1453 $post_billing_email = (!empty($_POST['billing_email'])) ? sanitize_text_field(wp_unslash($_POST['billing_email'])) : '';
1454 // Set $_POST shipping values.
1455 $post_shipping_first_name = (!empty($_POST['shipping_first_name']) && 'undefined' !== $_POST['shipping_first_name']) ? sanitize_text_field(wp_unslash($_POST['shipping_first_name'])) : '';
1456 $post_shipping_last_name = (!empty($_POST['shipping_last_name']) && 'undefined' !== $_POST['shipping_last_name']) ? sanitize_text_field(wp_unslash($_POST['shipping_last_name'])) : '';
1457 $post_shipping_address_1 = (!empty($_POST['shipping_address_1']) && 'undefined' !== $_POST['shipping_address_1']) ? sanitize_text_field(wp_unslash($_POST['shipping_address_1'])) : '';
1458 $post_shipping_address_2 = (!empty($_POST['shipping_address_2']) && 'undefined' !== $_POST['shipping_address_2']) ? sanitize_text_field(wp_unslash($_POST['shipping_address_2'])) : '';
1459 $post_shipping_city = (!empty($_POST['shipping_city']) && 'undefined' !== $_POST['shipping_city']) ? sanitize_text_field(wp_unslash($_POST['shipping_city'])) : '';
1460 $post_shipping_company = (!empty($_POST['shipping_company']) && 'undefined' !== $_POST['shipping_company']) ? sanitize_text_field(wp_unslash($_POST['shipping_company'])) : '';
1461 $post_shipping_state = (!empty($_POST['shipping_state']) && 'undefined' !== $_POST['shipping_state']) ? sanitize_text_field(wp_unslash($_POST['shipping_state'])) : '';
1462 $post_shipping_postcode = (!empty($_POST['shipping_postcode']) && 'undefined' !== $_POST['shipping_postcode']) ? sanitize_text_field(wp_unslash($_POST['shipping_postcode'])) : '';
1463 $post_shipping_country= (!empty($_POST['shipping_country']) && 'undefined' !== $_POST['shipping_country']) ? sanitize_text_field(wp_unslash($_POST['shipping_country'])) : '';
1464 // Set $_POST shipping rate.
1465 $post_shipping_rate = (!empty($_POST['shipping_rate'])) ? $_POST['shipping_rate'] : '';
1466 // Debuger
1467 $debugger = (!empty($_POST['debugger'])) ? $_POST['debugger'] : '';
1468
1469 // if order empty
1470 if (isset($post_update_address)) {
1471 // save credit card details.
1472 $save_credit_card_details = (!empty($_POST['save_credit_card_details_checkbox'])) ? sanitize_text_field(wp_unslash($_POST['save_credit_card_details_checkbox'])) : '';
1473
1474 // billing details.
1475 $billing_details = [];
1476 $billing_details['billing_first_name'] = (!empty($post_billing_first_name)) ? str_replace('\\', '', $post_billing_first_name) : '';
1477 $billing_details['billing_last_name'] = (!empty($post_billing_last_name)) ? str_replace('\\', '', $post_billing_last_name) : '';
1478 $billing_details['billing_address_1'] = (!empty($post_billing_address_1)) ? str_replace('\\', '', $post_billing_address_1) : '';
1479 $billing_details['billing_address_2'] = (!empty($post_billing_address_2)) ? str_replace('\\', '', $post_billing_address_2) : '';
1480 $billing_details['billing_city'] = (!empty($post_billing_city)) ? str_replace('\\', '', $post_billing_city) : '';
1481 $billing_details['billing_company'] = (!empty($post_billing_company)) ? str_replace('\\', '', $post_billing_company) : '';
1482 $billing_details['billing_state'] = (!empty($post_billing_state)) ? str_replace('\\', '', $post_billing_state) : '';
1483 $billing_details['billing_postcode'] = (!empty($post_billing_postcode)) ? str_replace('\\', '', $post_billing_postcode) : '';
1484 $billing_details['billing_country'] = (!empty($post_billing_country)) ? str_replace('\\', '', $post_billing_country) : '';
1485 $billing_details['billing_phone'] = (!empty($post_billing_phone)) ? str_replace('\\', '', $post_billing_phone) : '';
1486 $billing_details['billing_email'] = (!empty($post_billing_email)) ? str_replace('\\', '', $post_billing_email) : '';
1487
1488 // shipping details.
1489 $shipping_details = [];
1490 $shipping_details['shipping_first_name'] = (!empty($post_shipping_first_name)) ? str_replace('\\', '', $post_shipping_first_name) : '';
1491 $shipping_details['shipping_last_name'] = (!empty($post_shipping_last_name)) ? str_replace('\\', '', $post_shipping_last_name) : '';
1492 $shipping_details['shipping_address_1'] = (!empty($post_shipping_address_1)) ? str_replace('\\', '', $post_shipping_address_1) : '';
1493 $shipping_details['shipping_address_2'] = (!empty($post_shipping_address_2)) ? str_replace('\\', '', $post_shipping_address_2) : '';
1494 $shipping_details['shipping_city'] = (!empty($post_shipping_city)) ? str_replace('\\', '', $post_shipping_city) : '';
1495 $shipping_details['shipping_company'] = (!empty($post_shipping_company)) ? str_replace('\\', '', $post_shipping_company) : '';
1496 $shipping_details['shipping_state'] = (!empty($post_shipping_state)) ? str_replace('\\', '', $post_shipping_state) : '';
1497 $shipping_details['shipping_postcode'] = (!empty($post_shipping_postcode)) ? str_replace('\\', '', $post_shipping_postcode) : '';
1498 $shipping_details['shipping_country'] = (!empty($post_shipping_country)) ? str_replace('\\', '', $post_shipping_country) : '';
1499
1500 // get the WC Order.
1501 $order = new WC_Order($post_orderid);
1502
1503 $billing = array(
1504 'first_name' => !empty($billing_details['billing_first_name']) ? $billing_details['billing_first_name'] : '',
1505 'last_name' => !empty($billing_details['billing_last_name']) ? $billing_details['billing_last_name'] : '',
1506 'company' => !empty($billing_details['billing_company']) ? $billing_details['billing_company'] : '',
1507 'email' => !empty($billing_details['billing_email']) ? $billing_details['billing_email'] : '',
1508 'phone' => !empty($billing_details['billing_phone']) ? $billing_details['billing_phone'] : '',
1509 'address_1' => !empty($billing_details['billing_address_1']) ? $billing_details['billing_address_1'] : '',
1510 'address_2' => !empty($billing_details['billing_address_2']) ? $billing_details['billing_address_2'] : '',
1511 'city' => !empty($billing_details['billing_city']) ? $billing_details['billing_city'] : '',
1512 'postcode' => !empty($billing_details['billing_postcode']) ? $billing_details['billing_postcode'] : '',
1513 'state' => !empty($billing_details['billing_state']) ? $billing_details['billing_state'] : '',
1514 'country' => !empty($billing_details['billing_country']) ? $billing_details['billing_country'] : '',
1515 );
1516
1517 $shipping = array(
1518 'first_name' => !empty($shipping_details['shipping_first_name']) ? $shipping_details['shipping_first_name'] : '',
1519 'last_name' => !empty($shipping_details['shipping_last_name']) ? $shipping_details['shipping_last_name'] : '',
1520 'company' => !empty($shipping_details['shipping_company']) ? $shipping_details['shipping_company'] : '',
1521 'address_1' => !empty($shipping_details['shipping_address_1']) ? $shipping_details['shipping_address_1'] : '',
1522 'address_2' => !empty($shipping_details['shipping_address_2']) ? $shipping_details['shipping_address_2'] : '',
1523 'city' => !empty($shipping_details['shipping_city']) ? $shipping_details['shipping_city'] : '',
1524 'postcode' => !empty($shipping_details['shipping_postcode']) ? $shipping_details['shipping_postcode'] : '',
1525 'state' => !empty($shipping_details['shipping_state']) ? $shipping_details['shipping_state'] : '',
1526 'country' => !empty($shipping_details['shipping_country']) ? $shipping_details['shipping_country'] : '',
1527 );
1528
1529 $order->set_address( $billing, 'billing' );
1530 $order->set_address( $shipping, 'shipping' );
1531
1532 // get the order total.
1533 $order_total = $order->get_total();
1534
1535 // get the order shipping total.
1536 $order_shipping_total = $order->get_shipping_total();
1537
1538 // get shipping package rate
1539 $shipping_package_rate = 0;
1540 $all_shipping_package_rates = (!empty(WC()->session->get('shipping_for_package_0')['rates'])) ? WC()->session->get('shipping_for_package_0')['rates'] : '';
1541 if (!empty($all_shipping_package_rates)) {
1542 foreach ($all_shipping_package_rates as $key => $value) {
1543 if ($post_shipping_rate != '' && $post_shipping_rate === $value->get_id()) {
1544 $shipping_package_rate = $value->get_cost() * 100;
1545 }
1546 }
1547 }
1548
1549 // Payment method
1550 $payment_method = $order->get_payment_method();
1551
1552 // Helper
1553 $result = $this->helper->mgn_update_jwt_address_details(
1554 $post_orderid,
1555 $save_credit_card_details,
1556 $billing_details,
1557 $shipping_details,
1558 $shipping_package_rate,
1559 $order_total,
1560 $order_shipping_total,
1561 $payment_method,
1562 $debugger
1563 );
1564
1565 // return result.
1566 echo esc_html($result);
1567 }
1568 }
1569
1570 /**
1571 * @snippet Order Pay update JWT
1572 * @sourcecode https://magenest.com/
1573 * @author Minh Hung
1574 */
1575 public function tp_order_pay_update_jwt() {
1576 // Verify nonce.
1577 check_ajax_referer( 'tp_oder_pay_create_nonce', 'tp_oder_pay_nonce' );
1578
1579 $order_id = (!empty($_POST['order_id'])) ? $_POST['order_id'] : '';
1580 $paymentMethod = (!empty($_POST['payment_method'])) ? $_POST['payment_method'] : '';
1581 $save_card = filter_var($_POST['save_card'] ?? false, FILTER_VALIDATE_BOOLEAN);
1582 $use_users_saved_card = (!empty($_POST['use_users_saved_card'])) ? $_POST['use_users_saved_card'] : '';
1583 $order = wc_get_order($order_id);
1584 $order->set_payment_method($paymentMethod);
1585 $order->save();
1586 $isGuest = false;
1587 if ( empty($save_card) && empty($use_users_saved_card) ) {
1588 $isGuest = true;
1589 }
1590
1591 if ( true === $save_card ) {
1592 update_post_meta($order_id, '_'.SECURETRADING_API_ID.'_save_card', true);
1593 }
1594
1595 if ( !empty($use_users_saved_card) ) {
1596 global $wpdb;
1597 $table_woocommerce_payment_tokens = $wpdb->prefix . 'woocommerce_payment_tokens';
1598 $token = $wpdb->get_var("SELECT token FROM {$table_woocommerce_payment_tokens} WHERE token_id = {$use_users_saved_card}");
1599 update_post_meta($order_id, '_'.$paymentMethod.'_parent_transaction_reference', $token);
1600 }
1601
1602 // Helper
1603 $result = $this->helper->mgn_update_jwt_address_details(
1604 $order_id,
1605 $save_card,
1606 [],
1607 [],
1608 0,
1609 0,
1610 0,
1611 $paymentMethod,
1612 1,
1613 $isGuest
1614 );
1615
1616 // return result.
1617 echo esc_html($result);
1618 }
1619
1620 /**
1621 * @snippet Order get JWT
1622 * @sourcecode https://magenest.com/
1623 * @author Minh Hung
1624 */
1625 public function tp_apple_order_jwt() {
1626 // Verify nonce.
1627 check_ajax_referer( 'tp_apple_query_transaction_nonce', 'tp_apple_query_nonce' );
1628 $orderId = WC()->session->get('order_awaiting_payment');
1629 $shippingMethodSelected = (!empty($_POST['shipping_method_selected'])) ? $_POST['shipping_method_selected'] : '';
1630 $shippingAddressInfo = (!empty($_POST['shipping_address_info'])) ? (array)$_POST['shipping_address_info'] : [];
1631 if ( empty($orderId) ) {
1632 $createOrderData = [
1633 'payment_method' => SECURETRADING_APPLE_PAY,
1634 ];
1635 $orderId = $this->wcCheckout->create_order($createOrderData);
1636 WC()->session->set('order_awaiting_payment', $orderId);
1637 }
1638 $order = wc_get_order($orderId);
1639 if ( $shippingAddressInfo ) {
1640 $billing = [
1641 'first_name' => $shippingAddressInfo['phoneticGivenName'] ?? null,
1642 'last_name' => $shippingAddressInfo['phoneticFamilyName'] ?? null,
1643 'company' => $shippingAddressInfo['company'] ?? null,
1644 'email' => $shippingAddressInfo['email'] ?? null,
1645 'phone' => $shippingAddressInfo['phone'] ?? null,
1646 'address_1' => $shippingAddressInfo['administrativeArea'] ?? null,
1647 'address_2' => $shippingAddressInfo['subAdministrativeArea'] ?? null,
1648 'city' => $shippingAddressInfo['locality'] ?? null,
1649 'postcode' => $shippingAddressInfo['postalCode'] ?? null,
1650 'state' => $shippingAddressInfo['state'] ?? null,
1651 'country' => $shippingAddressInfo['countryCode'] ?? null,
1652 ];
1653
1654 $shipping = [
1655 'first_name' => $shippingAddressInfo['givenName'] ?? $shippingAddressInfo['phoneticGivenName'] ?? null,
1656 'last_name' => $shippingAddressInfo['familyName'] ?? $shippingAddressInfo['phoneticFamilyName'] ?? null,
1657 'company' => $shippingAddressInfo['company'] ?? null,
1658 'address_1' => $shippingAddressInfo['administrativeArea'] ?? null,
1659 'address_2' => $shippingAddressInfo['subAdministrativeArea'] ?? null,
1660 'city' => $shippingAddressInfo['locality'] ?? null,
1661 'postcode' => $shippingAddressInfo['postalCode'] ?? null,
1662 'state' => $shippingAddressInfo['state'] ?? null,
1663 'country' => $shippingAddressInfo['countryCode'] ?? null,
1664 ];
1665
1666 $order->set_address( $billing, 'billing' );
1667 $order->set_address( $shipping, 'shipping' );
1668 }
1669 $shippingItems = $order->get_items( 'shipping' );
1670 if ( ! empty( $shippingItems ) ) {
1671 foreach ( $shippingItems as $itemId => $item ) {
1672 $order->remove_item( $itemId );
1673 }
1674 }
1675
1676 /* Get list Shipping */
1677 $shippingPackages = WC()->cart->get_shipping_packages();
1678 $countryCode = $shippingAddressInfo['countryCode'] ?? $order->get_shipping_country() ?? '';
1679 $shippingPackages[0]['destination']['country'] = $countryCode;
1680 $calculateShipping = WC()->shipping->calculate_shipping($shippingPackages);
1681 $listShipping = $calculateShipping[0]['rates'] ?? [];
1682 $ratesShipping = [];
1683 if ( $listShipping ) {
1684 $keyFirst = array_key_first($listShipping);
1685 $shippingSelected = new WC_Order_Item_Shipping();
1686 foreach ($listShipping as $key => $method) {
1687 $ratesShipping[$method->get_id()] = [
1688 'method_id' => $method->get_id(),
1689 'method_title' => $method->get_label(),
1690 'method_description' => __( 'Shipping Cost: ' ) . $method->get_cost() . ' ' . get_option('woocommerce_currency'),
1691 'method_price' => $method->get_cost()
1692 ];
1693 if ( ($keyFirst === $key && empty($shippingMethodSelected)) || ($shippingMethodSelected === $key) ) {
1694 $this->helper->set_shipping_item($shippingSelected, $method, $order);
1695 }
1696 }
1697 }
1698 $order->calculate_totals();
1699 $orderTotal = $order->get_total();
1700 $jwt = $this->helper->mgn_update_jwt_address_details(
1701 $orderId,
1702 '',
1703 [],
1704 [],
1705 [],
1706 $orderTotal,
1707 0,
1708 SECURETRADING_APPLE_PAY,
1709 1
1710 );
1711 $result = [
1712 'jwt' => $jwt,
1713 'amount' => number_format($orderTotal, 2),
1714 'rates_shipping' => $ratesShipping
1715 ];
1716 wp_send_json_success($result);
1717 }
1718
1719 /**
1720 * @snippet Update JWT for MyST.
1721 * @sourcecode https://magenest.com/
1722 * @author Minh Hung
1723 */
1724 public function st_moto_api_update_jwt_myst() {
1725 // Verify nonce.
1726 // If nonce is not valid we should exit here.
1727 $nonce = (!empty($_POST['_wpnonce'])) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
1728 if (!empty($_POST) && !wp_verify_nonce($nonce, 'st-api-moto-update-jwt-myst-nonce')) {
1729 echo '['.SECURETRADING_VERSION.'] Invalid Update Address MyST Nonce';
1730 exit();
1731 }
1732
1733 $order_id = (!empty($_POST['order_id'])) ? (int) $_POST['order_id'] : 0;
1734 $moto_save_card = (!empty($_POST['moto_save_card'])) ? (int) $_POST['moto_save_card'] : 0;
1735 $jwt = $this->helper->get_payload_for_moto_webservices($order_id, $moto_save_card);
1736
1737 echo esc_html($jwt);
1738 }
1739
1740 /**
1741 * @snippet Set payment card selected on checkout.
1742 * @sourcecode https://magenest.com/
1743 * @author Minh Hung
1744 */
1745 public function mgn_select_saved_payment_card() {
1746 global $wpdb;
1747
1748 // Set $_GET values.
1749 $get_cid = (!empty($_GET['cardID'])) ? (int) $_GET['cardID'] : null;
1750
1751 // get current user id ( user must be logged in ).
1752 $current_user = wp_get_current_user();
1753 $user_id = (!empty($current_user->ID)) ? $current_user->ID : 0;
1754
1755 // set payment card selected.
1756 if (!empty($user_id) && !empty($get_cid)) {
1757 // set all cards to inactive.
1758 $set_inactive_cards = $wpdb->query(
1759 $wpdb->prepare( "UPDATE {$wpdb->prefix}woocommerce_payment_tokens SET is_default = '0' WHERE user_id = %s", $user_id)
1760 );
1761 // set selected card to active.
1762 $set_active_cards = $wpdb->query(
1763 $wpdb->prepare( "UPDATE {$wpdb->prefix}woocommerce_payment_tokens SET is_default = '1' WHERE user_id = %s AND token_id = %s", $user_id, $get_cid)
1764 );
1765 }
1766 }
1767
1768 /**
1769 * @snippet Reset saved purchase card.
1770 * @sourcecode https://magenest.com/
1771 * @author Minh Hung
1772 */
1773 public function mgn_reset_purchase_card() {
1774 global $wpdb;
1775 global $wp;
1776
1777 // Set $_GET values.
1778 $get_reset = (!empty($_GET['reset'])) ? sanitize_text_field(wp_unslash($_GET['reset'])) : null;
1779 $pay_for_order = (!empty($_GET['pay_for_order'])) ? sanitize_text_field(wp_unslash($_GET['pay_for_order'])) : null;
1780
1781 // Set current payment method
1782 if ( !empty($pay_for_order) ) {
1783 $pay_for_order_method = isset( $_COOKIE['pay_for_order_method'] ) ? $_COOKIE['pay_for_order_method'] : '';
1784 $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
1785 if ( $available_gateways && $pay_for_order_method ) {
1786 foreach ( $available_gateways as $gateway ) {
1787 if ( $gateway->id == $pay_for_order_method ) {
1788 $gateway->chosen = true;
1789 } else {
1790 $gateway->chosen = false;
1791 }
1792 }
1793 }
1794 }
1795
1796 // if reset is required.
1797 if (isset($get_reset)) {
1798 // get current user id ( user must be logged in ).
1799 $current_user = wp_get_current_user();
1800 $user_id = (!empty($current_user->ID)) ? $current_user->ID : 0;
1801
1802 // if we have reset data.
1803 if (!empty($get_reset)) {
1804 $set_inactive_cards = $wpdb->query(
1805 $wpdb->prepare( "UPDATE {$wpdb->prefix}woocommerce_payment_tokens SET is_default = '0' WHERE user_id = %s", $user_id)
1806 );
1807 }
1808
1809 // redirect page.
1810 if ( empty($pay_for_order) ) : ?>
1811 <script>
1812 window.location.href = '<?= esc_url(wc_get_checkout_url()); ?>';
1813 </script>
1814 <?php else :
1815 $order_id = get_query_var('order-pay');
1816 $pay_now_url = wc_get_order($order_id)->get_checkout_payment_url(); ?>
1817 <script>
1818 window.location.href = '<?= $pay_now_url; ?>';
1819 </script>
1820 <?php endif;
1821 }
1822 }
1823
1824 /**
1825 * @snippet Loadding JWT.
1826 * @sourcecode https://magenest.com/
1827 * @author Minh Hung
1828 */
1829 public function mgn_button_after_submit() {
1830 $st_securetrading_api_setting = get_option('woocommerce_securetrading_api_settings');
1831 $st_securetrading_google_pay_setting = get_option('woocommerce_securetrading_google_pay_settings');
1832 $st_securetrading_apple_pay_setting = get_option('woocommerce_securetrading_apple_pay_settings');
1833 $st_securetrading_paypal_setting = get_option('woocommerce_securetrading_paypal_settings');
1834
1835 /* Order Pay */
1836 if ( is_wc_endpoint_url() ) { ?>
1837 <div class="st-card_wapper">
1838 <div class="st-card_form">
1839 <div id="st-card-number" class="st-card-number"></div>
1840 <div id="st-expiration-date" class="st-expiration-date"></div>
1841 <div id="st-security-code" class="st-security-code"></div>
1842 </div>
1843
1844 <div class="st-loading">
1845 <div style="display: inline-block; vertical-align: top;">
1846 <img style="max-width: 25px;" src="<?php echo SECURETRADING_URL.'/assets/img/loading.gif'; ?>" alt="img" />
1847 </div>
1848 <div style="display: inline-block;">
1849 <p>
1850 <?php echo __( 'Loading, please wait...', SECURETRADING_TEXT_DOMAIN ) ?>
1851 </p>
1852 </div>
1853 </div>
1854 </div>
1855 <?php }
1856
1857 /* Google Pay */
1858 if ( !empty($st_securetrading_google_pay_setting) && 'yes' === $st_securetrading_google_pay_setting['enabled'] ) :
1859 if ( ( ! class_exists( 'WC_Subscriptions_Cart' ) ) || ( class_exists( 'WC_Subscriptions_Cart' ) && empty( WC_Subscriptions_Cart::cart_contains_subscription() ) ) ) : ?>
1860 <div class="gpay-inner">
1861 <p class="or-line">
1862 <?php esc_html_e( '- OR -', SECURETRADING_TEXT_DOMAIN ); ?>
1863 </p>
1864 <div class="st-gpay-loading">
1865 <div style="display: inline-block; vertical-align: top;">
1866 <img style="max-width: 25px;" src="<?php echo SECURETRADING_URL.'/assets/img/loading.gif'; ?>" alt="img" />
1867 </div>
1868 <div style="display: inline-block;">
1869 <p style="margin: 0;">
1870 <?php echo __( 'Loading, please wait...', SECURETRADING_TEXT_DOMAIN ) ?>
1871 </p>
1872 </div>
1873 </div>
1874 <button style="display: none;" type="button" class="button alt wp-element-button" name="trust_gpay_checkout_place_order" id="gpay_place_order" data-method="<?php echo SECURETRADING_GOOGLE_PAY; ?>" value="<?php esc_html_e( 'Google Pay', SECURETRADING_TEXT_DOMAIN ); ?>" data-value="<?php esc_html_e( 'Google Pay', SECURETRADING_TEXT_DOMAIN ); ?>">
1875 <?php esc_html_e( 'Google Pay', SECURETRADING_TEXT_DOMAIN ); ?>
1876 <?php echo ( '1' === $st_securetrading_api_setting['testmode'] ) ? '<span class="test-label" style="display: none;">'.__( 'TEST', SECURETRADING_TEXT_DOMAIN ).'</span>' : ''; ?>
1877 </button>
1878 </div>
1879 <?php endif;
1880 endif;
1881
1882 /* Apple Pay */
1883 if ( !empty($st_securetrading_apple_pay_setting) && 'yes' === $st_securetrading_apple_pay_setting['enabled'] ) :
1884 $check_brower = $this->helper->check_brower();
1885 if ( true === $check_brower ) : // Check device
1886 if ( ( ! class_exists( 'WC_Subscriptions_Cart' ) ) || ( class_exists( 'WC_Subscriptions_Cart' ) && empty( WC_Subscriptions_Cart::cart_contains_subscription() ) ) ) : ?>
1887 <div class="apple-inner">
1888 <p class="or-line">
1889 <?php esc_html_e( '- OR -', SECURETRADING_TEXT_DOMAIN ); ?>
1890 </p>
1891 <div class="st-apple-loading">
1892 <div style="display: inline-block; vertical-align: top;">
1893 <img style="max-width: 25px;" src="<?php echo SECURETRADING_URL.'/assets/img/loading.gif'; ?>" alt="img" />
1894 </div>
1895 <div style="display: inline-block;">
1896 <p style="margin: 0;">
1897 <?php echo __( 'Loading, please wait...', SECURETRADING_TEXT_DOMAIN ) ?>
1898 </p>
1899 </div>
1900 </div>
1901 <button type="button" class="button alt wp-element-button" name="trust_apple_checkout_place_order" id="apple_place_order" data-method="<?php echo SECURETRADING_APPLE_PAY; ?>" value="<?php esc_html_e( 'Apple Pay', SECURETRADING_TEXT_DOMAIN ); ?>" data-value="<?php esc_html_e( 'Apple Pay', SECURETRADING_TEXT_DOMAIN ); ?>">
1902 <?php esc_html_e( 'Apple Pay', SECURETRADING_TEXT_DOMAIN ); ?>
1903 <?php echo ( '1' === $st_securetrading_api_setting['testmode'] ) ? '<span class="test-label" style="display: none;">'.__( 'TEST', SECURETRADING_TEXT_DOMAIN ).'</span>' : ''; ?>
1904 </button>
1905 </div>
1906 <?php endif;
1907 endif;
1908 endif;
1909
1910 /* PayPal */
1911 if ( !empty($st_securetrading_paypal_setting) && 'yes' === $st_securetrading_paypal_setting['enabled'] ) :
1912 if ( ( ! class_exists( 'WC_Subscriptions_Cart' ) ) || ( class_exists( 'WC_Subscriptions_Cart' ) && empty( WC_Subscriptions_Cart::cart_contains_subscription() ) ) ) : ?>
1913 <div class="paypal-inner">
1914 <p class="or-line">
1915 <?php esc_html_e( '- OR -', SECURETRADING_TEXT_DOMAIN ); ?>
1916 </p>
1917 <button type="submit" class="button alt wp-element-button paypal-buy-now-button" name="trust_paypal_checkout_place_order" id="paypal_place_order" data-method="<?php echo SECURETRADING_PAYPAL; ?>" value="<?php esc_html_e( 'PayPal', SECURETRADING_TEXT_DOMAIN ); ?>" data-value="<?php esc_html_e( 'PayPal', SECURETRADING_TEXT_DOMAIN ); ?>">
1918 <svg aria-label="PayPal" xmlns="http://www.w3.org/2000/svg" width="70" height="33" viewBox="34.417 0 90 33">
1919 <path fill="#253B80" d="M46.211 6.749h-6.839a.95.95 0 0 0-.939.802l-2.766 17.537a.57.57 0 0 0 .564.658h3.265a.95.95 0 0 0 .939-.803l.746-4.73a.95.95 0 0 1 .938-.803h2.165c4.505 0 7.105-2.18 7.784-6.5.306-1.89.013-3.375-.872-4.415-.972-1.142-2.696-1.746-4.985-1.746zM47 13.154c-.374 2.454-2.249 2.454-4.062 2.454h-1.032l.724-4.583a.57.57 0 0 1 .563-.481h.473c1.235 0 2.4 0 3.002.704.359.42.469 1.044.332 1.906zM66.654 13.075h-3.275a.57.57 0 0 0-.563.481l-.146.916-.229-.332c-.709-1.029-2.29-1.373-3.868-1.373-3.619 0-6.71 2.741-7.312 6.586-.313 1.918.132 3.752 1.22 5.03.998 1.177 2.426 1.666 4.125 1.666 2.916 0 4.533-1.875 4.533-1.875l-.146.91a.57.57 0 0 0 .562.66h2.95a.95.95 0 0 0 .939-.804l1.77-11.208a.566.566 0 0 0-.56-.657zm-4.565 6.374c-.316 1.871-1.801 3.127-3.695 3.127-.951 0-1.711-.305-2.199-.883-.484-.574-.668-1.392-.514-2.301.295-1.855 1.805-3.152 3.67-3.152.93 0 1.686.309 2.184.892.499.589.697 1.411.554 2.317zM84.096 13.075h-3.291a.955.955 0 0 0-.787.417l-4.539 6.686-1.924-6.425a.953.953 0 0 0-.912-.678H69.41a.57.57 0 0 0-.541.754l3.625 10.638-3.408 4.811a.57.57 0 0 0 .465.9h3.287a.949.949 0 0 0 .781-.408l10.946-15.8a.57.57 0 0 0-.469-.895z"></path>
1920 <path fill="#179BD7" d="M94.992 6.749h-6.84a.95.95 0 0 0-.938.802l-2.767 17.537a.57.57 0 0 0 .563.658h3.51a.665.665 0 0 0 .656-.563l.785-4.971a.95.95 0 0 1 .938-.803h2.164c4.506 0 7.105-2.18 7.785-6.5.307-1.89.012-3.375-.873-4.415-.971-1.141-2.694-1.745-4.983-1.745zm.789 6.405c-.373 2.454-2.248 2.454-4.063 2.454h-1.031l.726-4.583a.567.567 0 0 1 .562-.481h.474c1.233 0 2.399 0 3.002.704.358.42.467 1.044.33 1.906zM115.434 13.075h-3.272a.566.566 0 0 0-.562.481l-.146.916-.229-.332c-.709-1.029-2.289-1.373-3.867-1.373-3.619 0-6.709 2.741-7.312 6.586-.312 1.918.131 3.752 1.22 5.03 1 1.177 2.426 1.666 4.125 1.666 2.916 0 4.532-1.875 4.532-1.875l-.146.91a.57.57 0 0 0 .563.66h2.949a.95.95 0 0 0 .938-.804l1.771-11.208a.57.57 0 0 0-.564-.657zm-4.565 6.374c-.314 1.871-1.801 3.127-3.695 3.127-.949 0-1.711-.305-2.199-.883-.483-.574-.666-1.392-.514-2.301.297-1.855 1.805-3.152 3.67-3.152.93 0 1.686.309 2.184.892.501.589.699 1.411.554 2.317zM119.295 7.23l-2.807 17.858a.569.569 0 0 0 .562.658h2.822c.469 0 .866-.34.938-.803l2.769-17.536a.57.57 0 0 0-.562-.659h-3.16a.571.571 0 0 0-.562.482z"></path>
1921 </svg>
1922 <?php echo ( '1' === $st_securetrading_api_setting['testmode'] ) ? '<span class="test-label">'.__( 'TEST', SECURETRADING_TEXT_DOMAIN ).'</span>' : ''; ?>
1923 </button>
1924 </div>
1925 <?php endif;
1926 endif;
1927 }
1928
1929 /**
1930 * Refund puchase.
1931 *
1932 * @param mixed $methods Payment methods.
1933 *
1934 * @return mixed
1935 */
1936 public function mgn_migrate_refund_purchase() {
1937 // Verify nonce.
1938 // If nonce is not valid we should exit here.
1939 $nonce = (!empty($_POST['_wpnonce'])) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
1940 if (!empty($_POST) && !wp_verify_nonce($nonce, 'refund-nonce')) {
1941 echo 'Invalid Refund Nonce';
1942
1943 return;
1944 }
1945
1946 // Get logged in users roles.
1947 $user = wp_get_current_user();
1948 $roles = (array) $user->roles;
1949
1950 // If we dont have any user roles, stop here.
1951 if (empty($user->roles)) {
1952 echo 'No User Roles';
1953
1954 return;
1955 } else { // else, if this user roles include customer we dont need to go any further.
1956 foreach ($roles as $role) {
1957 if ('customer' === $role) {
1958 echo 'Invalid Role';
1959
1960 return;
1961 }
1962 }
1963 }
1964
1965 // Set $_POST values.
1966 $post_baseamount = (!empty($_POST['baseamount'])) ? sanitize_text_field(wp_unslash($_POST['baseamount'])) : null;
1967 $post_parenttransactionreference = (!empty($_POST['parenttransactionreference'])) ? sanitize_text_field(wp_unslash($_POST['parenttransactionreference'])) : null;
1968 $post_orderid = (!empty($_POST['orderid'])) ? (int) $_POST['orderid'] : null;
1969
1970 // get logged in userid.
1971 $userid = get_current_user_id();
1972 if (!$userid) {
1973 return;
1974 }
1975
1976 // if refund is required.
1977 if (isset($post_baseamount)) {
1978 // get tp gateway settings.
1979 $st_api_setting = get_option('woocommerce_securetrading_api_settings');
1980
1981 // get purchase details.
1982 $userpwd = $st_api_setting['webservices_username'].':'.$st_api_setting['webservices_password'];
1983 $alias = $st_api_setting['webservices_username'];
1984 $sitereference = $st_api_setting['site_reference'];
1985 $platform = $st_api_setting['platform'];
1986
1987 $parenttransactionreference = $post_parenttransactionreference;
1988 $baseamount = round($post_baseamount, 0);
1989 $orderreference = $post_orderid;
1990
1991 // Issue Refund.
1992 $args = [
1993 'headers' => [
1994 'Authorization' => 'Basic '.base64_encode($userpwd),
1995 ],
1996 'body' => '{
1997 "alias":"'.$alias.'",
1998 "version":"1.0",
1999 "request":[{
2000 "requesttypedescriptions":["REFUND"],
2001 "sitereference":"'.$sitereference.'",
2002 "parenttransactionreference":"'.$parenttransactionreference.'",
2003 "baseamount":"'.$baseamount.'",
2004 "orderreference":"'.$orderreference.'"
2005 }]
2006 }',
2007 ];
2008 if ( 'eu' === $platform ) {
2009 $response = wp_remote_post(SECURE_TRADING_EU_WEBSERVICES_JSON, $args);
2010 } elseif ( 'us' === $platform ) {
2011 $response = wp_remote_post(SECURE_TRADING_US_WEBSERVICES_JSON, $args);
2012 }
2013 $response_body = wp_remote_retrieve_body($response);
2014
2015 // check if the response states it's an unauthorised action.
2016 $pos = strpos($response_body, 'Unauthorized');
2017 if (false !== $pos) {
2018 print_r($response_body);
2019 exit();
2020 }
2021
2022 // check if result is error.
2023 $json = json_decode($response_body, true);
2024 if ('0' !== $json['response'][0]['errorcode']) {
2025 // return error message.
2026 print_r($json['response'][0]['errormessage']);
2027 exit();
2028 }
2029
2030 // if result is authorised.
2031 if (false === strpos($response_body, 'Unauthorized')) {
2032 // add refund message to orders > edit order > order notes section in admin area.
2033 $order = wc_get_order($post_orderid);
2034 if (is_object($order)) {
2035 $total = $post_baseamount / 100;
2036 $order->add_order_note('Trust Payments Refund: '.get_woocommerce_currency_symbol().''.number_format($total, 2, '.', '') );
2037 }
2038 }
2039
2040 // return result details.
2041 print_r($response_body);
2042 } else {
2043 // No base amount value has been set.
2044 print_r('NoBaseAmountValue');
2045 }
2046 }
2047
2048 /**
2049 * @snippet Query order not is method tp_gateway
2050 * @sourcecode https://magenest.com/
2051 * @author Minh Hung
2052 */
2053 public function excerpt_tp_gateway() {
2054 $not_tp_gateway = array(
2055 'post_type' => 'shop_order',
2056 'fields' => 'ids',
2057 'nopaging' => true,
2058 'post_status' => 'any',
2059 'posts_per_page' => -1,
2060 'meta_query' => array(
2061 'relation' => 'OR',
2062 array(
2063 'key' => '_payment_method',
2064 'value' => 'tp_gateway',
2065 'compare' => '!=',
2066 ),
2067 array(
2068 'key' => '_payment_method',
2069 'compare' => 'NOT EXISTS' // this should work...
2070 ),
2071 array(
2072 'key' => '_tp_transaction_reference',
2073 'compare' => 'NOT EXISTS' // this should work...
2074 ),
2075 )
2076 );
2077
2078 return get_posts( $not_tp_gateway );
2079 }
2080
2081 /**
2082 * @snippet Migrate grid ST Transactions
2083 * @sourcecode https://magenest.com/
2084 * @author Minh Hung
2085 */
2086 public function mgn_migrate_st_transactions($query) {
2087 $post_type = 'st_transaction';
2088
2089 if( ! is_admin() )
2090 return;
2091
2092 if ( array_key_exists('post_type', (array) $query->query ) && $query->query['post_type'] != $post_type )
2093 return;
2094
2095 $query->set( 'post_type', array( 'st_transaction', 'shop_order' ) );
2096 $query->set( 'post_status', 'any' );
2097 $query->set( 'post__not_in', $this->excerpt_tp_gateway() );
2098
2099 return $query;
2100 }
2101
2102 /**
2103 * @snippet Migrate detail Transactions
2104 * @sourcecode https://magenest.com/
2105 * @author Minh Hung
2106 */
2107 public function mgn_migrate_order_detail() {
2108 add_dashboard_page(
2109 __( 'Trust Payments Transactions', SECURETRADING_TEXT_DOMAIN ),
2110 __( 'Trust Payments Transactions', SECURETRADING_TEXT_DOMAIN ),
2111 'manage_options',
2112 'st-transaction-detail',
2113 array( __CLASS__, 'mgn_migrate_st_transaction' )
2114 );
2115 }
2116
2117 /**
2118 * Form page handler checks is there some data posted and tries to save it
2119 * Also it renders basic wrapper in which we are callin meta box render
2120 */
2121 public function mgn_migrate_st_transaction($item) {
2122 add_meta_box('migrate_data_order_detail', __( 'Trust Payments transaction data', SECURETRADING_TEXT_DOMAIN ), array( __CLASS__, 'mgn_migrate_data_order_detail' ), 'st-transaction-detail', 'normal', 'default'); ?>
2123 <div class="wrap">
2124 <h1 class="wp-heading-inline">
2125 <?php _e('Trust Payments Transactions', SECURETRADING_TEXT_DOMAIN); ?>
2126 </h1>
2127 <div class="metabox-holder" id="poststuff">
2128 <div id="post-body">
2129 <div id="post-body-content">
2130 <?php do_meta_boxes('st-transaction-detail', 'normal', $item); ?>
2131 </div>
2132 </div>
2133 </div>
2134 </div>
2135 <?php }
2136
2137 /**
2138 * This function renders our custom meta box
2139 * $item is row
2140 *
2141 */
2142 public function mgn_migrate_data_order_detail() {
2143 $template_path = SECURETRADING_PATH . 'templates/';
2144 include $template_path. 'transaction-detail.php';
2145 }
2146
2147 /**
2148 * Create payment
2149 * @throws Exception
2150 */
2151 public function mgn_create_payment() {
2152 try {
2153 $st_iframe_setting = get_option('woocommerce_securetrading_iframe_settings');
2154 $orderId = (int)WC()->session->get('mgn_order_awaiting');
2155 if (empty($orderId)) {
2156 $orderId = (int)WC()->session->get('order_awaiting_payment');
2157 }
2158
2159 if (empty($orderId)) {
2160 $orderId = (int)WC()->session->get('tp_pay_for_order_awaiting');
2161 }
2162
2163 /* MOTO iframe */
2164 if (isset($_COOKIE['order_moto'])) {
2165 $url = WC()->api_request_url('trust-moto-payments');
2166 $st_iframe_setting = get_option('woocommerce_securetrading_iframe_settings');
2167 $iFrame_width = $st_iframe_setting['width'] != null ? $st_iframe_setting['width'] : '100%';
2168 $iFrame_height = $st_iframe_setting['height'] != null ? $st_iframe_setting['height'] : '600px';
2169 get_header(); ?>
2170 <iframe width="<?php echo esc_html($iFrame_width); ?>"
2171 height="<?php echo esc_html($iFrame_height); ?>"
2172 src="<?php echo esc_html($url); ?>"
2173 frameborder="0"
2174 allowtransparency=="true">
2175 </iframe>
2176 <?php get_footer();
2177 die;
2178 }
2179
2180 if (empty($orderId)) {
2181 wp_redirect(wc_get_cart_url());
2182 die;
2183 }
2184
2185 if ( 'redirect' === $st_iframe_setting['useiframe'] ) {
2186 $params = $this->helper->prepare_required_fields($orderId);
2187 } elseif ( 'iframe' === $st_iframe_setting['useiframe'] ) {
2188 $url = WC()->api_request_url('trust-iframe');
2189 }
2190
2191 include SECURETRADING_PATH . '/templates/create-payment.php';
2192 die;
2193 } catch (Exception $e) {
2194 wc_add_notice(__('Trust Payments payment error.', SECURETRADING_TEXT_DOMAIN), 'error');
2195 wp_redirect(wc_get_checkout_url());
2196 die;
2197 }
2198 }
2199
2200 /**
2201 * Create MOTO payment
2202 * @throws Exception
2203 */
2204 public function mgn_create_moto_payment() {
2205 try {
2206 if (isset($_COOKIE['order_moto'])) {
2207 $orderId = $_COOKIE['order_moto'];
2208 setcookie('order_moto', '', time() - 3600, "/");
2209 }
2210
2211 if (empty($orderId)) {
2212 wp_redirect(wc_get_cart_url());
2213 die;
2214 }
2215
2216 $params = $this->helper->prepare_required_fields($orderId, 'admin');
2217
2218 get_header();
2219 include SECURETRADING_PATH . '/templates/create-iframe.php';
2220 get_footer();
2221 die;
2222 } catch (Exception $e) {
2223 wc_add_notice(__('Trust Payments payment error.', SECURETRADING_TEXT_DOMAIN), 'error');
2224 wp_redirect(wc_get_checkout_url());
2225 die;
2226 }
2227 }
2228
2229 /**
2230 * Create payment
2231 * @throws Exception
2232 */
2233 public function mgn_iframe_payment() {
2234 try {
2235 $orderId = (int)WC()->session->get('mgn_order_awaiting');
2236 if (empty($orderId)) {
2237 $orderId = (int)WC()->session->get('order_awaiting_payment');
2238 }
2239
2240 if (empty($orderId)) {
2241 wp_redirect(wc_get_cart_url());
2242 die;
2243 }
2244
2245 $params = $this->helper->prepare_required_fields($orderId);
2246
2247 get_header();
2248 include SECURETRADING_PATH . '/templates/create-iframe.php';
2249 get_footer();
2250 die;
2251 } catch (Exception $e) {
2252 wc_add_notice(__('Trust Payments payment error.', SECURETRADING_TEXT_DOMAIN), 'error');
2253 wp_redirect(wc_get_checkout_url());
2254 die;
2255 }
2256 }
2257
2258 /**
2259 * Confirm payment
2260 * @throws Exception
2261 */
2262 public function mgn_confirm_payment() {
2263 try {
2264 $params = $this->helper->get_params();
2265 $st_iframe_setting = get_option('woocommerce_securetrading_iframe_settings');
2266
2267 $orderId = (int)WC()->session->get('order_awaiting_payment');
2268
2269 if (empty($orderId) && !empty($params['orderreference'])) {
2270 $orderreference = str_replace( '#', '', $params['orderreference'] );
2271 $orderId = (int)$orderreference;
2272 }
2273
2274 if (empty($orderId)) {
2275 $logger = wc_get_logger();
2276 $logger->debug(
2277 '['.SECURETRADING_VERSION.' - I tried hard, but no order was found for confirmation.',
2278 ['source' => 'trust_payments_subscription-log']
2279 );
2280 }
2281
2282 if (!empty($orderId)) {
2283 $order = wc_get_order($orderId);
2284 if ( 'yes' === $st_iframe_setting['site_notification'] ) {
2285 $error_code = $params['errorcode'];
2286 } else {
2287 $transactionreference = $params['transactionreference'];
2288 $payment_method = $order->get_payment_method();
2289 $payment_confirmed = $this->helper->mgn_confirm_post_order_data($transactionreference, $payment_method);
2290 if (empty($payment_confirmed) || true !== $payment_confirmed['success']) {
2291 $message = __('Order ID not comfirm.', SECURETRADING_TEXT_DOMAIN);
2292 $url = wc_get_checkout_url();
2293 wc_add_notice( $message,'error' );
2294 echo "<script>document.addEventListener('DOMContentLoaded', function(){ window.top.location.href = '".$url."'; }); </script>";
2295 die;
2296 } else {
2297 $raw_data = (array) $payment_confirmed['response'][0];
2298 $this->helper->create_transaction($raw_data);
2299 $this->helper->process_response_api($orderId, $raw_data, $payment_method);
2300 }
2301 }
2302 $is_moto = get_post_meta( $orderId, '_' . SECURETRADING_ID . '_moto_use_hpp', true );
2303 if( '70000' == $error_code ) {
2304 $url = wc_get_checkout_url();
2305 wc_add_notice( __('Decline your payment. Please try again!', SECURETRADING_TEXT_DOMAIN),'error' );
2306 } else {
2307 $url = $order->get_checkout_order_received_url();
2308 }
2309
2310 if ( !empty($is_moto) ) {
2311 $url = admin_url( 'post.php?post='.$orderId.'&action=edit');
2312 }
2313 }
2314
2315 echo "<script>document.addEventListener('DOMContentLoaded', function(){ window.top.location.href = '".$url."'; }); </script>";
2316 die;
2317 } catch (Exception $e) {
2318 wc_add_notice(__('Trust Payments payment error.', SECURETRADING_TEXT_DOMAIN), 'error');
2319 echo "<script>document.addEventListener('DOMContentLoaded', function(){ window.top.location.href = '".wc_get_checkout_url()."'; }); </script>";
2320 die;
2321 }
2322 }
2323
2324 /**
2325 * Remove checkout ZIP code validation
2326 *
2327 * @author Minh Hung
2328 * @link https://magenest.com
2329 */
2330 public function mgn_gpay_no_zip_validation( $fields ) {
2331 if ( isset($_POST['payment_method']) && ( SECURETRADING_GOOGLE_PAY === $_POST['payment_method'] || SECURETRADING_APPLE_PAY === $_POST['payment_method'] ) ) {
2332 // billing postcode
2333 unset( $fields[ 'billing' ][ 'billing_postcode' ][ 'validate' ] );
2334 // shipping postcode
2335 unset( $fields[ 'shipping' ][ 'shipping_postcode' ][ 'validate' ] );
2336 }
2337
2338 return $fields;
2339 }
2340
2341 /**
2342 * Provider data checkout
2343 *
2344 * @author Minh Hung
2345 * @link https://magenest.com
2346 */
2347 public function tp_refresh_jwt($post_data) {
2348 $payment_method = WC()->session->get('chosen_payment_method');
2349 $output = esc_html($this->helper->mgn_update_jwt_address_details( '0', '', [], [], 0, 0, 0, $payment_method, 0 ));
2350 $post_data['total'] = (!empty(WC()->cart->get_total())) ? round(WC()->cart->get_total('raw')) : 0;
2351 $post_data['jwt'] = $output;
2352 $post_data['needs_shipping'] = WC()->cart->needs_shipping();
2353 $post_data['sub_total'] = number_format(WC()->cart->get_subtotal(), 2);
2354
2355 return $post_data;
2356 }
2357
2358 /**
2359 * Modify Apple Pay request
2360 *
2361 * @author Minh Hung
2362 * @link https://magenest.com
2363 */
2364 public function tp_checkout_posted_data($data) {
2365 $apple_pay_method = $data['payment_method'];
2366 if ( $apple_pay_method === SECURETRADING_APPLE_PAY ) {
2367 if ( array_key_exists( 'shipping_first_name', $data ) ) {
2368 $data['shipping_first_name'] = ( isset( $_POST['shipping_first_name'] ) && !empty($_POST['shipping_first_name']) ) ? $_POST['shipping_first_name'] : '';
2369 }
2370
2371 if ( array_key_exists( 'shipping_last_name', $data ) ) {
2372 $data['shipping_last_name'] = ( isset( $_POST['shipping_last_name'] ) && !empty($_POST['shipping_last_name']) ) ? $_POST['shipping_last_name'] : '';
2373 }
2374
2375 if ( array_key_exists( 'shipping_company ', $data ) ) {
2376 $data['shipping_company '] = ( isset( $_POST['shipping_company '] ) && !empty($_POST['shipping_company ']) ) ? $_POST['shipping_company '] : '';
2377 }
2378
2379 if ( array_key_exists( 'shipping_country', $data ) ) {
2380 $data['shipping_country'] = ( isset( $_POST['shipping_country'] ) && !empty($_POST['shipping_country']) ) ? $_POST['shipping_country'] : '';
2381 }
2382
2383 if ( array_key_exists( 'shipping_address_1', $data ) ) {
2384 $data['shipping_address_1'] = ( isset( $_POST['shipping_address_1'] ) && !empty($_POST['shipping_address_1']) ) ? $_POST['shipping_address_1'] : '';
2385 }
2386
2387 if ( array_key_exists( 'shipping_address_2', $data ) ) {
2388 $data['shipping_address_2'] = ( isset( $_POST['shipping_address_2'] ) && !empty($_POST['shipping_address_2']) ) ? $_POST['shipping_address_2'] : '';
2389 }
2390
2391 if ( array_key_exists( 'shipping_city', $data ) ) {
2392 $data['shipping_city'] = ( isset( $_POST['shipping_city'] ) && !empty($_POST['shipping_city']) ) ? $_POST['shipping_city'] : '';
2393 }
2394
2395 if ( array_key_exists( 'shipping_state', $data ) ) {
2396 $data['shipping_state'] = ( isset( $_POST['shipping_state'] ) && !empty($_POST['shipping_state']) ) ? $_POST['shipping_state'] : '';
2397 }
2398
2399 if ( array_key_exists( 'shipping_postcode', $data ) ) {
2400 $data['shipping_postcode'] = ( isset( $_POST['shipping_postcode'] ) && !empty($_POST['shipping_postcode']) ) ? $_POST['shipping_postcode'] : '';
2401 }
2402 }
2403
2404 return $data;
2405 }
2406
2407 /**
2408 * Add custom meta box.
2409 *
2410 * @return void
2411 */
2412 public function tp_order_details() {
2413 $orderId = intval($_GET['post'] ?? $_GET['id'] ?? 0);
2414 if ( empty($orderId) ) {
2415 return;
2416 }
2417
2418 $order = wc_get_order($orderId);
2419 if ( ! $order ) {
2420 return;
2421 }
2422
2423 $paymentMethod = $order->get_payment_method();
2424 $allowMethod = [
2425 SECURETRADING_ID,
2426 SECURETRADING_API_ID,
2427 SECURETRADING_GOOGLE_PAY,
2428 SECURETRADING_APPLE_PAY,
2429 SECURETRADING_PAYPAL,
2430 SECURETRADING_A2A
2431 ];
2432 if ( ! in_array( $paymentMethod, $allowMethod ) ) {
2433 return;
2434 }
2435
2436 add_meta_box(
2437 'tp-order-details',
2438 __( 'Trust Payments Transactions', SECURETRADING_TEXT_DOMAIN ),
2439 array( $this, 'tp_order_meta_box_callback' ),
2440 'woocommerce_page_wc-orders',
2441 'side',
2442 'high'
2443 );
2444 }
2445
2446 /**
2447 * Callback function for custom meta box.
2448 *
2449 * @param object $post Post object.
2450 *
2451 * @return void
2452 */
2453 public function tp_order_meta_box_callback($post) {
2454 $orderId = $post->ID;
2455 $order = wc_get_order($orderId);
2456 $transactionId = get_post_meta($orderId, '_transaction_id', true) ?: $order->get_meta('_transaction_id');
2457 if (empty($transactionId)) {
2458 echo '<p style="margin: 0;"><b>' . __( 'Not found Data', SECURETRADING_TEXT_DOMAIN ) . '</b></p>';
2459 return;
2460 }
2461 $createdVia = get_post_meta( $orderId, '_created_via', true);
2462 $paymentMethod = $order->get_payment_method();
2463 echo '<p style="margin: 1em 0 0;"><b>' . esc_html(__('Transaction Reference: ')) . '</b>' . esc_html($transactionId) . '</p>';
2464 if ( !empty( $transactionId ) && 'subscription' !== $createdVia ) {
2465 $dataTransactionSubscription = [
2466 '_' . $paymentMethod . '_parent_transaction_reference' => __('Parent Transaction Reference: '),
2467 '_securetrading_notification_reference' => __('Notification Reference: '),
2468 '_' . $paymentMethod . '_card_number' => __('Card Number: '),
2469 '_' . $paymentMethod . '_card_type' => __('Card Type: '),
2470 '_' . $paymentMethod . '_card_month' => __('Expiry Month: '),
2471 '_' . $paymentMethod . '_card_year' => __('Expiry Year: '),
2472 '_' . $paymentMethod . '_authcode' => __('Authcode: '),
2473 '_' . $paymentMethod . '_errorcode' => __('Errorcode: '),
2474 '_' . $paymentMethod . '_card_issuer' => __('Card Issuer: '),
2475 '_' . $paymentMethod . '_issuercountryiso2a' => __('Card Issuer Country: '),
2476 '_' . $paymentMethod . '_save_card' => __('aved CC: '),
2477 '_' . $paymentMethod . '_securityresponseaddress' => __('AVS Response Code first line of address: '),
2478 '_' . $paymentMethod . '_securityresponsepostcode' => __('AVS Response Code postcode: '),
2479 '_' . $paymentMethod . '_securityresponsesecuritycode' => __('CVV2 Response Code: '),
2480 '_' . $paymentMethod . '_enrolled' => __('3D secure enrolled status: '),
2481 '_' . $paymentMethod . '_status' => __('3D secure status: '),
2482 '_' . $paymentMethod . '_message' => __('Message: '),
2483 '_' . $paymentMethod . '_orderreference' => __('Order Reference: '),
2484 '_' . $paymentMethod . '_payment_type_description' => __('Payment Type Description: '),
2485 '_' . $paymentMethod . '_account_type_description' => __('Account Type Description: '),
2486 '_' . $paymentMethod . '_settle_status' => __('Settle Status: '),
2487 '_' . $paymentMethod . '_acquirerresponsemessage' => __('Acquirer Transaction Reference: '),
2488 '_' . $paymentMethod . '_transactionstartedtimestamp' => __('Transaction Started Time Stamp: '),
2489 '_' . $paymentMethod . '_settle_status' => __('Settle Status: '),
2490 '_' . $paymentMethod . '_settleduedate' => __('Settle Due Date: '),
2491 '_' . $paymentMethod . '_settledtimestamp' => __('Settle Time Stamp: '),
2492 '_' . $paymentMethod . '_operator_name' => __('Operator Name: ')
2493 ];
2494 }
2495
2496 if ( !empty( $transactionId ) && 'subscription' === $createdVia ) {
2497 $dataTransactionSubscription = [
2498 '_' . $paymentMethod . '_authcode' => __('Authcode: '),
2499 '_' . $paymentMethod . '_parenttransactionreference' => __('Operator Name: '),
2500 '_' . $paymentMethod . '_operator_name' => __('Parent Transaction Reference: '),
2501 '_' . $paymentMethod . '_errorcode' => __('Errorcode: '),
2502 '_' . $paymentMethod . '_issuer' => __('Card Issuer: '),
2503 '_' . $paymentMethod . '_aissuercountryiso2a' => __('Card Issuer Country: '),
2504 '_' . $paymentMethod . '_maskedpan' => __('Card Number: '),
2505 '_' . $paymentMethod . '_paymenttypedescription' => __('Card Type: ')
2506 ];
2507 }
2508
2509 foreach ( $dataTransactionSubscription as $key => $item ) {
2510 if ( $order->get_meta($key) ) {
2511 if (
2512 '_' . $paymentMethod . '_securityresponseaddress' === $key ||
2513 '_' . $paymentMethod . '_securityresponsepostcode' === $key
2514 ) {
2515 echo '<p style="margin: 0;"><b>' .esc_html($item) . '</b>'. esc_html($this->helper->convert_Account_Check( $order->get_meta($key) )) .'</p>';
2516 } else {
2517 echo '<p style="margin: 0;"><b>' .esc_html($item) . '</b>'. esc_html( $order->get_meta($key) ) .'</p>';
2518 }
2519 }
2520 }
2521
2522 if ( $paymentMethod === SECURETRADING_PAYPAL ) {
2523 $dataTransactionPayPal = [
2524 '_securetrading_paypal_parenttransactionreference' => __('Parent Transaction Reference: '),
2525 '_securetrading_paypal_billingemail' => __('Email: '),
2526 '_securetrading_paypal_billingfirstname' => __('First Name: '),
2527 '_securetrading_paypal_billinglastname' => __('Last Name: '),
2528 '_securetrading_paypal_customerlastname' => __('Customer Lastname: '),
2529 '_securetrading_paypal_customerpostcode' => __('Customer Postcode: '),
2530 '_securetrading_paypal_customerpremise' => __('Customer Premise: '),
2531 '_securetrading_paypal_customertown' => __('Customer Town: '),
2532 '_securetrading_paypal_errormessage' => __('Error Message: '),
2533 '_securetrading_paypal_paypaladdressstatus' => __('PayPal Address Status: '),
2534 '_securetrading_paypal_paypalpayerid' => __('PayPal Payerid: '),
2535 '_securetrading_paypal_paypalpayerstatus' => __('PayPal Payerid Status: ')
2536 ];
2537
2538 foreach ($dataTransactionPayPal as $key => $item) {
2539 $metaValue = get_post_meta($orderId, $key, true);
2540 if (!empty($metaValue)) {
2541 echo '<p style="margin: 0;"><b>' . esc_html($item) . '</b> ' . esc_html($metaValue) . '</p>';
2542 }
2543 }
2544 }
2545 }
2546
2547 /**
2548 * Pay for Order.
2549 *
2550 * @return void
2551 */
2552 public function tp_pay_for_order() {
2553 // Verify nonce.
2554 check_ajax_referer( 'tp_oder_pay_create_nonce', 'tp_oder_pay_nonce' );
2555
2556 $orderId = (!empty($_POST['order_id'])) ? $_POST['order_id'] : '';
2557 $order = wc_get_order($orderId);
2558 $paymentMethod = (!empty($_POST['method'])) ? $_POST['method'] : '';
2559 $order->set_payment_method($paymentMethod);
2560 $order->save();
2561 WC()->session->set( 'tp_pay_for_order_awaiting', $orderId );
2562 $endpoint = WC()->api_request_url('trust-payments');
2563 $result = [
2564 'url' => $endpoint
2565 ];
2566 wp_send_json_success($result);
2567 }
2568 }
2569 $GLOBALS['securetrading'] = WC_SecureTrading_Main::getInstance();