Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/tilopay/assets/blocks/frontend/blocks.asset.php
+++ b/tilopay/assets/blocks/frontend/blocks.asset.php
@@ -1 +1 @@
-<?php return array('dependencies' => array('react', 'wc-blocks-checkout', 'wc-blocks-registry', 'wc-settings', 'wp-data', 'wp-html-entities', 'wp-i18n'), 'version' => 'e201e123b0ac45a54280');
+<?php return array('dependencies' => array('react', 'wc-blocks-checkout', 'wc-blocks-registry', 'wc-settings', 'wp-data', 'wp-html-entities', 'wp-i18n'), 'version' => '983ec0b60ff5e1afeff3');
--- a/tilopay/includes/TilopayHelper.php
+++ b/tilopay/includes/TilopayHelper.php
@@ -20,11 +20,10 @@
{
$allowed_hosts[] = 'tilopay.com';
$allowed_hosts[] = 'app.tilopay.com';
- $allowed_hosts[] = 'staging--incredible-melomakarona-d1c124.netlify.app';
- $allowed_hosts[] = 'tilopay-staging-kb4ui2z5cq-uc.a.run.app';
$allowed_hosts[] = 'securepayment.tilopay.com';
$allowed_hosts[] = 'secure.tilopay.com';
$allowed_hosts[] = 'staging.tilopay.com';
+ $allowed_hosts[] = 'develop.tilopay.com';
return $allowed_hosts;
}
@@ -68,7 +67,15 @@
if (isset($_GET['message_error'])) {
$error_msg = sanitize_text_field(wp_unslash($_GET['message_error']));
$tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', message_error query params', 'info');
- TilopayConfig::tilopay_show_block_notices('error', 'Error: ' . esc_html($error_msg));
+ // Do not print HTML on 'init' (it lands before the page header and duplicates the notice).
+ // Block checkout: the notice is rendered by block-tilopay-checkout.js as plain text.
+ // Classic checkout: queue a WooCommerce notice that is printed in the checkout notices area.
+ if (!TilopayConfig::tilopay_check_is_checkout_block() && function_exists('wc_add_notice') && function_exists('WC') && WC()->session) {
+ $error_msg = WCTilopay::tpay_clean_note_text($error_msg);
+ if ('' !== $error_msg && !wc_has_notice('Error: ' . $error_msg, 'error')) {
+ wc_add_notice('Error: ' . $error_msg, 'error');
+ }
+ }
return;
}
@@ -101,9 +108,12 @@
$request_order_id = (isset($_GET['order'])) ? sanitize_text_field(wp_unslash($_GET['order'])) : '';
$request_code_payment = (isset($_GET['code'])) ? sanitize_text_field(wp_unslash($_GET['code'])) : '';
$request_auth_code_payment = (isset($_GET['auth'])) ? sanitize_text_field(wp_unslash($_GET['auth'])) : '';
- $request_description = (isset($_GET['description'])) ? sanitize_text_field(wp_unslash($_GET['description'])) : __('Unknown', 'tilopay');
+ // The description is attacker-controllable: strip any markup and HTML-sensitive characters
+ $request_description = (isset($_GET['description'])) ? WCTilopay::tpay_clean_note_text(wp_unslash($_GET['description'])) : '';
+ $request_description = ('' !== $request_description) ? $request_description : __('Unknown', 'tilopay');
$request_token_card = (isset($_GET['crd'])) ? sanitize_text_field(wp_unslash($_GET['crd'])) : '';
$selected_method = (isset($_GET['selected_method'])) ? sanitize_text_field(wp_unslash($_GET['selected_method'])) : '';
+ $request_return_data = (isset($_GET['returnData']) && is_string($_GET['returnData'])) ? sanitize_text_field(wp_unslash($_GET['returnData'])) : '';
if (!empty($request_order_id)) {
@@ -124,8 +134,22 @@
$order = wc_get_order($request_order_id); //working with notice php
if ($order) {
+ // Only handle returns for orders paid with Tilopay
+ if ($tilopay_getaway_instance->id !== $order->get_payment_method()) {
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', ignored return, order is not a Tilopay order, order_id:' . $order->get_id(), 'info');
+ return;
+ }
+
$check_unpaid_status = (!in_array($order->get_status(), ['wc-processing', 'processing', 'refunded', 'wc-refunded', 'completed', 'wc-completed', 'cancelled', 'wc-cancelled']));
+ // Idempotency: a Tilopay transaction already processed can not be replayed
+ if ($tilopay_getaway_instance->tpay_is_tpt_processed($order, $request_tpay_order_id)) {
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', ignored return, tpt already processed, order_id:' . $order->get_id() . ', tpt:' . $request_tpay_order_id, 'info');
+ // The order received URL (with the order key) is only for the owner of the order
+ wp_safe_redirect(esc_url_raw($tilopay_getaway_instance->tpay_safe_return_url($order)));
+ exit;
+ }
+
$tilopay_getaway_settings = $tilopay_getaway_instance->tilopay_getaway_settings();
$capture_payment = $tilopay_getaway_settings['capture'];
@@ -144,34 +168,33 @@
// HPOS
$existing_auth_code = $order->get_meta('tilopay_auth_code', true);
} else {
- $existing_auth_code = get_post_meta($request_auth_code_payment, 'tilopay_auth_code', true);
+ $existing_auth_code = get_post_meta($wc_order_id, 'tilopay_auth_code', true);
}
$textOrderTilopay = ('yes' == $capture_payment) ? __('Capture', 'tilopay') : __('Authorization', 'tilopay');
+ // Capture or authorization, it is saved on the order only when the payment is verified (code=1)
$orderType = ('yes' == $capture_payment) ? 1 : 0;
- //set last action done
- if (TilopayConfig::tilopay_check_is_active_HPOS()) {
- // HPOS
- $order->update_meta_data('tilopay_is_captured', $orderType);
- } else {
- update_post_meta($request_order_id, 'tilopay_is_captured', $orderType);
- }
if (isset($_GET['wp_cancel']) && 'yes' === sanitize_text_field(wp_unslash($_GET['wp_cancel']))) {
//user cancel the process payment
- if (isset($_GET['order'])) {
+ $message_text = __('¡Process canceled by user!', 'tilopay');
- $message_text = __('¡Process canceled by user!', 'tilopay');
+ // Only the owner of an unpaid order can flag it as canceled by the user
+ if ($check_unpaid_status && $tilopay_getaway_instance->tpay_current_visitor_owns_order($order)) {
if (TilopayConfig::tilopay_check_is_active_HPOS()) {
//HPOS
$order->update_meta_data('tpay_cancel', 'yes');
$order->save();
} else {
- update_post_meta(sanitize_text_field(wp_unslash($_REQUEST['order'])), 'tpay_cancel', 'yes');
+ update_post_meta($wc_order_id, 'tpay_cancel', 'yes');
}
-
- TilopayConfig::tilopay_show_block_notices('error', esc_html($message_text));
+ } else {
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', cancel ignored, not owner or order already processed, order_id:' . $wc_order_id, 'info');
}
+
+ // No HTML output on 'init', the notice is shown on the checkout page
+ wp_safe_redirect(esc_url_raw(add_query_arg('message_error', rawurlencode($message_text), wc_get_checkout_url())));
+ exit;
} else if (!empty($request_code_payment) && 1 == $request_code_payment) {
$amount = $order->get_total();
@@ -222,14 +245,21 @@
if (TilopayConfig::tilopay_check_is_active_HPOS()) {
//HPOS
$order->update_meta_data('tilopay_auth_code', $request_auth_code_payment);
+ //set last action done (capture or authorization)
+ $order->update_meta_data('tilopay_is_captured', $orderType);
} else {
- update_post_meta($request_order_id, 'tilopay_auth_code', $request_auth_code_payment);
+ update_post_meta($wc_order_id, 'tilopay_auth_code', $request_auth_code_payment);
+ update_post_meta($wc_order_id, 'tilopay_is_captured', $orderType);
}
- $order->add_order_note(__('Authorization:', 'tilopay') . $request_auth_code_payment);
- $order->add_order_note(__('Code:', 'tilopay') . $request_code_payment);
- $order->add_order_note(__('Description:', 'tilopay') . $request_description);
+ $order->add_order_note(__('Authorization:', 'tilopay') . WCTilopay::tpay_note_value($request_auth_code_payment));
+ $order->add_order_note(__('Code:', 'tilopay') . WCTilopay::tpay_note_value($request_code_payment));
+ $order->add_order_note(__('Description:', 'tilopay') . WCTilopay::tpay_note_value($request_description));
// translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . $request_tpay_order_id);
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . WCTilopay::tpay_note_value($request_tpay_order_id));
+
+ // Invalidate the return token and register the transaction to prevent replays
+ $tilopay_getaway_instance->tpay_consume_return_token($order);
+ $tilopay_getaway_instance->tpay_mark_tpt_processed($order, $request_tpay_order_id);
$have_subscription = ((function_exists('wcs_order_contains_subscription') && wcs_order_contains_subscription($order)) || (function_exists('wcs_is_subscription') && wcs_is_subscription($request_order_id)));
//Save card for Woocommerce subscriptions payments
@@ -281,9 +311,9 @@
$redirectOrder = $tilopay_getaway_instance->get_return_url($order); // . 'order-received/' . $request_order_id . '/?key=wc_order_' . $returnData;
- //Check if car not ready empty
- if ($woocommerce->cart->is_empty()) {
- $woocommerce->cart->empty_cart();
+ //Empty the cart once the order is paid
+ if (WC()->cart && !WC()->cart->is_empty()) {
+ WC()->cart->empty_cart();
}
//Redirect to order details
@@ -294,9 +324,9 @@
exit;
} else {
- //Check if car not ready empty
- if (!WC()->cart->is_empty()) {
- $woocommerce->cart->empty_cart();
+ //Empty the cart once the order is paid
+ if (WC()->cart && !WC()->cart->is_empty()) {
+ WC()->cart->empty_cart();
}
$redirectOrder = $tilopay_getaway_instance->get_return_url($order); // . 'order-received/' . $request_order_id . '/?key=wc_order_' . $returnData;
@@ -309,19 +339,11 @@
}
} else {
+ // Unverified return: ignored, no notes and no output before the redirect
$error_message_validation = __('Description:', 'tilopay') . $request_description;
- //no hash or not equals
- $order->add_order_note($error_message_validation);
- $order->save();
- TilopayConfig::tilopay_show_block_notices('error', 'Error: ' . $error_message_validation);
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', unverified approved return ignored, order_id:' . $wc_order_id, 'info');
- $checkout_url = wc_get_checkout_url();
- $pos = strpos($checkout_url, '?');
- if (false === $pos) {
- $checkout_url = $checkout_url . '?message_error=' . $error_message_validation;
- } else {
- $checkout_url = $checkout_url . '&message_error=' . $error_message_validation;
- }
+ $checkout_url = add_query_arg('message_error', rawurlencode($error_message_validation), wc_get_checkout_url());
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . esc_url_raw($checkout_url), true, 307);
exit;
@@ -335,29 +357,45 @@
header('Location: ' . esc_url_raw($checkout_url), true, 307);
exit;
} //. end check hash
- } else if ('Pending' == $request_code_payment && empty($existing_auth_code)) {
+ } else if ('Pending' == $request_code_payment) {
- //Update order status
- $order->set_status('wc-on-hold');
+ // Pending return must be signed by Tilopay (OrderHash) or carry the valid single-use return token
+ $is_valid_hash = $tilopay_getaway_instance->tpay_verify_return_hash($order, $request_order_id, $request_tpay_order_id, $request_code_payment, $request_auth_code_payment, $computed_hash_hmac_tilopay_server);
+ $is_valid_token = !$is_valid_hash && $tilopay_getaway_instance->tpay_verify_return_token($order, $request_return_data);
- if (TilopayConfig::tilopay_check_is_active_HPOS()) {
- //HPOS
- $order->update_meta_data('tilopay_auth_code', $request_code_payment);
- } else {
- update_post_meta($request_order_id, 'tilopay_auth_code', $request_code_payment);
- }
- $order->add_order_note(__('Code:', 'tilopay') . $request_code_payment);
- $order->add_order_note(__('Description:', 'tilopay') . $request_description);
- // translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . $request_tpay_order_id);
- $order->save();
-
- //Check if car not ready empty
- if (!WC()->cart->is_empty()) {
- WC()->cart->empty_cart();
+ if ($check_unpaid_status && empty($existing_auth_code) && ($is_valid_hash || $is_valid_token)) {
+
+ //Update order status
+ $order->set_status('wc-on-hold');
+
+ if (TilopayConfig::tilopay_check_is_active_HPOS()) {
+ //HPOS
+ $order->update_meta_data('tilopay_auth_code', $request_code_payment);
+ } else {
+ update_post_meta($request_order_id, 'tilopay_auth_code', $request_code_payment);
+ }
+ $order->add_order_note(__('Code:', 'tilopay') . WCTilopay::tpay_note_value($request_code_payment));
+ $order->add_order_note(__('Description:', 'tilopay') . WCTilopay::tpay_note_value($request_description) . ($is_valid_token ? ' ' . esc_html__('(verified by return token)', 'tilopay') : ''));
+ // translators: %s action type.
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . WCTilopay::tpay_note_value($request_tpay_order_id));
+
+ // Invalidate the return token and register the transaction to prevent replays
+ $tilopay_getaway_instance->tpay_consume_return_token($order);
+ $tilopay_getaway_instance->tpay_mark_tpt_processed($order, $request_tpay_order_id);
+ $order->save();
+
+ //Check if car not ready empty
+ if (WC()->cart && !WC()->cart->is_empty()) {
+ WC()->cart->empty_cart();
+ }
+ //Redirect to order details
+ wp_safe_redirect(esc_url_raw($tilopay_getaway_instance->get_return_url($order)));
+ exit;
}
- //Redirect to order details
- wp_safe_redirect(esc_url_raw($tilopay_getaway_instance->get_return_url($order)));
+
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', unverified Pending return ignored, order_id:' . $order->get_id() . ', tpt:' . $request_tpay_order_id, 'info');
+ // Unverified: the order received URL (with the order key) is only for the owner of the order
+ wp_safe_redirect(esc_url_raw($tilopay_getaway_instance->tpay_safe_return_url($order)));
exit;
} else {
@@ -367,15 +405,27 @@
*/
$tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', else, not approved:' . print_r($_GET, true), 'info');
- $order->add_order_note(__('Order with failed payment', 'tilopay'));
- if (!empty($request_code_payment)) {
- $order->add_order_note(__('Code:', 'tilopay') . $request_code_payment);
- }
- $order->add_order_note(__('Description:', 'tilopay') . $request_description);
+ // Failed return must be signed by Tilopay (OrderHash) or carry the valid single-use return token
+ $is_valid_hash = $tilopay_getaway_instance->tpay_verify_return_hash($order, $request_order_id, $request_tpay_order_id, $request_code_payment, $request_auth_code_payment, $computed_hash_hmac_tilopay_server);
+ $is_valid_token = !$is_valid_hash && $tilopay_getaway_instance->tpay_verify_return_token($order, $request_return_data);
+
+ if ($check_unpaid_status && ($is_valid_hash || $is_valid_token)) {
+ $order->add_order_note(__('Order with failed payment', 'tilopay'));
+ if (!empty($request_code_payment)) {
+ $order->add_order_note(__('Code:', 'tilopay') . WCTilopay::tpay_note_value($request_code_payment));
+ }
+ $order->add_order_note(__('Description:', 'tilopay') . WCTilopay::tpay_note_value($request_description) . ($is_valid_token ? ' ' . esc_html__('(verified by return token)', 'tilopay') : ''));
- //Update order status
- $order->set_status('wc-failed');
- $order->save();
+ // Invalidate the return token and register the transaction to prevent replays
+ $tilopay_getaway_instance->tpay_consume_return_token($order);
+ $tilopay_getaway_instance->tpay_mark_tpt_processed($order, $request_tpay_order_id);
+
+ //Update order status
+ $order->set_status('wc-failed');
+ $order->save();
+ } else {
+ $tilopay_getaway_instance->log(__METHOD__ . ':::' . __LINE__ . ', unverified failed return ignored, order_id:' . $order->get_id() . ', tpt:' . $request_tpay_order_id, 'info');
+ }
//if SINPEMOVIL error mean is partial payment
if ('SINPEMOVIL' == $selected_method) {
@@ -383,16 +433,15 @@
$request_description = sprintf(__('%1$s, contact the seller to complete your order no.%2$s. If you try to pay again, your payment will be rejected.', 'tilopay'), $request_description, $request_order_id);
}
- $checkout_url = wc_get_checkout_url();
- $pos = strpos($checkout_url, '?');
- if (false === $pos) {
- $checkout_url = $checkout_url . '?message_error=' . $request_description . '&from=' . __LINE__;
- } else {
- $checkout_url = $checkout_url . '&message_error=' . $request_description . '&from=' . __LINE__;
- }
+ $checkout_url = add_query_arg(
+ array(
+ 'message_error' => rawurlencode($request_description),
+ 'from' => __LINE__,
+ ),
+ wc_get_checkout_url()
+ );
header('Cache-Control: no-cache, must-revalidate');
- //header('Location: ' . $checkout_url, true, 307);
wp_safe_redirect(esc_url_raw($checkout_url));
exit;
}
@@ -438,7 +487,7 @@
}
} catch (Throwable $th) {
//throw $th;
- $this->log(__METHOD__ . ':::' . __LINE__ . 'Throwable message error:' . $th->getMessage() . ', file:' . $th->getFile() . ', line:' . $th->getLine(), 'error');
+ (new WCTilopay())->log(__METHOD__ . ':::' . __LINE__ . ', Throwable message error:' . $th->getMessage() . ', file:' . $th->getFile() . ', line:' . $th->getLine(), 'error');
}
}
@@ -550,15 +599,13 @@
'limit' => -1,
));
foreach ($orders as $data) {
- $logger = new WC_Logger();
- if (TilopayConfig::tilopay_check_is_active_HPOS()) {
- // HPOS
- $meta_field_data = $data->get_meta('tpay_cancel', true);
- } else {
- $meta_field_data = get_post_meta($data, 'tpay_cancel')[0] ? get_post_meta($data, 'tpay_cancel')[0] : '';
+ // wc_get_orders returns ids: load the order before reading its meta
+ $order = wc_get_order($data);
+ if (!$order || 'tilopay' !== $order->get_payment_method()) {
+ continue;
}
+ $meta_field_data = $order->get_meta('tpay_cancel', true);
if ('modal' == $meta_field_data) {
- $order = wc_get_order($data);
$wc_order_id = $order->get_id();
$order->add_order_note(__('Order canceled when closing the payment method', 'tilopay'));
@@ -622,14 +669,19 @@
{
if (isset($_REQUEST['response_data'])) {
if ('found' === $_REQUEST['response_data'] && isset($_REQUEST['order_id'])) {
- $order_id = sanitize_text_field(wp_unslash($_REQUEST['order_id']));
+ $order_id = absint(wp_unslash($_REQUEST['order_id']));
+ $order = wc_get_order($order_id);
+ $tilopay_instance = new WCTilopay();
+
+ // The payment form belongs to the order: only its owner can be redirected to it, and only while unpaid
+ if (!$order || $tilopay_instance->id !== $order->get_payment_method() || !$order->needs_payment() || !$tilopay_instance->tpay_current_visitor_owns_order($order)) {
+ $tilopay_instance->log(__METHOD__ . ':::' . __LINE__ . ', payment form redirect ignored, order_id:' . $order_id, 'info');
+ return;
+ }
- if (TilopayConfig::tilopay_check_is_active_HPOS()) {
- // HPOS
- $order = wc_get_order($order_id);
- $tpay_url_payment_form = $order->get_meta('tilopay_html_form', true);
- } else {
- $tpay_url_payment_form = get_post_meta($order_id, 'tilopay_html_form')[0];
+ $tpay_url_payment_form = $order->get_meta('tilopay_html_form', true);
+ if (empty($tpay_url_payment_form)) {
+ $tpay_url_payment_form = get_post_meta($order_id, 'tilopay_html_form', true);
}
//check if have html
if (isset($tpay_url_payment_form) && '' != $tpay_url_payment_form) {
@@ -713,8 +765,8 @@
update_post_meta($order_id, 'tilopay_is_captured', 1);
}
// translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . $request_tpay_order_id);
- $order->add_order_note(__('Result:', 'tilopay') . $getResponse->ReasonCodeDescription);
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . WCTilopay::tpay_note_value($request_tpay_order_id));
+ $order->add_order_note(__('Result:', 'tilopay') . WCTilopay::tpay_note_value($getResponse->ReasonCodeDescription));
//Update order status
$order->set_status('wc-processing');
@@ -729,7 +781,7 @@
// translators: %s the order number.
$errorNote = sprintf(__('Error, the refund of the order no.%s could not be made.', 'tilopay'), $order_id);
- $errorNote = (!empty($errorResponse)) ? $errorNote . ' Error Tilopay:' . $errorResponse : $errorNote;
+ $errorNote = (!empty($errorResponse)) ? $errorNote . ' Error Tilopay:' . WCTilopay::tpay_note_value($errorResponse) : $errorNote;
$order->add_order_note($errorNote);
$order->set_status('wc-failed');
$order->save();
@@ -788,7 +840,7 @@
return;
}
- $wc_tilopay->log(__METHOD__ . ':::' . __LINE__ . ', order null, order_get_id:' . $order_get_id . ', order:' . print_r($order, true), 'warning');
+ $wc_tilopay->log(__METHOD__ . ':::' . __LINE__ . ', order_get_id:' . $order_get_id . ', status:' . $order->get_status(), 'warning');
//Get refund order
$refund = wc_get_order($refund_id);
@@ -840,9 +892,9 @@
//Set not from API Response
if (false !== $getResponse && isset($getResponse->ReasonCode) && in_array($getResponse->ReasonCode, ['1', '1101'])) {
// translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . $tpay_order_id);
- $order->add_order_note(__('Code:', 'tilopay') . $getResponse->ReasonCode);
- $order->add_order_note(__('Result:', 'tilopay') . $getResponse->ReasonCodeDescription);
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . WCTilopay::tpay_note_value($tpay_order_id));
+ $order->add_order_note(__('Code:', 'tilopay') . WCTilopay::tpay_note_value($getResponse->ReasonCode));
+ $order->add_order_note(__('Result:', 'tilopay') . WCTilopay::tpay_note_value($getResponse->ReasonCodeDescription));
$wc_order_id = $order->get_id();
//Update order status
@@ -863,7 +915,7 @@
// translators: %s the order number.
$errorNote = sprintf(__('Error, the refund of the order no.%s could not be made.', 'tilopay'), $order_id);
- $errorNote = (!empty($errorResponse)) ? $errorNote . ' Error Tilopay:' . $errorResponse : $errorNote;
+ $errorNote = (!empty($errorResponse)) ? $errorNote . ' Error Tilopay:' . WCTilopay::tpay_note_value($errorResponse) : $errorNote;
$order->add_order_note($errorNote);
}
--- a/tilopay/includes/WCTilopay.php
+++ b/tilopay/includes/WCTilopay.php
@@ -144,43 +144,32 @@
function tpay_url_for_invalide_hash_confirmation($order, $computed_hash_hmac_tilopay_server, $customer_computed_hash_hmac, $wc_order_id)
{
- // translators: %s the order number.
- $order->add_order_note(__('Description:', 'tilopay') . sprintf(__('Invalid order confirmation, please check and try again or contact the seller to completed you order no.%s', 'tilopay'), $wc_order_id));
- $order->add_order_note('Order hash:', ' tpay:' . sanitize_text_field($computed_hash_hmac_tilopay_server) . '|website:' . sanitize_text_field($customer_computed_hash_hmac));
- // translators: %s the order number.
- TilopayConfig::tilopay_show_block_notices('error', 'Error: ' . sprintf(__('Invalid order confirmation, please check and try again or contact the seller to completed you order no.%s', 'tilopay'), $wc_order_id));
-
- //Update order status
- $order->set_status('wc-failed');
- $order->save();
-
+ // An approved return whose OrderHash can not be verified did not come from Tilopay (or was tampered).
+ // It is ignored: no order notes, no status change (no "Failed order" email) and no output before the redirect.
+ // The expected HMAC is never exposed; only a short prefix of the received hash is logged for support.
// translators: %s the order number.
$error_message_validation = sprintf(__('Invalid order confirmation, please check and try again or contact the seller to completed you order no.%s', 'tilopay'), $wc_order_id);
- $this->log(__METHOD__ . ':::' . __LINE__ . ', order_id:' . $wc_order_id . ', error message:' . $error_message_validation, 'info');
-
- $checkout_url = wc_get_checkout_url();
- $pos = strpos($checkout_url, '?');
- if (false === $pos) {
- $checkout_url = $checkout_url . '?message_error=' . $error_message_validation;
- } else {
- $checkout_url = $checkout_url . '&message_error=' . $error_message_validation;
- }
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', unverified approved return ignored, order_id:' . $wc_order_id . ', status:' . $order->get_status() . ', received hash prefix:' . substr(preg_replace('/[^a-f0-9]/i', '', (string) $computed_hash_hmac_tilopay_server), 0, 8), 'info');
- return $checkout_url;
+ return add_query_arg('message_error', rawurlencode($error_message_validation), wc_get_checkout_url());
}
function tpay_apply_redirect_to_payment_form($show_error = false)
{
if (isset($_REQUEST['process_payment']) && 'tilopay' == $_REQUEST['process_payment'] && isset($_REQUEST['tlpy_payment_order'])) {
- $order_id = sanitize_text_field(wp_unslash($_REQUEST['tlpy_payment_order']));
+ $order_id = absint(wp_unslash($_REQUEST['tlpy_payment_order']));
+ $getOrder = wc_get_order($order_id);
- if ($this->is_active_HPOS) {
- // HPOS
- $getOrder = wc_get_order($order_id);
- $tpay_url_payment_form = $getOrder->get_meta('tilopay_html_form', true);
- } else {
- $tpay_url_payment_form = get_post_meta($order_id, 'tilopay_html_form')[0];
+ // The payment form belongs to the order: only its owner can be redirected to it, and only while unpaid
+ if (!$getOrder || $this->id !== $getOrder->get_payment_method() || !$getOrder->needs_payment() || !$this->tpay_current_visitor_owns_order($getOrder)) {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', payment form redirect ignored, order_id:' . $order_id, 'info');
+ return;
+ }
+
+ $tpay_url_payment_form = $getOrder->get_meta('tilopay_html_form', true);
+ if (empty($tpay_url_payment_form)) {
+ $tpay_url_payment_form = get_post_meta($order_id, 'tilopay_html_form', true);
}
if (true === $show_error) {
$tpay_url_payment_form = (false === strpos($tpay_url_payment_form, '?'))
@@ -208,11 +197,14 @@
wp_safe_redirect($redirect_url);
exit;
} else {
- $cross_domain_handle = (false === strpos($this->site_url, '?'))
- ? $this->site_url . '?message_error=Cross domain redirect error, is not Tilopay redirect payment form.' . $tpay_url_payment_form . '&from=' . __LINE__
- : $this->site_url . '&message_error=Cross domain redirect error, is not Tilopay redirect payment form.' . $tpay_url_payment_form . '&from=' . __LINE__;
- // translators: %s the order number.
- TilopayConfig::tilopay_show_block_notices('error', 'Error: Cross domain redirect error, is not Tilopay redirect payment form.' . $tpay_url_payment_form);
+ // No HTML output before the redirect, the error is shown on the destination page
+ $cross_domain_handle = add_query_arg(
+ array(
+ 'message_error' => rawurlencode('Cross domain redirect error, is not Tilopay redirect payment form.'),
+ 'from' => __LINE__,
+ ),
+ $this->site_url
+ );
wp_safe_redirect(esc_url_raw($cross_domain_handle));
exit;
}
@@ -242,6 +234,9 @@
if (isset($params['api_user'])) {
$log_params['api_user'] = '***';
}
+ if (isset($params['api_Key'])) {
+ $log_params['api_Key'] = self::tpay_mask_secret($params['api_Key']);
+ }
//computed customer hash_hmac
$own_hash = hash_hmac('sha256', http_build_query($params), $hashKey);
@@ -249,6 +244,366 @@
//computed customer hash
return $own_hash;
}
+
+ /**
+ * Verify the OrderHash (HMAC V2) received from Tilopay on the browser return.
+ * Uses the email sent to Tilopay (or billing email) and falls back to the WP user email.
+ *
+ * @param WC_Order $order
+ * @param string $request_order_id WooCommerce order id received in the URL.
+ * @param string $tpay_order_id Tilopay order id (tpt).
+ * @param string $code Response code received in the URL.
+ * @param string $auth Authorization code received in the URL.
+ * @param string $server_hash OrderHash received in the URL.
+ * @return bool
+ */
+ public function tpay_verify_return_hash($order, $request_order_id, $tpay_order_id, $code, $auth, $server_hash)
+ {
+ if (empty($server_hash) || 64 !== strlen($server_hash) || empty($tpay_order_id)) {
+ return false;
+ }
+
+ $saved_email = $order->get_meta('tilopay_sent_email', true);
+ if (empty($saved_email)) {
+ $saved_email = get_post_meta($order->get_id(), 'tilopay_sent_email', true);
+ }
+ $billing_email = !empty($saved_email)
+ ? strtolower(trim($saved_email))
+ : strtolower(trim($order->get_billing_email()));
+
+ $amount = $order->get_total();
+ $currency = get_woocommerce_currency();
+
+ $customer_hash = $this->computed_customer_hash($request_order_id, $amount, $currency, $tpay_order_id, $code, $auth, $billing_email);
+ if (hash_equals($customer_hash, $server_hash)) {
+ return true;
+ }
+
+ // Fallback: order belongs to a WP user, test with user_email
+ if ($order->get_user_id()) {
+ $user = get_userdata($order->get_user_id());
+ if ($user && !empty($user->user_email)) {
+ $wp_user_email = strtolower(trim($user->user_email));
+ if (!empty($wp_user_email) && $wp_user_email !== $billing_email) {
+ $user_hash = $this->computed_customer_hash($request_order_id, $amount, $currency, $tpay_order_id, $code, $auth, $wp_user_email);
+ if (hash_equals($user_hash, $server_hash)) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Sign the return token.
+ *
+ * @param int $order_id
+ * @param string $nonce
+ * @param int $exp
+ * @return string
+ */
+ private function tpay_sign_return_token($order_id, $nonce, $exp)
+ {
+ return hash_hmac('sha256', absint($order_id) . '|' . $nonce . '|' . absint($exp), wp_salt('auth'));
+ }
+
+ /**
+ * Create an ephemeral, single-use and signed return token for a payment request.
+ * It is sent to Tilopay as returnData and echoed back on the browser return.
+ * Each call invalidates the previous token of the order.
+ *
+ * @param WC_Order $order
+ * @return string nonce.exp.sig
+ */
+ public function tpay_create_return_token($order)
+ {
+ $order_id = $order->get_id();
+ $nonce = wp_generate_password(16, false, false);
+ $ttl = absint(apply_filters('tilopay_return_token_ttl', 2 * HOUR_IN_SECONDS, $order));
+ $exp = time() + ($ttl > 0 ? $ttl : 2 * HOUR_IN_SECONDS);
+
+ if ($this->is_active_HPOS) {
+ //HPOS
+ $order->update_meta_data('tilopay_return_nonce', $nonce);
+ $order->save();
+ } else {
+ update_post_meta($order_id, 'tilopay_return_nonce', $nonce);
+ }
+
+ return $nonce . '.' . $exp . '.' . $this->tpay_sign_return_token($order_id, $nonce, $exp);
+ }
+
+ /**
+ * Check if the current visitor is the owner of the order (same logged in customer or same WooCommerce session).
+ * Used to avoid exposing the order received URL (it contains the order key) to third parties.
+ *
+ * @param WC_Order $order
+ * @return bool
+ */
+ public function tpay_current_visitor_owns_order($order)
+ {
+ if (!$order) {
+ return false;
+ }
+
+ // Order key (same proof WooCommerce uses for guests: pay for order links, order received page)
+ if (isset($_GET['key']) && is_string($_GET['key'])) {
+ $order_key = wc_clean(wp_unslash($_GET['key']));
+ if ('' !== $order_key && hash_equals((string) $order->get_order_key(), $order_key)) {
+ return true;
+ }
+ }
+
+ $customer_id = (int) $order->get_customer_id();
+ if ($customer_id > 0) {
+ return get_current_user_id() === $customer_id;
+ }
+
+ if (function_exists('WC') && WC()->session) {
+ foreach (array('order_awaiting_payment', 'store_api_draft_order') as $session_key) {
+ if ((int) WC()->session->get($session_key) === (int) $order->get_id()) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Redirect URL after a browser return that does not change the order:
+ * the order received page only for the owner of the order, otherwise the checkout page.
+ *
+ * @param WC_Order $order
+ * @return string
+ */
+ public function tpay_safe_return_url($order)
+ {
+ return $this->tpay_current_visitor_owns_order($order)
+ ? $this->get_return_url($order)
+ : wc_get_checkout_url();
+ }
+
+ /**
+ * Prepare an order to be paid from the SDK at the browser (native SINPE Móvil).
+ * Saves the lowercase email sent to Tilopay (used to validate the OrderHash) and creates the return token.
+ *
+ * @param WC_Order $order
+ * @return array returnData and billToEmail for the SDK init
+ */
+ public function tpay_prepare_sdk_order_payment($order)
+ {
+ $sent_email = strtolower(trim($order->get_billing_email()));
+
+ if ($this->is_active_HPOS) {
+ //HPOS
+ $order->update_meta_data('tilopay_sent_email', $sent_email);
+ $order->save();
+ } else {
+ update_post_meta($order->get_id(), 'tilopay_sent_email', $sent_email);
+ }
+
+ return array(
+ 'returnData' => $this->tpay_create_return_token($order),
+ 'billToEmail' => $sent_email,
+ );
+ }
+
+ /**
+ * Verify the return token received in returnData.
+ *
+ * @param WC_Order $order
+ * @param string $token
+ * @return bool
+ */
+ public function tpay_verify_return_token($order, $token)
+ {
+ if (empty($token) || !is_string($token)) {
+ return false;
+ }
+
+ $parts = explode('.', $token);
+ if (3 !== count($parts)) {
+ return false;
+ }
+ list($nonce, $exp, $sig) = $parts;
+
+ if ('' === $nonce || !ctype_digit($exp) || 64 !== strlen($sig)) {
+ return false;
+ }
+
+ if ((int) $exp < time()) {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', return token expired, order_id:' . $order->get_id(), 'info');
+ return false;
+ }
+
+ $expected_sig = $this->tpay_sign_return_token($order->get_id(), $nonce, $exp);
+ if (!hash_equals($expected_sig, $sig)) {
+ return false;
+ }
+
+ $stored_nonce = $order->get_meta('tilopay_return_nonce', true);
+ if (empty($stored_nonce)) {
+ $stored_nonce = get_post_meta($order->get_id(), 'tilopay_return_nonce', true);
+ }
+ if (empty($stored_nonce) || !is_string($stored_nonce)) {
+ // Token already consumed, replaced by a new payment request or order created before 3.1.4
+ return false;
+ }
+
+ return hash_equals($stored_nonce, $nonce);
+ }
+
+ /**
+ * Consume (invalidate) the current return token so a return URL can not be replayed.
+ *
+ * @param WC_Order $order
+ */
+ public function tpay_consume_return_token($order)
+ {
+ if ($this->is_active_HPOS) {
+ //HPOS
+ $order->delete_meta_data('tilopay_return_nonce');
+ } else {
+ delete_post_meta($order->get_id(), 'tilopay_return_nonce');
+ }
+ }
+
+ /**
+ * Check if a Tilopay transaction (tpt) was already processed for this order.
+ *
+ * @param WC_Order $order
+ * @param string $tpay_order_id
+ * @return bool
+ */
+ public function tpay_is_tpt_processed($order, $tpay_order_id)
+ {
+ if ('' === (string) $tpay_order_id) {
+ return false;
+ }
+ $processed = $order->get_meta('tilopay_processed_tpt', true);
+ if (empty($processed)) {
+ $processed = get_post_meta($order->get_id(), 'tilopay_processed_tpt', true);
+ }
+ return is_array($processed) && in_array((string) $tpay_order_id, $processed, true);
+ }
+
+ /**
+ * Register a Tilopay transaction (tpt) as processed for this order.
+ *
+ * @param WC_Order $order
+ * @param string $tpay_order_id
+ */
+ public function tpay_mark_tpt_processed($order, $tpay_order_id)
+ {
+ if ('' === (string) $tpay_order_id) {
+ return;
+ }
+ $processed = $order->get_meta('tilopay_processed_tpt', true);
+ if (empty($processed)) {
+ $processed = get_post_meta($order->get_id(), 'tilopay_processed_tpt', true);
+ }
+ $processed = is_array($processed) ? $processed : array();
+ $processed[] = (string) $tpay_order_id;
+ // Keep only the last 20 transactions
+ $processed = array_slice(array_values(array_unique($processed)), -20);
+
+ if ($this->is_active_HPOS) {
+ //HPOS
+ $order->update_meta_data('tilopay_processed_tpt', $processed);
+ } else {
+ update_post_meta($order->get_id(), 'tilopay_processed_tpt', $processed);
+ }
+ }
+
+ /**
+ * Clean a text received from an external source (URL / API) before using it in an order note.
+ * Removes any markup, HTML entities and characters that could be used to build HTML, JS or shell code,
+ * keeping only a whitelist of plain text characters.
+ *
+ * @param mixed $text
+ * @return string
+ */
+ public static function tpay_clean_note_text($text)
+ {
+ if (is_array($text) || is_object($text)) {
+ $text = wp_json_encode($text);
+ }
+ if (!is_scalar($text)) {
+ return '';
+ }
+ $text = sanitize_text_field((string) $text);
+ $text = wp_strip_all_tags($text);
+ // Remove HTML entities (e.g. < ") that could be decoded back to markup by admin scripts
+ $text = preg_replace('/&#?[a-z0-9]+;?/i', '', $text);
+ // Whitelist: letters (any language), numbers, spaces and basic punctuation.
+ // Drops < > " ' ` = ; & | $ { } [ ] and any other character usable to inject HTML, JS or shell code
+ $text = preg_replace('/[^p{L}p{N}s.,:-_/#()%+@*]/u', '', $text);
+ $text = preg_replace('/s+/u', ' ', (string) $text);
+ // Avoid very long notes
+ if (function_exists('mb_substr')) {
+ $text = mb_substr($text, 0, 500);
+ } else {
+ $text = substr($text, 0, 500);
+ }
+ return trim($text);
+ }
+
+ /**
+ * Clean and escape an external value to be concatenated into an order note.
+ *
+ * @param mixed $value
+ * @return string
+ */
+ public static function tpay_note_value($value)
+ {
+ return esc_html(self::tpay_clean_note_text($value));
+ }
+
+ /**
+ * Mask a secret value (API key, password, user) keeping only the last 4 characters.
+ *
+ * @param string $value
+ * @return string
+ */
+ public static function tpay_mask_secret($value)
+ {
+ $value = (string) $value;
+ if ('' === $value) {
+ return '';
+ }
+ return (strlen($value) > 4) ? str_repeat('*', 8) . substr($value, -4) : '****';
+ }
+
+ /**
+ * Remove credentials from a log message: configured API key/user/password,
+ * any API key with Tilopay format (xxxx-xxxx-xxxx-xxxx-xxxx) and bearer tokens.
+ *
+ * @param string $message
+ * @return string
+ */
+ private function tpay_mask_log_message($message)
+ {
+ $message = (string) $message;
+ $secrets = array($this->tpay_key, $this->tpay_password, $this->tpay_user);
+ foreach ($secrets as $secret) {
+ if (is_string($secret) && strlen($secret) >= 4) {
+ $message = str_replace($secret, self::tpay_mask_secret($secret), $message);
+ }
+ }
+ // API keys with Tilopay format
+ $message = preg_replace_callback('/bd{4}-d{4}-d{4}-d{4}-(d{4})b/', function ($m) {
+ return '****-****-****-****-' . $m[1];
+ }, $message);
+ // Bearer / access tokens
+ $message = preg_replace('/(bearers+)[A-Za-z0-9-._~+/]+=*/i', '$1***', $message);
+ // access_token in print_r ([access_token] => x), JSON ("access_token":"x") or query string (access_token=x)
+ $message = preg_replace('/(["']?[?access_token]?["']?s*(=>|:|=)s*["']?)[A-Za-z0-9-._~+/]+=*/i', '$1***', $message);
+ return $message;
+ }
+
/**
* Notify of issues in wp-admin
*/
@@ -280,7 +635,8 @@
//Only log if debug mode is yes
if ('yes' == $this->debug_mode) {
- $this->log->add($this->id, $message, $level);
+ // Never write credentials to the logs
+ $this->log->add($this->id, $this->tpay_mask_log_message($message), $level);
}
}
@@ -424,7 +780,7 @@
$response = wp_remote_post(TPAY_ENV_URL . 'login', $args);
- $result = json_decode($response['body']);
+ $result = json_decode(wp_remote_retrieve_body($response));
$order_total = $order->get_total();
@@ -462,7 +818,7 @@
'key' => $this->tpay_key,
'amount' => $order_total,
'currency' => get_woocommerce_currency(),
- 'email' => $order->get_billing_email(),
+ 'email' => strtolower(trim($order->get_billing_email())),
'orderNumber' => $wc_order_id,
'capture' => 'yes' == $this->tpay_capture ? 1 : 0,
'card' => $token,
@@ -497,12 +853,12 @@
);
$response = wp_remote_post(TPAY_ENV_URL . 'processRecurrentPayment', $args);
- $result = json_decode($response['body']);
+ $result = json_decode(wp_remote_retrieve_body($response));
if (is_wp_error($response)) {
$cleanBodyRequest = $dataJson;
$cleanBodyRequest['card'] = '...';
- $responseBodyError = isset($response['body']) ? $response['body'] : '';
+ $responseBodyError = (is_wp_error($response) ? $response->get_error_message() : wp_remote_retrieve_body($response));
$this->log(__METHOD__ . ':::' . __LINE__ . ', response:' . print_r($responseBodyError, true) . ', request_data:' . print_r($cleanBodyRequest, true), 'error');
}
@@ -513,7 +869,7 @@
return true;
} else {
- $order->add_order_note(json_encode($result));
+ $order->add_order_note(self::tpay_note_value($result));
$order->add_order_note(__('Connection error with TILOPAY, contact sac@tilopay.com.', 'tilopay'));
//Update order status
@@ -525,7 +881,7 @@
} else {
//Dont have token
- $order->add_order_note(json_encode($result) . ' Pay With token ' . __LINE__);
+ $order->add_order_note(self::tpay_note_value($result) . ' Pay With token ' . __LINE__);
$order->add_order_note(__("There seems to be an issue with this website's integration with Tilopay, please inform the seller to complete your purchase.", 'tilopay') . ' Pay With token ' . __LINE__);
//Update order status
@@ -582,11 +938,11 @@
//Add update post meta to the state user select
$order->payment_complete($response->auth);
- $order->add_order_note(__('Authorization:', 'tilopay') . $response->auth);
- $order->add_order_note(__('Code:', 'tilopay') . $response->response);
- $order->add_order_note(__('Description:', 'tilopay') . $response->description);
+ $order->add_order_note(__('Authorization:', 'tilopay') . self::tpay_note_value($response->auth));
+ $order->add_order_note(__('Code:', 'tilopay') . self::tpay_note_value($response->response));
+ $order->add_order_note(__('Description:', 'tilopay') . self::tpay_note_value(isset($response->description) ? $response->description : ''));
// translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . $tpay_order_id);
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), $textOrderTilopay) . self::tpay_note_value($tpay_order_id));
} else {
$responseText = isset($response->description) ? $response->description : '';
$responseResult = (!empty($response->result) && isset($response->result)) ? $response->result : $responseText;
@@ -594,7 +950,7 @@
$responseResult = (!empty($responseResult)) ? $responseResult : 'validation response ' . wp_json_encode($response);
// translators: %s message get from Tilopay call api.
- $order->add_order_note(sprintf(__('Payment processing failed. Please retry, Tilopay responded with error: %s', 'tilopay'), $responseResult));
+ $order->add_order_note(sprintf(__('Payment processing failed. Please retry, Tilopay responded with error: %s', 'tilopay'), self::tpay_note_value($responseResult)));
//Update order status
$order->set_status('wc-failed');
@@ -1106,11 +1462,16 @@
$order->set_status('wc-pending');
$order->save();
+ // The SDK pays this order from the browser: send it the signed return token and the lowercase email
+ $sdk_order_payment = $this->tpay_prepare_sdk_order_payment($order);
+
//Return to get order_id at FE only for sinpemovil
return array(
'result' => 'processing',
'messages' => 'sinpemovil',
'order_id' => $order_id,
+ 'return_data' => $sdk_order_payment['returnData'],
+ 'bill_to_email' => $sdk_order_payment['billToEmail'],
);
}
$tokenize_new_card = 'off'; // not need tokenize
@@ -1127,6 +1488,8 @@
} else {
$checkout_url = $checkout_url . '&process_payment=tilopay&tlpy_payment_order=' . $order_id . '&tlpy_payment_method=' . base64_encode($get_tlpy_payment_method . '|' . $check_box_must_be_selected);
}
+ // Order key: lets guests without the order in session (pay for order links) continue the payment
+ $checkout_url = add_query_arg('key', $order->get_order_key(), $checkout_url);
return array(
'result' => 'success',
@@ -1209,7 +1572,7 @@
'billToZipPostCode' => $order->get_billing_postcode(),
'billToCountry' => $order->get_billing_country(),
'billToTelephone' => $order->get_billing_phone(),
- 'billToEmail' => $order->get_billing_email(),
+ 'billToEmail' => strtolower(trim($order->get_billing_email())),
'orderNumber' => $order_id,
'capture' => 'yes' == $this->tpay_capture ? 1 : 0,
'sessionId' => isset($_POST['woo_session_tilopay']) ? sanitize_text_field(wp_unslash($_POST['woo_session_tilopay'])) : 'WOO-' . time(),
@@ -1234,7 +1597,7 @@
//'referenceSinpe' => $referenceSinpe,
'lang' => get_bloginfo('language'),
'hashVersion' => 'V2',
- 'returnData' => $this->id,
+ 'returnData' => $this->tpay_create_return_token($order),
'paymentData' => isset($_POST['payload_apple_pay']) ? json_decode(sanitize_text_field(wp_unslash($_POST['payload_apple_pay'])), true) : '',
'processApplePay' => $processApplePay,
'phoneYappy' => isset($_POST['tlpy_yappy_phone']) ? json_decode(sanitize_text_field(wp_unslash($_POST['tlpy_yappy_phone'])), true) : '',
@@ -1333,7 +1696,7 @@
$response = wp_remote_post(TPAY_ENV_URL . 'login', $args);
- $result = json_decode($response['body']);
+ $result = json_decode(wp_remote_retrieve_body($response));
$order_id = $order->get_id();
//Check if have a token
@@ -1355,7 +1718,7 @@
'billToZipPostCode' => $order->get_billing_postcode(),
'billToCountry' => $order->get_billing_country(),
'billToTelephone' => $order->get_billing_phone(),
- 'billToEmail' => $order->get_billing_email(),
+ 'billToEmail' => strtolower(trim($order->get_billing_email())),
'orderNumber' => $order_id,
'capture' => 'yes' == $this->tpay_capture ? 1 : 0,
'subscription' => $this->tpay_check_have_subscription(),
@@ -1364,7 +1727,7 @@
'platform_reference' => $this->tpay_platform_detail(),
'lang' => get_bloginfo('language'),
'hashVersion' => 'V2',
- 'returnData' => $this->id
+ 'returnData' => $this->tpay_create_return_token($order)
];
if ($this->have_subscription && ((function_exists('wcs_order_contains_subscription') && wcs_order_contains_subscription($order_id)) || (function_exists('wcs_is_subscription') && wcs_is_subscription($order_id)))) {
$datajson['subscription'] = 1;
@@ -1392,7 +1755,7 @@
'cookies' => array(),
);
$response = wp_remote_post(TPAY_ENV_URL . 'processPayment', $args);
- $result = json_decode($response['body']);
+ $result = json_decode(wp_remote_retrieve_body($response));
$this->log(__METHOD__ . ':::' . __LINE__ . ', redirect payment order_id:' . $order_id . ', response:' . print_r($result, true), 'info');
@@ -1439,6 +1802,8 @@
} else {
$checkout_url = $checkout_url . '&process_payment=tilopay&tlpy_payment_order=' . $order_id . $for_native_error;
}
+ // Order key: lets guests without the order in session (pay for order links) continue the payment
+ $checkout_url = add_query_arg('key', $order->get_order_key(), $checkout_url);
return array(
'result' => 'success',
@@ -1455,8 +1820,8 @@
}
} else {
//Dont have token
- $responseBodyError = isset($response['body']) ? $response['body'] : '';
- $this->log(__METHOD__ . ':::' . __LINE__ . ', order_id:' . $order_id . ', response:', print_r($responseBodyError, true), 'error');
+ $responseBodyError = (is_wp_error($response) ? $response->get_error_message() : wp_remote_retrieve_body($response));
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', order_id:' . $order_id . ', response:' . print_r($responseBodyError, true), 'error');
// TilopayConfig::tilopay_show_block_notices('error', __("There seems to be an issue with this website's integration with Tilopay, please inform the seller to complete your purchase.", 'tilopay') . ' Process Payment ' . __LINE__, 'error');
} //.End check have token
@@ -1506,13 +1871,13 @@
$getCallTpayAPI = wp_remote_post(TPAY_ENV_URL . 'login', $args);
if (is_wp_error($getCallTpayAPI)) {
- $responseBodyError = isset($getCallTpayAPI['body']) ? $getCallTpayAPI['body'] : '';
- $this->log(__METHOD__ . ':::' . __LINE__ . ', order_id:' . $order_id . ', response:', print_r($responseBodyError, true), 'error');
+ $responseBodyError = (is_wp_error($getCallTpayAPI) ? $getCallTpayAPI->get_error_message() : wp_remote_retrieve_body($getCallTpayAPI));
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', order_id:' . $order_id . ', response:' . print_r($responseBodyError, true), 'error');
return false;
}
//All is ok
- $getTpayResponseDecode = json_decode($getCallTpayAPI['body']);
+ $getTpayResponseDecode = json_decode(wp_remote_retrieve_body($getCallTpayAPI));
//Check if have a token
if (isset($getTpayResponseDecode->access_token)) {
@@ -1548,12 +1913,12 @@
);
$getCallTpayAPIModification = wp_remote_post(TPAY_ENV_URL . 'processModification', $args);
if (is_wp_error($getCallTpayAPIModification)) {
- $responseBodyError = isset($getCallTpayAPIModification['body']) ? $getCallTpayAPIModification['body'] : '';
+ $responseBodyError = (is_wp_error($getCallTpayAPIModification) ? $getCallTpayAPIModification->get_error_message() : wp_remote_retrieve_body($getCallTpayAPIModification));
$this->log(__METHOD__ . ':::' . __LINE__ . ', request_data:' . print_r($responseBodyError, true), 'error');
return false;
}
- $getModificationResDecode = json_decode($getCallTpayAPIModification['body']);
+ $getModificationResDecode = json_decode(wp_remote_retrieve_body($getCallTpayAPIModification));
return $getModificationResDecode;
} //.End check have token
@@ -1616,12 +1981,23 @@
$orderNumber = $responseJson->orderNumber;
$code = $responseJson->code;
$tpay_order_id = $responseJson->tpt;
- $auth = $responseJson->auth;
//Get Woocommerce order
global $woocommerce;
$order = wc_get_order($orderNumber);
+ // Unknown order or not paid with Tilopay: same generic answer, no data about the order
+ if (!$order || $this->id !== $order->get_payment_method() || !is_string($responseJson->orderHash)) {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', notification ignored, unknown or not Tilopay order', 'info');
+ return wp_send_json(array(
+ 'code' => 400,
+ 'message' => 'Invalid order confirmation',
+ 'data' => null
+ ), 400);
+ exit;
+ }
$wc_order_id = $order->get_id();
+ $auth = isset($responseJson->auth) ? $responseJson->auth : '';
+ $check_unpaid_status = !in_array($order->get_status(), array('processing', 'completed', 'refunded', 'cancelled'), true);
$orderHash = $responseJson->orderHash;
if (!empty($orderHash) && isset($orderHash) && 64 == strlen($orderHash)) {
@@ -1660,9 +2036,11 @@
//Use hmac data to check if the response is from Tilopay or not
if (!hash_equals($customerOrderHash, $orderHash)) {
- $order->add_order_note(__('Description:', 'tilopay') . __('Order with failed payment', 'tilopay'));
+ // Unverified notification: ignored, no order notes
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', unverified notification ignored, order_id:' . $wc_order_id, 'info');
// translators: %s the order number.
- $get_traslate_message = sprintf(__('Invalid order confirmation, please check and try again or contact the seller to completed you order no.%s', 'tilopay'), $orderNumber) . ', order has status: ' . $order->get_status();
+ // Do not expose the order status to unverified requests
+ $get_traslate_message = sprintf(__('Invalid order confirmation, please check and try again or contact the seller to completed you order no.%s', 'tilopay'), absint($orderNumber));
//response api
return wp_send_json(array(
'code' => 400,
@@ -1676,6 +2054,14 @@
* Process to check if the payment was approved to pudate the order status payment.
*/
+ // Auth code already saved on the order (for example 'Pending' for PayCash)
+ if ($this->is_active_HPOS) {
+ // HPOS
+ $existing_auth_code = $order->get_meta('tilopay_auth_code', true);
+ } else {
+ $existing_auth_code = get_post_meta($wc_order_id, 'tilopay_auth_code', true);
+ }
+
if (1 == $code && !empty($responseJson->auth) && isset($responseJson->auth)) {
$auth = $responseJson->auth;
/**
@@ -1683,12 +2069,6 @@
* Process to pudate the order status payment.
*/
- if ($this->is_active_HPOS) {
- // HPOS
- $existing_auth_code = $order->get_meta('tilopay_auth_code', true);
- } else {
- $existing_auth_code = get_post_meta($auth, 'tilopay_auth_code', true);
- }
//check if order is pending || on-hold to update status
if (in_array($order->get_status(), ['on-hold']) && !empty($existing_auth_code) && 'Pending' == $existing_auth_code) {
@@ -1701,9 +2081,9 @@
update_post_meta($orderNumber, 'tilopay_auth_code', $auth);
}
// translators: %s action type.
- $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), 'PayCash') . $tpay_order_id);
- $order->add_order_note(__('Authorization:', 'tilopay') . $auth);
- $order->add_order_note(__('Code:', 'tilopay') . $code);
+ $order->add_order_note(sprintf(__('%s Tilopay id:', 'tilopay'), 'PayCash') . self::tpay_note_value($tpay_order_id));
+ $order->add_order_note(__('Authorization:', 'tilopay') . self::tpay_note_value($auth));
+ $order->add_order_note(__('Code:', 'tilopay') . self::tpay_note_value($code));
$order->add_order_note(__('Description:', 'tilopay') . __('Payment was successfully', 'tilopay'));
$order->save();
}
@@ -1715,9 +2095,19 @@
), 200);
exit;
} else if ('Pending' == $code) {
+ // An order already paid or closed is never changed by a Pending notification
+ if (!$check_unpaid_status) {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', Pending notification ignored, order already processed, order_id:' . $wc_order_id, 'info');
+ return wp_send_json(array(
+ 'code' => 200,
+ 'message' => 'Order already processed',
+ 'data' => null
+ ), 200);
+ exit;
+ }
if (empty($existing_auth_code)) {
//Update order status to pending
- $order->add_order_note(__('Code:', 'tilopay') . $code);
+ $order->add_order_note(__('Code:', 'tilopay') . self::tpay_note_value($code));
//Update order status
$order->set_status('wc-on-hold');
@@ -1733,9 +2123,19 @@
), 200);
exit;
} else {
+ // An order already paid or closed is never marked as failed (replayed or late notification)
+ if (!$check_unpaid_status) {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', failed notification ignored, order already processed, order_id:' . $wc_order_id, 'info');
+ return wp_send_json(array(
+ 'code' => 200,
+ 'message' => 'Order already processed',
+ 'data' => null
+ ), 200);
+ exit;
+ }
//The payment was not approved by Tilopay
$order->add_order_note(__('Order with failed payment', 'tilopay'));
- $order->add_order_note(__('Code:', 'tilopay') . $code);
+ $order->add_order_note(__('Code:', 'tilopay') . self::tpay_note_value($code));
//Update order status
$order->set_status('wc-failed');
@@ -1806,10 +2206,10 @@
$this->log(__METHOD__ . ':::' . __LINE__ . ', response error message: ' . $responseBodyError, 'error');
return false;
}
- $result = json_decode($response['body']);
+ $result = json_decode(wp_remote_retrieve_body($response));
if (isset($result->error)) {
- $this->log(__METHOD__ . ':::' . __LINE__ . ', response:' . print_r($response['body'], true), 'error');
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', response:' . print_r(wp_remote_retrieve_body($response), true), 'error');
return false;
}
@@ -1883,6 +2283,20 @@
$wooSessionTpay = ($order->get_order_key()) ? $order->get_order_key() : 'WOO-' . time();
$haveSubscription = (function_exists('wcs_order_contains_subscription') && wcs_order_contains_subscription($order));
}
+
+ // Native SINPE Móvil on the classic checkout: the SDK pays an order already created.
+ // Only for the owner of the order, send the signed return token and the lowercase email of the order.
+ $returnData = $this->id;
+ if (isset($_GET['process_payment'], $_GET['tlpy_payment_order']) && $this->id === sanitize_text_field(wp_unslash($_GET['process_payment']))) {
+ $sdk_order = wc_get_order(absint(wp_unslash($_GET['tlpy_payment_order'])));
+ if ($sdk_order && $this->id === $sdk_order->get_payment_method() && $sdk_order->needs_payment() && $this->tpay_current_visitor_owns_order($sdk_order)) {
+ $sdk_order_payment = $this->tpay_prepare_sdk_order_payment($sdk_order);
+ $returnData = $sdk_order_payment['returnData'];
+ $email_current_user = $sdk_order_payment['billToEmail'];
+ } else {
+ $this->log(__METHOD__ . ':::' . __LINE__ . ', SDK order payment without return token, order_id:' . absint(wp_unslash($_GET['tlpy_payment_order'])), 'info');
+ }
+ }
//should 32 characters
$wooSessionTpay = (strlen($wooSessionTpay) <= 25) ? $wooSessionTpay : substr($wooSessionTpay, 0, (25 - strlen($wooSessionTpay)));
@@ -1901,7 +2315,7 @@
'billToZipPostCode' => $billing_postcode_current_user,
'billToCountry' => $billing_country_current_user,
'billToTelephone' => $billing_phone_current_user,
- 'billToEmail' => $email_current_user,
+ 'billToEmail' => strtolower(trim($email_current_user)),
'orderNumber' => $orderNumber,
'capture' => 'yes' == $this->tpay_capture ? 1 : 0,
'redirect' => $this->tpay_checkout_redirect,
@@ -1920,7 +2334,7 @@
'hashVersion' => 'V2',
'haveSubscription' => $haveSubscription,
'wooSessionTpay' => $wooSessionTpay,
- 'returnData' => $this->id
+ 'returnData' => $returnData
);
}
@@ -1976,19 +2390,19 @@
// clean logs;
$cleanBodyRequest['paymentData'] = '...';
$cleanBodyRequest['expDate'] = '...';
- $cleanRequest['cvvEncrypted'] = '...';
+ $cleanBodyRequest['cvvEncrypted'] = '...';
$cleanBodyRequest['cvv'] = '...';
$cleanBodyRequest['card'] = '...';
if (is_wp_error($response)) {
//erros
- $responseBodyError = isset($response['body']) ? $response['body'] : '';
+ $responseBodyError = (is_wp_error($response) ? $response->get_error_message() : wp_remote_retrieve_body($response));
$this->log(__METHOD__ . ':::' . __LINE__ . ' response:' . print_r($responseBodyError, true) . ', request_data:' . print_r($cleanBodyRequest,