log($level, $message, array('source' => 'woocommerce-alatpay')); } if (function_exists('error_log')) { error_log('[ALATPay] ' . $message); } } } if (! function_exists('alatpay_transaction_log')) { /** * Log payment transaction events in a dedicated WooCommerce log. * * @param string $level Log level, e.g. info, warning. * @param string $message Message to log. * @param array $context Optional context passed to the logger. * @return void */ function alatpay_transaction_log($level, $message, $context = array()) { if (function_exists('wc_get_logger')) { $logger_context = array_merge(array('source' => 'woocommerce-alatpay-payments'), $context); wc_get_logger()->log($level, $message, $logger_context); } if (function_exists('error_log')) { error_log('[ALATPay][Txn] ' . $message); } } } if (! function_exists('alatpay_add_success_note_if_needed')) { /** * Attach a single success note to an order. * * @param mixed $order WooCommerce order instance. * @return bool True when meta updates are pending a save. */ function alatpay_add_success_note_if_needed($order) { if (! ($order instanceof WC_Order)) { return false; } if ('yes' === $order->get_meta('_alatpay_success_note_added')) { return false; } $order->add_order_note(__('Payment received via ALATPay (Success).', 'alatpay')); $order->update_meta_data('_alatpay_success_note_added', 'yes'); return true; } } if (! function_exists('alatpay_add_initiated_note_if_needed')) { /** * Attach a single note when checkout is initiated. * * @param mixed $order WooCommerce order instance. * @return bool True when meta updates are pending a save. */ function alatpay_add_initiated_note_if_needed($order) { if (! ($order instanceof WC_Order)) { return false; } if ('yes' === $order->get_meta('_alatpay_initiated_note_added')) { return false; } $order->add_order_note(__('Customer clicked "Pay with ALATPay". Awaiting payment confirmation.', 'alatpay')); $order->update_meta_data('_alatpay_initiated_note_added', 'yes'); return true; } } if (! function_exists('alatpay_add_failure_note_if_needed')) { /** * Attach a single failure note to an order. * * @param mixed $order WooCommerce order instance. * @return bool True when meta updates are pending a save. */ function alatpay_add_failure_note_if_needed($order) { if (! ($order instanceof WC_Order)) { return false; } if ('yes' === $order->get_meta('_alatpay_failure_note_added')) { return false; } $order->add_order_note(__('Payment failed via ALATPay (Failed).', 'alatpay')); $order->update_meta_data('_alatpay_failure_note_added', 'yes'); return true; } } add_filter('woocommerce_payment_gateways', 'alatpay_add'); add_action('woocommerce_receipt_alatpay', 'alatpay_payment_page', 10, 1); function alatpay_add($gateways) { $gateways[] = 'Alatpay_Payment_Gateway'; return $gateways; } /** * Custom function to declare compatibility with cart_checkout_blocks feature */ function alatpay_checkout_blocks_compatibility() { // Check if the required class exists if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) { // Declare compatibility for 'cart_checkout_blocks' \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true); } } // Hook the custom function to the 'before_woocommerce_init' action add_action('before_woocommerce_init', 'alatpay_checkout_blocks_compatibility'); // Hook the custom function to the 'woocommerce_blocks_loaded' action add_action('woocommerce_blocks_loaded', 'alatpay_register_order_approval_payment_method_type'); /** * Custom function to register a payment method type */ function alatpay_register_order_approval_payment_method_type() { // Check if the required class exists if (! class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) { return; } // Include the custom Blocks Checkout class require_once plugin_dir_path(__FILE__) . 'class-gateway-alatpay-block.php'; // Hook the registration function to the 'woocommerce_blocks_payment_method_type_registration' action add_action( 'woocommerce_blocks_payment_method_type_registration', function (Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry $payment_method_registry) { // Register an instance of Alatpay_Payment_Gateway_Blocks $payment_method_registry->register(new Alatpay_Payment_Gateway_Blocks); } ); } add_action('rest_api_init', 'alatpay_register_webhook'); function alatpay_register_webhook() { register_rest_route('alatpay/v1', '/webhook', array( 'methods' => 'POST', 'callback' => 'alatpay_handle_webhook', 'permission_callback' => '__return_true' )); } function alatpay_handle_webhook($request) { // Get the signature from the request header $signature = $request->get_header('x-signature'); // If the signature is not present, return an error if (! $signature) { alatpay_log('error', 'Missing signature. Contact ALATPay support.'); return new WP_Error('unauthorized', 'Missing signature', array('status' => 401)); } // Get the request body $body = $request->get_body(); // Get the webhook secret from the gateway settings $gateway = new Alatpay_Payment_Gateway(); $secret_key = $gateway->get_option('webhook_secret'); // If the secret key is not set, return an error if (empty($secret_key)) { alatpay_log('error', 'Webhook secret is not configured.'); return new WP_Error('unauthorized', 'Webhook secret is not configured', array('status' => 401)); } // Calculate the HMAC-SHA256 signature of the request body $calculated_signature = hash_hmac('sha256', $body, $secret_key, true); $calculated_signature_base64 = base64_encode($calculated_signature); // Compare the calculated signature with the one from the request if (! hash_equals($calculated_signature_base64, $signature)) { alatpay_log('error', 'Invalid signature. Contact ALATPay support.'); return new WP_Error( 'unauthorized', 'Invalid signature', array('status' => 401) ); } $params = json_decode($body, true); if (! is_array($params)) { alatpay_log('error', 'Invalid request. Contact ALATPay support.'); return new WP_Error('bad_request', 'Invalid request', array('status' => 400)); } $status = strtolower($params['Value']['Data']['Status'] ?? ''); if ($status !== 'completed') { alatpay_log('error', 'Invalid status. Contact ALATPay support.'); return new WP_Error('bad_request', 'Invalid status', array('status' => 400)); } // error_log('ALATPay Webhook Request: ' . print_r($params, true)); alatpay_log('info', 'ALATPay Webhook Request: ' . print_r($params, true)); $metadata_json = $params['Value']['Data']['Customer']['Metadata'] ?? '{}'; $metadata = json_decode($metadata_json, true); $payment_order_id = intval($metadata['order_id'] ?? 0); if (! isset($payment_order_id) || $payment_order_id <= 0) { return new WP_Error('bad_request', 'Missing order_id', array('status' => 400)); } $order = wc_get_order($payment_order_id); if (! $order) { return new WP_Error('not_found', 'Order not found', array('status' => 404)); } $order_currency = $order->get_currency(); $payment_currency = $params['Value']['Data']['Currency']; if ($order_currency !== $payment_currency) { return new WP_Error('currency_mismatch', 'Order currency mismatch', array('status' => 400)); } $transaction_id = sanitize_text_field($params['Value']['Data']['Customer']['TransactionId'] ?? ''); $amount = isset($params['Value']['Data']['Amount']) ? floatval($params['Value']['Data']['Amount']) : 0.0; $needs_save = false; if (! empty($transaction_id)) { $order->set_transaction_id($transaction_id); $order->add_order_note(sprintf('ALATPay transaction ID: %s', $transaction_id)); $needs_save = true; } if (alatpay_add_success_note_if_needed($order)) { $needs_save = true; } if ($needs_save) { $order->save(); } alatpay_transaction_log( 'info', sprintf( 'Webhook completed order %d. Amount: %s %s. Transaction ID: %s.', $payment_order_id, number_format($amount, 2, '.', ''), $payment_currency, $transaction_id ? $transaction_id : 'N/A' ), array( 'order_id' => $payment_order_id, 'transaction_id' => $transaction_id, 'amount' => $amount, 'currency' => $payment_currency, 'event' => 'webhook_completed', ) ); // Only update the status if the order is not already completed if (! $order->has_status('completed')) { $order->update_status('completed', __('Payment received via ALATPay webhook.', 'alatpay')); } return new WP_REST_Response(array('status' => 'success'), 200); } function alatpay_payment_page($order_id) { $order = wc_get_order($order_id); if (! $order) { wp_safe_redirect(wc_get_checkout_url() . '?result=fail'); exit; } $gateway = new Alatpay_Payment_Gateway(); $api_key = $gateway->get_option('api_key'); $business_id = $gateway->get_option('business_id'); $auto_complete_order = $gateway->get_option('auto_complete_order'); // Get the currency set in WooCommerce settings $currency = get_woocommerce_currency(); if (function_exists('WC') && WC()->session) { WC()->session->__unset('order_awaiting_payment'); WC()->session->__unset('order_awaiting_payment_' . $gateway->id); } $gateway_data = array( 'apiKey' => sanitize_text_field($api_key), 'businessId' => sanitize_text_field($business_id), 'orderEmail' => sanitize_email($order->get_billing_email()), 'orderAmount' => floatval($order->get_total()), 'currency' => $currency, 'orderFirstName' => $order->get_billing_first_name(), 'orderLastName' => $order->get_billing_last_name(), 'orderId' => strval($order->get_id()), 'updateOrderUrl' => esc_url(admin_url('admin-ajax.php')) . "?action=alatpay_update_order_status&order_id={$order_id}&status=" . ('yes' === $auto_complete_order ? 'completed' : 'processing') . "&nonce=" . wp_create_nonce('alatpay_update_order_status'), 'failUrl' => esc_url(wc_get_checkout_url() . '?result=fail'), 'closeOrderUrl' => esc_url(admin_url('admin-ajax.php')), 'closeOrderNonce' => wp_create_nonce('alatpay_popup_closed_' . $order_id), 'failOrderUrl' => esc_url(admin_url('admin-ajax.php')), 'failOrderNonce' => wp_create_nonce('alatpay_payment_failed_' . $order_id), 'clickOrderUrl' => esc_url(admin_url('admin-ajax.php')), 'clickOrderNonce' => wp_create_nonce('alatpay_payment_initiated_' . $order_id), ); wp_register_script( 'alatpay-gateway', esc_url(plugin_dir_url(__FILE__) . '/assets/js/alatpay.js'), array('jquery', 'alatpay-js'), '1.0.0', true ); wp_localize_script('alatpay-gateway', 'gatewayData', $gateway_data); wp_enqueue_script('alatpay-gateway'); ?> ' . esc_html__('Thank you for your order, please click the button below to pay via ALATPay.', 'alatpay') . '

'; ?>