id = $this->get_gateway_id();
$this->method_title = $this->get_gateway_method_title();
$this->method_description = $this->get_gateway_method_description();
$this->supports_s2s = $this->gateway_supports_s2s();
$this->has_fields = false;
$this->supports = array( 'products' );
$this->icon = '';
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option( 'title', $this->get_default_checkout_title() );
$this->description = wp_kses_post( (string) $this->get_option( 'description', '' ) );
$this->enabled = $this->get_option( 'enabled', 'no' );
$this->mer_no = (string) $this->get_option( 'mer_no', '' );
$this->gateway_no = (string) $this->get_option( 'gateway_no', '' );
$this->sign_key = (string) $this->get_option( 'sign_key', '' );
$this->payment_center = (string) $this->get_option( 'payment_center', '' );
$this->payment_mode = $this->supports_s2s ? (string) $this->get_option( 'payment_mode', 'redirect' ) : 'redirect';
if ( ! in_array( $this->payment_mode, array( 'redirect', 's2s' ), true ) ) {
$this->payment_mode = 'redirect';
}
if ( ! $this->supports_s2s ) {
$this->payment_mode = 'redirect';
}
$this->has_fields = $this->supports_s2s && 's2s' === $this->payment_mode;
$this->redirect_payment_center = (string) $this->get_option( 'redirect_payment_center', '' );
$this->payment_method_logo_id = absint( $this->get_option( 'payment_method_logo_id', 0 ) );
$this->icon = $this->get_payment_method_logo_url();
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_api_' . $this->id, array( $this, 'handle_callback' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_checkout_assets' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
}
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'acquireros-payment-gateway' ),
'type' => 'checkbox',
// translators: %s is the AcquirerOS payment gateway name shown in WooCommerce settings.
'label' => sprintf( __( 'Enable %s', 'acquireros-payment-gateway' ), $this->get_gateway_method_title() ),
'default' => 'no',
),
'title' => array(
'title' => __( 'Checkout title', 'acquireros-payment-gateway' ),
'type' => 'text',
'default' => $this->get_default_checkout_title(),
'description' => __( 'Title shown to customers at checkout.', 'acquireros-payment-gateway' ),
),
'description' => array(
'title' => __( 'Checkout description', 'acquireros-payment-gateway' ),
'type' => 'checkout_description_editor',
'default' => '',
'description' => __( 'Optional. Default is empty. Add text, links or images from the WordPress Media Library. This content is displayed beneath the payment method at checkout.', 'acquireros-payment-gateway' ),
),
'payment_method_logo_id' => array(
'title' => __( 'Payment Method Logo', 'acquireros-payment-gateway' ),
'type' => 'payment_method_logo',
'default' => '',
'description' => __( 'Optional. Default is no logo. Upload an image to the WordPress Media Library and select it here to display next to this payment method at checkout. No third-party payment-brand artwork is bundled with this plugin.', 'acquireros-payment-gateway' ),
),
'mer_no' => array(
'title' => __( 'Merchant Number', 'acquireros-payment-gateway' ),
'type' => 'text',
'description' => __( 'Merchant identifier provided by AcquirerOS.', 'acquireros-payment-gateway' ),
),
'gateway_no' => array(
'title' => __( 'Gateway Number', 'acquireros-payment-gateway' ),
'type' => 'text',
'description' => __( 'Gateway identifier for this payment method.', 'acquireros-payment-gateway' ),
),
'sign_key' => array(
'title' => __( 'Signature Key', 'acquireros-payment-gateway' ),
'type' => 'password',
'description' => __( 'Secret key used to sign payment requests.', 'acquireros-payment-gateway' ),
),
);
if ( $this->gateway_supports_s2s() ) {
$this->form_fields['payment_mode'] = array(
'title' => __( 'Payment Mode', 'acquireros-payment-gateway' ),
'type' => 'select',
'default' => 'redirect',
'options' => array(
'redirect' => __( 'Redirect / Hosted Checkout (Recommended)', 'acquireros-payment-gateway' ),
's2s' => __( 'S2S / Direct API (Advanced)', 'acquireros-payment-gateway' ),
),
'description' => __( 'Hosted Checkout is recommended. S2S passes cardholder data through WooCommerce and should only be enabled for an appropriately compliant environment.', 'acquireros-payment-gateway' ),
);
$this->form_fields['payment_center'] = array(
'title' => __( 'Payment Gateway URL', 'acquireros-payment-gateway' ),
'type' => 'url',
'placeholder' => 'https://gateway.example.com/payment',
'description' => __( 'HTTPS API endpoint used by Credit Card S2S / Direct API. Hosted Checkout can use the separate URL below.', 'acquireros-payment-gateway' ),
);
$this->form_fields['redirect_payment_center'] = array(
'title' => __( 'Hosted Checkout URL', 'acquireros-payment-gateway' ),
'type' => 'url',
'placeholder' => 'https://gateway.example.com/checkout/create',
'description' => __( 'Hosted Checkout endpoint for Credit Card. Leave empty to reuse Payment Gateway URL.', 'acquireros-payment-gateway' ),
);
} else {
$this->form_fields['redirect_payment_center'] = array(
'title' => __( 'Hosted Checkout URL', 'acquireros-payment-gateway' ),
'type' => 'url',
'placeholder' => 'https://gateway.example.com/checkout/create',
'description' => __( 'Required HTTPS Hosted Checkout endpoint for this payment method.', 'acquireros-payment-gateway' ),
);
}
$this->form_fields['debug'] = array(
'title' => __( 'Logging', 'acquireros-payment-gateway' ),
'type' => 'checkbox',
'label' => __( 'Enable diagnostic logging', 'acquireros-payment-gateway' ),
'default' => 'no',
'description' => __( 'Logs status and request IDs only. Card numbers and CVV are never logged.', 'acquireros-payment-gateway' ),
);
}
/**
* Render Checkout description editor with Media Library image insertion.
/**
* Render Checkout description editor with Media Library image insertion.
*
* @param string $key Field key.
* @param array $data Field data.
* @return string
*/
public function generate_checkout_description_editor_html( $key, $data ) {
$field_key = $this->get_field_key( $key );
$value = (string) $this->get_option( $key, '' );
ob_start();
?>
payment_method_logo_id );
if ( ! $attachment_id || ! wp_attachment_is_image( $attachment_id ) ) {
return '';
}
$url = wp_get_attachment_image_url( $attachment_id, 'full' );
return is_string( $url ) ? esc_url_raw( $url ) : '';
}
/**
* Render the custom Media Library logo selector.
*
* @param string $key Field key.
* @param array $data Field data.
* @return string
*/
public function generate_payment_method_logo_html( $key, $data ) {
$field_key = $this->get_field_key( $key );
$attachment_id = absint( $this->get_option( $key, 0 ) );
$image_url = '';
if ( $attachment_id && wp_attachment_is_image( $attachment_id ) ) {
$url = wp_get_attachment_image_url( $attachment_id, 'medium' );
if ( is_string( $url ) ) {
$image_url = $url;
}
}
ob_start();
?>
id !== $section ) {
return;
}
wp_enqueue_media();
$file = ACQUIREROS_GATEWAY_PATH . 'assets/js/admin-payment-logo.js';
$ver = file_exists( $file ) ? (string) filemtime( $file ) : ACQUIREROS_GATEWAY_VERSION;
wp_enqueue_script(
'acquireros-admin-payment-logo',
ACQUIREROS_GATEWAY_URL . 'assets/js/admin-payment-logo.js',
array( 'jquery' ),
$ver,
true
);
wp_localize_script(
'acquireros-admin-payment-logo',
'acquirerosPaymentLogo',
array(
'title' => __( 'Select payment method logo', 'acquireros-payment-gateway' ),
'button' => __( 'Use this image', 'acquireros-payment-gateway' ),
'descriptionImageTitle' => __( 'Select checkout description image', 'acquireros-payment-gateway' ),
'descriptionImageButton' => __( 'Insert image', 'acquireros-payment-gateway' ),
)
);
}
public function admin_options() {
echo '' . esc_html__( 'AcquirerOS Payment Gateway', 'acquireros-payment-gateway' ) . ' ';
echo '' . esc_html__( 'Configure the credentials supplied by your AcquirerOS-compatible payment service.', 'acquireros-payment-gateway' ) . '
';
echo '' . esc_html__( 'Recommended:', 'acquireros-payment-gateway' ) . ' ' . esc_html__( 'Use Redirect / Hosted Checkout for the smallest card-data footprint. S2S / Direct API causes cardholder data to pass through the WordPress/WooCommerce server and should only be enabled after your payment provider and security/compliance advisers have confirmed that the integration is appropriate for your environment.', 'acquireros-payment-gateway' ) . '
';
parent::admin_options();
}
public function process_admin_options() {
$result = parent::process_admin_options();
$this->init_settings();
$endpoint = isset( $this->settings['payment_center'] ) ? esc_url_raw( (string) $this->settings['payment_center'] ) : '';
$redirect_endpoint = isset( $this->settings['redirect_payment_center'] ) ? esc_url_raw( (string) $this->settings['redirect_payment_center'] ) : '';
$mode = isset( $this->settings['payment_mode'] ) ? sanitize_key( (string) $this->settings['payment_mode'] ) : 'redirect';
$this->settings['payment_center'] = $endpoint;
$this->settings['redirect_payment_center'] = $redirect_endpoint;
$this->settings['payment_mode'] = in_array( $mode, array( 'redirect', 's2s' ), true ) ? $mode : 'redirect';
update_option( $this->get_option_key(), $this->settings );
return $result;
}
public function is_available() {
if ( ! parent::is_available() ) {
return false;
}
if ( empty( $this->mer_no ) || empty( $this->gateway_no ) || empty( $this->sign_key ) ) {
return false;
}
$endpoint = 'redirect' === $this->payment_mode ? ( $this->redirect_payment_center ?: $this->payment_center ) : $this->payment_center;
return $this->is_https_endpoint( $endpoint );
}
public function enqueue_checkout_assets() {
$description_css = '
.acquireros-checkout-description { margin-top: 10px; }
.acquireros-checkout-description p { margin: 0 0 8px; }
.acquireros-checkout-description img {
display: inline-block;
width: auto;
height: auto;
max-height: 28px;
max-width: 180px;
vertical-align: middle;
margin: 0 4px;
object-fit: contain;
}
.acquireros-checkout-description a img { vertical-align: middle; }
';
wp_register_style( 'acquireros-checkout-inline', false, array(), ACQUIREROS_GATEWAY_VERSION );
wp_enqueue_style( 'acquireros-checkout-inline' );
wp_add_inline_style( 'acquireros-checkout-inline', $description_css );
if ( ! function_exists( 'is_checkout' ) || ! is_checkout() ) {
return;
}
wp_enqueue_script(
'acquireros-gateway-checkout',
ACQUIREROS_GATEWAY_URL . 'assets/js/checkout-fields.js',
array( 'jquery' ),
ACQUIREROS_GATEWAY_VERSION,
true
);
}
public function payment_fields() {
$description = wp_kses_post( (string) $this->description );
$has_description = '' !== trim( wp_strip_all_tags( $description ) ) || false !== stripos( $description, ' supports_s2s || 's2s' !== $this->payment_mode ) {
if ( $has_description ) {
echo '';
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Sanitized with wp_kses_post() above.
echo wpautop( $description );
echo '
';
}
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce verifies the checkout request; this only repopulates checkout fields.
$card_number = isset( $_POST['acquireros_card_number'] ) ? sanitize_text_field( wp_unslash( $_POST['acquireros_card_number'] ) ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- WooCommerce verifies the checkout request; this only repopulates checkout fields.
$card_expiry = isset( $_POST['acquireros_card_expiry'] ) ? sanitize_text_field( wp_unslash( $_POST['acquireros_card_expiry'] ) ) : '';
echo '';
woocommerce_form_field(
'acquireros_card_number',
array(
'type' => 'text',
'label' => __( 'Card Number', 'acquireros-payment-gateway' ),
'required' => true,
'class' => array( 'form-row-wide' ),
'input_class' => array( 'input-text' ),
'autocomplete' => 'cc-number',
'custom_attributes' => array(
'inputmode' => 'numeric',
'maxlength' => '23',
),
),
$card_number
);
woocommerce_form_field(
'acquireros_card_expiry',
array(
'type' => 'text',
'label' => __( 'Expiry (MM/YY)', 'acquireros-payment-gateway' ),
'required' => true,
'class' => array( 'form-row-first' ),
'input_class' => array( 'input-text' ),
'placeholder' => 'MM/YY',
'autocomplete' => 'cc-exp',
'custom_attributes' => array(
'inputmode' => 'numeric',
'maxlength' => '5',
),
),
$card_expiry
);
woocommerce_form_field(
'acquireros_card_cvv',
array(
'type' => 'password',
'label' => __( 'Security Code', 'acquireros-payment-gateway' ),
'required' => true,
'class' => array( 'form-row-last' ),
'input_class' => array( 'input-text' ),
'autocomplete' => 'cc-csc',
'custom_attributes' => array(
'inputmode' => 'numeric',
'maxlength' => '4',
),
),
''
);
echo '
';
// Credit Card S2S: render the optional rich description after all card inputs.
if ( $has_description ) {
echo '';
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Sanitized with wp_kses_post() above.
echo wpautop( $description );
echo '
';
}
}
public function validate_fields() {
if ( ! $this->supports_s2s || 's2s' !== $this->payment_mode ) {
return true;
}
if ( 'redirect' === $this->payment_mode ) { return true; }
$card = preg_replace( '/\D+/', '', $this->post_value( 'acquireros_card_number', 'authorizepay_number' ) );
$expiry = trim( $this->post_value( 'acquireros_card_expiry', 'authorizepay_expires' ) );
$cvv = preg_replace( '/\D+/', '', $this->post_value( 'acquireros_card_cvv', 'authorizepay_checkcode' ) );
if ( ! preg_match( '/^\d{13,19}$/', $card ) || ! $this->valid_luhn( $card ) ) {
wc_add_notice( __( 'Please enter a valid card number.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
if ( ! preg_match( '/^(0[1-9]|1[0-2])\/(\d{2})$/', $expiry, $matches ) ) {
wc_add_notice( __( 'Please enter a valid card expiry date in MM/YY format.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
$month = (int) $matches[1];
$year = 2000 + (int) $matches[2];
$last_day = (int) gmdate( 't', gmmktime( 0, 0, 0, $month, 1, $year ) );
if ( gmmktime( 23, 59, 59, $month, $last_day, $year ) < time() ) {
wc_add_notice( __( 'The card has expired.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
if ( ! preg_match( '/^\d{3,4}$/', $cvv ) ) {
wc_add_notice( __( 'Please enter a valid card security code.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
return true;
}
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order ) {
wc_add_notice( __( 'Unable to load the order.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
if ( ! $this->validate_fields() ) {
return false;
}
$order_no = $this->generate_payment_order_no( $order );
$return_token = wp_generate_password( 48, false, false );
$notify_token = wp_generate_password( 48, false, false );
$order->update_meta_data( '_acquireros_order_no', $order_no );
$order->update_meta_data( '_acquireros_return_token', $return_token );
$order->update_meta_data( '_acquireros_notify_token', $notify_token );
$order->update_meta_data( '_acquireros_payment_mode', $this->payment_mode );
$order->update_meta_data( '_acquireros_gateway_id', $this->id );
$order->update_meta_data( '_acquireros_last_payment_order_no', $order_no );
$order->update_meta_data( '_acquireros_payment_attempt_count', (int) $order->get_meta( '_acquireros_payment_attempt_count', true ) + 1 );
$order->save();
if ( 'redirect' === $this->payment_mode ) {
$payload = $this->build_redirect_payload( $order, $order_no, $return_token, $notify_token );
$endpoint = $this->supports_s2s
? ( $this->redirect_payment_center ?: $this->payment_center )
: $this->redirect_payment_center;
} else {
$payload = $this->build_payload( $order, $order_no, $return_token, $notify_token );
$endpoint = $this->payment_center;
}
$response = $this->send_request( $payload, $order_id, $endpoint );
if ( is_wp_error( $response ) ) {
wc_add_notice( __( 'The payment service could not be reached. Please try again.', 'acquireros-payment-gateway' ), 'error' );
$this->log( 'Payment request failed: ' . $response->get_error_message(), $order_id );
return false;
}
$status = isset( $response['orderStatus'] ) ? (string) $response['orderStatus'] : '';
$redirect_url = $this->extract_redirect_url( $response );
$trade_no = isset( $response['tradeNo'] ) ? sanitize_text_field( (string) $response['tradeNo'] ) : '';
$message = isset( $response['orderInfo'] ) ? sanitize_text_field( (string) $response['orderInfo'] ) : '';
if ( $redirect_url ) { $order->update_status( 'pending', 'redirect' === $this->payment_mode ? __( 'Redirected to hosted checkout.', 'acquireros-payment-gateway' ) : __( 'Awaiting payment authentication.', 'acquireros-payment-gateway' ) ); $order->update_meta_data( '_acquireros_payment_mode', $this->payment_mode ); $order->save(); return array( 'result' => 'success', 'redirect' => $redirect_url ); }
if ( 'redirect' === $this->payment_mode ) { $order->update_status( 'failed', __( 'Hosted checkout did not return a redirect URL.', 'acquireros-payment-gateway' ) ); wc_add_notice( __( 'Unable to start the hosted payment page. Please try again.', 'acquireros-payment-gateway' ), 'error' ); return false; }
if ( '1' === $status ) {
if ( ! $order->is_paid() ) {
$order->payment_complete( $trade_no );
}
if ( WC()->cart ) {
WC()->cart->empty_cart();
}
return array( 'result' => 'success', 'redirect' => $this->get_return_url( $order ) );
}
$order->update_status( 'failed', $message ? $message : __( 'Payment failed.', 'acquireros-payment-gateway' ) );
wc_add_notice( $message ? $message : __( 'Payment failed. Please try another payment method.', 'acquireros-payment-gateway' ), 'error' );
return false;
}
private function build_payload( WC_Order $order, $order_no, $return_token, $notify_token ) {
$card = preg_replace( '/\D+/', '', $this->post_value( 'acquireros_card_number', 'authorizepay_number' ) );
$expiry = trim( $this->post_value( 'acquireros_card_expiry', 'authorizepay_expires' ) );
$cvv = preg_replace( '/\D+/', '', $this->post_value( 'acquireros_card_cvv', 'authorizepay_checkcode' ) );
list( $exp_month, $short_year ) = explode( '/', $expiry );
$exp_year = '20' . $short_year;
$amount = number_format( (float) $order->get_total(), 2, '.', '' );
$currency = (string) $order->get_currency();
$first = $order->get_shipping_first_name() ?: $order->get_billing_first_name();
$last = $order->get_shipping_last_name() ?: $order->get_billing_last_name();
$callback_base = WC()->api_request_url( $this->id );
$return_url = add_query_arg( array( 'type' => 'return', 'order_id' => $order->get_id(), 'token' => $return_token ), $callback_base );
$notify_url = add_query_arg( array( 'type' => 'notify', 'order_id' => $order->get_id(), 'token' => $notify_token ), $callback_base );
$goods = array();
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
$goods[] = array(
'gdNo' => $product ? (string) $product->get_id() : '',
'gdName' => $product ? (string) $product->get_name() : (string) $item->get_name(),
'gdPrice' => number_format( (float) $order->get_item_total( $item, false, false ), 2, '.', '' ),
'gdQty' => (int) $item->get_quantity(),
);
}
$sign_info = hash(
'sha256',
$this->mer_no . $this->gateway_no . $order_no . $currency . $amount . $first . $last . $card . $exp_year . $exp_month . $cvv . $order->get_billing_email() . $this->sign_key
);
$payload = array(
'merNo' => $this->mer_no,
'gatewayNo' => $this->gateway_no,
'orderNo' => $order_no,
'orderCurrency' => $currency,
'orderAmount' => $amount,
'returnUrl' => $return_url,
'notifyUrl' => $notify_url,
'cardExpireMonth' => $exp_month,
'cardExpireYear' => $exp_year,
'signInfo' => strtoupper( $sign_info ),
'website' => home_url( '/' ),
'webSite' => home_url( '/' ),
'firstName' => (string) $first,
'lastName' => (string) $last,
'cardHolderName' => trim( $first . ' ' . $last ),
'email' => (string) $order->get_billing_email(),
'ip' => $this->client_ip(),
'phone' => (string) $order->get_billing_phone(),
'goodsInfoList' => $goods,
'country' => (string) ( $order->get_shipping_country() ?: $order->get_billing_country() ),
'state' => (string) ( $order->get_shipping_state() ?: $order->get_billing_state() ),
'city' => (string) ( $order->get_shipping_city() ?: $order->get_billing_city() ),
'address' => trim( ( $order->get_shipping_address_1() ?: $order->get_billing_address_1() ) . ' ' . ( $order->get_shipping_address_2() ?: $order->get_billing_address_2() ) ),
'zip' => (string) ( $order->get_shipping_postcode() ?: $order->get_billing_postcode() ),
'resolution' => $this->post_value( 'acquireros_resolution', 'browserResolution' ),
'javascriptEnabled' => true,
'userAgent' => $this->server_value( 'HTTP_USER_AGENT' ),
'browserLang' => $this->server_value( 'HTTP_ACCEPT_LANGUAGE' ),
'colorDepth' => $this->post_value( 'acquireros_color_depth', 'browserColorDepth' ),
'acceptHeader' => $this->server_value( 'HTTP_ACCEPT' ),
'shipFirstName' => (string) $first,
'shipLastName' => (string) $last,
'shipEmail' => (string) $order->get_billing_email(),
'shipPhone' => (string) $order->get_billing_phone(),
'shipCountry' => (string) ( $order->get_shipping_country() ?: $order->get_billing_country() ),
'shipState' => (string) ( $order->get_shipping_state() ?: $order->get_billing_state() ),
'shipCity' => (string) ( $order->get_shipping_city() ?: $order->get_billing_city() ),
'shipAddress' => trim( ( $order->get_shipping_address_1() ?: $order->get_billing_address_1() ) . ' ' . ( $order->get_shipping_address_2() ?: $order->get_billing_address_2() ) ),
'shipZip' => (string) ( $order->get_shipping_postcode() ?: $order->get_billing_postcode() ),
'os' => $this->detect_os(),
'timezone' => $this->post_value( 'acquireros_timezone', 'browserTimezone' ) ?: '0',
'cardNo' => $card,
'cardSecurityCode' => $cvv,
'brower' => $this->server_value( 'HTTP_USER_AGENT' ),
'browerLang' => $this->server_value( 'HTTP_ACCEPT_LANGUAGE' ),
);
return $payload;
}
private function build_redirect_payload( WC_Order $order, $order_no, $return_token, $notify_token ) {
$amount = number_format( (float) $order->get_total(), 2, '.', '' );
$currency = (string) $order->get_currency();
$first = $order->get_shipping_first_name() ?: $order->get_billing_first_name();
$last = $order->get_shipping_last_name() ?: $order->get_billing_last_name();
$callback_base = WC()->api_request_url( $this->id );
$return_url = add_query_arg(
array( 'type' => 'return', 'order_id' => $order->get_id(), 'token' => $return_token ),
$callback_base
);
$notify_url = add_query_arg(
array( 'type' => 'notify', 'order_id' => $order->get_id(), 'token' => $notify_token ),
$callback_base
);
$goods = array();
foreach ( $order->get_items() as $item_id => $item ) {
if ( ! is_a( $item, 'WC_Order_Item_Product' ) ) {
continue;
}
$product = $item->get_product();
$quantity = max( 1, (int) $item->get_quantity() );
$total = (float) $item->get_total();
$unit = $total > 0 ? ( $total / $quantity ) : ( $product ? (float) $product->get_price() : 0 );
$goods[] = array(
'gdNo' => $this->generate_goods_no( $order->get_id(), $item_id, $order_no ),
'gdName' => mb_substr( wp_strip_all_tags( $product ? $product->get_name() : $item->get_name() ), 0, 128 ),
'gdPrice' => number_format( $unit, 2, '.', '' ),
'gdQty' => (string) $quantity,
);
}
// Hosted Checkout signature rule from the proven legacy implementation:
// merNo + gatewayNo + orderNo + orderCurrency + orderAmount + returnUrl + signKey
$sign_raw = $this->mer_no
. $this->gateway_no
. $order_no
. $currency
. $amount
. $return_url
. $this->sign_key;
$country = (string) ( $order->get_shipping_country() ?: $order->get_billing_country() );
$state = (string) ( $order->get_shipping_state() ?: $order->get_billing_state() );
$city = (string) ( $order->get_shipping_city() ?: $order->get_billing_city() );
$address = trim( ( $order->get_shipping_address_1() ?: $order->get_billing_address_1() ) . ' ' . ( $order->get_shipping_address_2() ?: $order->get_billing_address_2() ) );
$zip = (string) ( $order->get_shipping_postcode() ?: $order->get_billing_postcode() );
$email = (string) $order->get_billing_email();
$phone = (string) $order->get_billing_phone();
$ua = $this->server_value( 'HTTP_USER_AGENT' );
$lang = $this->server_value( 'HTTP_ACCEPT_LANGUAGE' );
$payload = array(
'merNo' => $this->mer_no,
'gatewayNo' => $this->gateway_no,
'orderNo' => $order_no,
'orderCurrency' => $currency,
'orderAmount' => $amount,
'returnUrl' => $return_url,
'notifyUrl' => $notify_url,
'goodsInfoList' => $goods,
'signInfo' => strtoupper( hash( 'sha256', $sign_raw ) ),
'website' => home_url( '/' ),
'webSite' => home_url( '/' ),
'firstName' => (string) $first,
'lastName' => (string) $last,
'email' => $email,
'ip' => $this->client_ip(),
'phone' => $phone,
'country' => $country,
'state' => $state,
'city' => $city,
'address' => $address,
'zip' => $zip,
'resolution' => $this->post_value( 'acquireros_resolution', 'browserResolution' ),
'javascriptEnabled' => true,
'userAgent' => $ua,
'browser' => $ua,
'browserLang' => $lang,
'colorDepth' => $this->post_value( 'acquireros_color_depth', 'browserColorDepth' ),
'acceptHeader' => $this->server_value( 'HTTP_ACCEPT' ) ?: 'application/json, */*;q=0.8',
'timezone' => $this->post_value( 'acquireros_timezone', 'browserTimezone' ) ?: (string) (float) get_option( 'gmt_offset', 0 ),
'os' => $this->detect_os(),
'shipFirstName' => (string) $first,
'shipLastName' => (string) $last,
'shipEmail' => $email,
'shipPhone' => $phone,
'shipCountry' => $country,
'shipState' => $state,
'shipCity' => $city,
'shipAddress' => $address,
'shipZip' => $zip,
);
return $payload;
}
private function generate_payment_order_no( WC_Order $order ) {
try {
$rand = strtoupper( bin2hex( random_bytes( 3 ) ) );
} catch ( Exception $e ) {
$rand = (string) wp_rand( 100000, 999999 );
}
return 'WP' . gmdate( 'YmdHis' ) . $order->get_id() . $rand;
}
private function generate_goods_no( $order_id, $item_id, $payment_order_no = '' ) {
try {
$rand = strtoupper( bin2hex( random_bytes( 3 ) ) );
} catch ( Exception $e ) {
$rand = (string) wp_rand( 100000, 999999 );
}
$base = 'G-' . absint( $order_id ) . '-' . absint( $item_id ) . '-' . $rand;
if ( $payment_order_no ) {
$base .= '-' . strtoupper( substr( md5( $payment_order_no ), 0, 8 ) );
}
return $base;
}
private function extract_redirect_url( array $response ) {
foreach(array('redirectUrl','checkoutUrl','payUrl','url') as $key){if(!empty($response[$key])&&is_string($response[$key])){$url=esc_url_raw($response[$key]);if(0===stripos($url,'https://'))return $url;}}
if(isset($response['data'])&&is_array($response['data'])){foreach(array('redirectUrl','checkoutUrl','payUrl','url') as $key){if(!empty($response['data'][$key])&&is_string($response['data'][$key])){$url=esc_url_raw($response['data'][$key]);if(0===stripos($url,'https://'))return $url;}}}
return '';
}
private function send_request( array $payload, $order_id, $endpoint = '' ) {
if ( '' === $endpoint && $this->supports_s2s ) {
$endpoint = $this->payment_center;
}
if ( ! $this->is_https_endpoint( $endpoint ) ) {
return new WP_Error( 'acquireros_invalid_endpoint', __( 'The configured payment endpoint is not a valid public HTTPS URL.', 'acquireros-payment-gateway' ) );
}
$this->log( 'Starting payment request.', $order_id );
$response = wp_safe_remote_post(
$endpoint,
array(
'timeout' => 45,
'redirection' => 0,
'headers' => array( 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json' ),
'body' => wp_json_encode( $payload ),
'data_format' => 'body',
)
);
if ( is_wp_error( $response ) ) {
return $response;
}
$code = (int) wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
$this->log( 'Gateway HTTP status ' . $code . '.', $order_id );
if ( $code < 200 || $code >= 300 ) {
return new WP_Error( 'acquireros_http_error', sprintf( 'HTTP %d', $code ) );
}
$data = json_decode( $body, true );
if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $data ) ) {
return new WP_Error( 'acquireros_invalid_json', 'Invalid JSON response.' );
}
$this->log( 'Gateway response received.', $order_id );
return $data;
}
public function handle_callback() {
$order_id = absint( $this->request_value( 'order_id' ) );
$type = sanitize_key( $this->request_value( 'type' ) );
$token = $this->request_value( 'token' );
$order = $order_id ? wc_get_order( $order_id ) : false;
if ( ! $order || ! in_array( $type, array( 'return', 'notify' ), true ) ) {
$this->callback_fail( $type, __( 'Invalid callback.', 'acquireros-payment-gateway' ), 400 );
}
$method = strtoupper( $this->server_value( 'REQUEST_METHOD' ) );
if ( ( 'notify' === $type && 'POST' !== $method ) || ( 'return' === $type && ! in_array( $method, array( 'GET', 'POST' ), true ) ) ) {
$this->callback_fail( $type, __( 'Invalid callback method.', 'acquireros-payment-gateway' ), 405 );
}
$expected = (string) $order->get_meta( 'notify' === $type ? '_acquireros_notify_token' : '_acquireros_return_token', true );
if ( '' === $expected || '' === $token || ! hash_equals( $expected, $token ) ) {
$this->log( 'Rejected callback with invalid token.', $order_id );
$this->callback_fail( $type, __( 'Invalid callback token.', 'acquireros-payment-gateway' ), 403 );
}
$payload = $this->callback_payload();
if ( isset( $payload['order_info'] ) && is_string( $payload['order_info'] ) && '' !== $payload['order_info'] ) {
$decoded = $this->decrypt_callback( $payload['order_info'] );
if ( is_array( $decoded ) ) {
$payload = array_merge( $payload, $decoded );
}
}
if ( ! $this->verify_callback_signature( $payload, 'notify' === $type ) ) {
$this->log( 'Rejected callback with invalid signature.', $order_id );
$this->callback_fail( $type, __( 'Invalid callback signature.', 'acquireros-payment-gateway' ), 403 );
}
$gateway_order_no = isset( $payload['orderNo'] ) ? sanitize_text_field( (string) $payload['orderNo'] ) : '';
$stored_order_no = (string) $order->get_meta( '_acquireros_order_no', true );
if ( '' === $gateway_order_no || '' === $stored_order_no || ! hash_equals( $stored_order_no, $gateway_order_no ) ) {
$this->log( 'Rejected callback with mismatched order number.', $order_id );
$this->callback_fail( $type, __( 'Order mismatch.', 'acquireros-payment-gateway' ), 400 );
}
if ( ! $this->callback_matches_order( $payload, $order ) ) {
$this->log( 'Rejected callback with mismatched merchant, gateway, amount or currency.', $order_id );
$this->callback_fail( $type, __( 'Callback data mismatch.', 'acquireros-payment-gateway' ), 400 );
}
$status = isset( $payload['orderStatus'] ) ? sanitize_text_field( (string) $payload['orderStatus'] ) : '';
$trade_no = isset( $payload['tradeNo'] ) ? sanitize_text_field( (string) $payload['tradeNo'] ) : '';
$message = isset( $payload['orderInfo'] ) ? sanitize_text_field( (string) $payload['orderInfo'] ) : '';
if ( $trade_no ) {
$order->update_meta_data( '_acquireros_trade_no', $trade_no );
}
if ( '1' === $status ) {
if ( ! $order->is_paid() ) {
$order->payment_complete( $trade_no );
}
} elseif ( ! $order->is_paid() ) {
$order->update_status( 'failed', $message ? $message : __( 'Payment failed.', 'acquireros-payment-gateway' ) );
}
$order->save();
$this->log( 'Validated callback processed with status ' . $status . '.', $order_id );
if ( 'notify' === $type ) {
wp_send_json( array( 'respCode' => '0000', 'respMsg' => 'success' ), 200 );
}
if ( '1' === $status ) {
wp_safe_redirect( $order->get_checkout_order_received_url() );
exit;
}
wc_add_notice( $message ? $message : __( 'Payment failed.', 'acquireros-payment-gateway' ), 'error' );
wp_safe_redirect( wc_get_checkout_url() );
exit;
}
private function callback_payload() {
$raw = file_get_contents( 'php://input' );
if ( is_string( $raw ) && '' !== trim( $raw ) ) {
$json = json_decode( $raw, true );
if ( JSON_ERROR_NONE === json_last_error() && is_array( $json ) ) {
return $json;
}
}
$payload = array();
foreach ( array( 'merNo', 'gatewayNo', 'tradeNo', 'orderNo', 'orderCurrency', 'orderAmount', 'orderStatus', 'orderErrorCode', 'orderInfo', 'signInfo', 'returnType', 'order_info' ) as $key ) {
$value = $this->request_value( $key );
if ( '' !== $value ) {
$payload[ $key ] = $value;
}
}
return $payload;
}
private function verify_callback_signature( array $payload, $require_signature = false ) {
$received = isset( $payload['signInfo'] ) ? strtoupper( trim( (string) $payload['signInfo'] ) ) : '';
if ( '' === $received ) {
return ! $require_signature;
}
$fields = array( 'merNo', 'gatewayNo', 'tradeNo', 'orderNo', 'orderCurrency', 'orderAmount', 'orderStatus', 'orderInfo' );
$raw = '';
foreach ( $fields as $field ) {
$value = isset( $payload[ $field ] ) ? (string) $payload[ $field ] : '';
if ( 'null' === strtolower( trim( $value ) ) ) {
$value = '';
}
$raw .= $value;
}
$expected = strtoupper( hash( 'sha256', $raw . $this->sign_key ) );
if ( hash_equals( $expected, $received ) ) {
return true;
}
// Compatibility fallback: preserve literal "null" if the upstream signed it that way.
$raw = '';
foreach ( $fields as $field ) {
$raw .= isset( $payload[ $field ] ) ? (string) $payload[ $field ] : '';
}
$expected_raw = strtoupper( hash( 'sha256', $raw . $this->sign_key ) );
return hash_equals( $expected_raw, $received );
}
private function callback_matches_order( array $payload, WC_Order $order ) {
if ( isset( $payload['merNo'] ) && '' !== (string) $payload['merNo'] && ! hash_equals( $this->mer_no, (string) $payload['merNo'] ) ) {
return false;
}
if ( isset( $payload['gatewayNo'] ) && '' !== (string) $payload['gatewayNo'] && ! hash_equals( $this->gateway_no, (string) $payload['gatewayNo'] ) ) {
return false;
}
if ( isset( $payload['orderCurrency'] ) && '' !== (string) $payload['orderCurrency'] && strtoupper( (string) $payload['orderCurrency'] ) !== strtoupper( (string) $order->get_currency() ) ) {
return false;
}
if ( isset( $payload['orderAmount'] ) && '' !== (string) $payload['orderAmount'] ) {
$expected = number_format( (float) $order->get_total(), 2, '.', '' );
$received = number_format( (float) $payload['orderAmount'], 2, '.', '' );
if ( ! hash_equals( $expected, $received ) ) {
return false;
}
}
return true;
}
private function is_https_endpoint( $url ) {
$url = esc_url_raw( (string) $url );
if ( ! $url || 'https' !== strtolower( (string) wp_parse_url( $url, PHP_URL_SCHEME ) ) ) {
return false;
}
$host = (string) wp_parse_url( $url, PHP_URL_HOST );
if ( '' === $host || 'localhost' === strtolower( $host ) || filter_var( $host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) === false && filter_var( $host, FILTER_VALIDATE_IP ) ) {
return false;
}
return true;
}
private function decrypt_callback( $encoded ) {
$binary = base64_decode( $encoded, true );
if ( false === $binary ) {
return false;
}
$decrypted = openssl_decrypt( $binary, 'AES-128-ECB', $this->sign_key . $this->sign_key, OPENSSL_RAW_DATA );
if ( false === $decrypted || '' === $decrypted ) {
$decrypted = openssl_decrypt( $binary, 'AES-128-ECB', $this->sign_key . $this->sign_key, 0 );
}
if ( false === $decrypted || '' === $decrypted ) {
return false;
}
$data = json_decode( $decrypted, true );
return ( JSON_ERROR_NONE === json_last_error() && is_array( $data ) ) ? $data : false;
}
private function callback_fail( $type, $message, $status ) {
if ( 'notify' === $type ) {
wp_send_json( array( 'respCode' => '9999', 'respMsg' => $message ), $status );
}
wp_die( esc_html( $message ), esc_html__( 'Payment callback error', 'acquireros-payment-gateway' ), array( 'response' => absint( $status ) ) );
}
private function post_value( $primary, $legacy = '' ) {
// WooCommerce verifies the checkout nonce before gateway payment fields are processed.
$key = isset( $_POST[ $primary ] ) ? $primary : $legacy; // phpcs:ignore WordPress.Security.NonceVerification.Missing
if ( ! $key || ! isset( $_POST[ $key ] ) || ! is_string( $_POST[ $key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
return '';
}
return sanitize_text_field( wp_unslash( $_POST[ $key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
}
private function request_value( $key ) {
// External callbacks cannot use a WordPress nonce. Authentication is
// provided by the per-order callback token and gateway signature.
if ( isset( $_POST[ $key ] ) && is_string( $_POST[ $key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
return sanitize_text_field( wp_unslash( $_POST[ $key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
}
if ( isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return sanitize_text_field( wp_unslash( $_GET[ $key ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
return '';
}
private function server_value( $key ) {
if ( ! isset( $_SERVER[ $key ] ) || ! is_string( $_SERVER[ $key ] ) ) {
return '';
}
return sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) );
}
private function client_ip() {
$ip = $this->server_value( 'REMOTE_ADDR' );
return filter_var( $ip, FILTER_VALIDATE_IP ) ? $ip : '';
}
private function detect_os() {
$ua = strtolower( $this->server_value( 'HTTP_USER_AGENT' ) );
if ( false !== strpos( $ua, 'iphone' ) || false !== strpos( $ua, 'ipad' ) ) { return 'iOS'; }
if ( false !== strpos( $ua, 'android' ) ) { return 'Android'; }
if ( false !== strpos( $ua, 'windows' ) ) { return 'Windows'; }
if ( false !== strpos( $ua, 'macintosh' ) || false !== strpos( $ua, 'mac os x' ) ) { return 'Mac'; }
if ( false !== strpos( $ua, 'linux' ) ) { return 'Linux'; }
return 'Unknown OS';
}
private function valid_luhn( $number ) {
$sum = 0;
$alt = false;
for ( $i = strlen( $number ) - 1; $i >= 0; $i-- ) {
$n = (int) $number[ $i ];
if ( $alt ) {
$n *= 2;
if ( $n > 9 ) { $n -= 9; }
}
$sum += $n;
$alt = ! $alt;
}
return 0 === $sum % 10;
}
private function log( $message, $order_id = 0 ) {
if ( 'yes' !== $this->get_option( 'debug', 'no' ) ) {
return;
}
$prefix = $order_id ? '[order:' . absint( $order_id ) . '] ' : '';
wc_get_logger()->info( $prefix . sanitize_text_field( $message ), array( 'source' => self::LOG_SOURCE ) );
}
}
class AcquirerOS_WC_Gateway_PayPal extends AcquirerOS_WC_Gateway_Credit_Card {
protected function get_gateway_id() { return 'acquireros_paypal'; }
protected function get_gateway_method_title() { return __( 'AcquirerOS - PayPal', 'acquireros-payment-gateway' ); }
protected function get_gateway_method_description() { return __( 'Offer PayPal through an AcquirerOS Hosted Checkout integration.', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_title() { return __( 'PayPal', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_description() { return ''; }
protected function gateway_supports_s2s() { return false; }
}
class AcquirerOS_WC_Gateway_Apple_Pay extends AcquirerOS_WC_Gateway_Credit_Card {
protected function get_gateway_id() { return 'acquireros_apple_pay'; }
protected function get_gateway_method_title() { return __( 'AcquirerOS - Apple Pay', 'acquireros-payment-gateway' ); }
protected function get_gateway_method_description() { return __( 'Offer Apple Pay through an AcquirerOS Hosted Checkout integration.', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_title() { return __( 'Apple Pay', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_description() { return ''; }
protected function gateway_supports_s2s() { return false; }
}
class AcquirerOS_WC_Gateway_Google_Pay extends AcquirerOS_WC_Gateway_Credit_Card {
protected function get_gateway_id() { return 'acquireros_google_pay'; }
protected function get_gateway_method_title() { return __( 'AcquirerOS - Google Pay', 'acquireros-payment-gateway' ); }
protected function get_gateway_method_description() { return __( 'Offer Google Pay through an AcquirerOS Hosted Checkout integration.', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_title() { return __( 'Google Pay', 'acquireros-payment-gateway' ); }
protected function get_default_checkout_description() { return ''; }
protected function gateway_supports_s2s() { return false; }
}
// Backward-compatibility aliases for versions prior to 2.3.5 Plugin Check cleanup.
if ( class_exists( 'AcquirerOS_WC_Gateway_Credit_Card' ) && ! class_exists( 'WC_Gateway_AcquirerOS', false ) ) {
class_alias( 'AcquirerOS_WC_Gateway_Credit_Card', 'WC_Gateway_AcquirerOS' );
}
if ( class_exists( 'AcquirerOS_WC_Gateway_PayPal' ) && ! class_exists( 'WC_Gateway_AcquirerOS_PayPal', false ) ) {
class_alias( 'AcquirerOS_WC_Gateway_PayPal', 'WC_Gateway_AcquirerOS_PayPal' );
}
if ( class_exists( 'AcquirerOS_WC_Gateway_Apple_Pay' ) && ! class_exists( 'WC_Gateway_AcquirerOS_Apple_Pay', false ) ) {
class_alias( 'AcquirerOS_WC_Gateway_Apple_Pay', 'WC_Gateway_AcquirerOS_Apple_Pay' );
}
if ( class_exists( 'AcquirerOS_WC_Gateway_Google_Pay' ) && ! class_exists( 'WC_Gateway_AcquirerOS_Google_Pay', false ) ) {
class_alias( 'AcquirerOS_WC_Gateway_Google_Pay', 'WC_Gateway_AcquirerOS_Google_Pay' );
}