### Untitled No description -------------------------------- ### Open 7-11 Store Selection Map and Handle Callback (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP function, `openMapForStore`, initiates the process by requesting a store selection map URL from a 7-11 API. It prepares the request with necessary credentials and callback information. The `handle_store_callback` function then processes the data returned from the store selection, validates it, and communicates the selected store details back to the parent window or redirects to the checkout page. ```php public static function openMapForStore(string $store_category, string $shipping_method): void { // Create unique identifier for callback $base_id = uniqid(); $random = wp_rand(1000000, 9999999); $temp_var = $base_id . $random; $callback_url = add_query_arg( array('action' => 'ccat711_store_callback'), site_url('cvs-callback') ); // Get API credentials $api_data = self::get_api_data(); $api_url = $api_data[1] . 'api/Logistics/OpenMap'; // Prepare request data $request_data = array( 'ServiceId' => $api_data[2], 'ReturnUrl' => $callback_url, 'TempVar' => $temp_var, 'StoreCategory' => $store_category, // 13=normal, 15=refrigerated, 14=frozen ); // Send API request $response = wp_remote_post($api_url, array( 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_data[0], ), 'body' => wp_json_encode($request_data), 'timeout' => 30, )); if (is_wp_error($response)) { wp_send_json_error(array('message' => 'API request failed')); return; } $response_data = json_decode(wp_remote_retrieve_body($response), true); // Store temporary data for callback validation update_option( CCATPAYMENTS_PREFIX . 'ccat_temp_var_' . $temp_var, array( 'shipping_method' => $shipping_method, 'order_id' => $_POST['order_id'] ?? '', 'created_at' => time(), ), false ); // Return map URL to frontend wp_send_json_success(array('url' => $response_data['url'])); } // Handle store selection callback public function handle_store_callback() { if (!isset($_GET['action']) || 'ccat711_store_callback' !== $_GET['action']) { return; } // Get callback data $temp_var = sanitize_text_field($_POST['TempVar']); $store_name = sanitize_text_field($_POST['storename']); $store_id = sanitize_text_field($_POST['storeid']); $store_address = sanitize_text_field($_POST['storeaddress']); // Validate temporary variable $stored_data = get_option(CCATPAYMENTS_PREFIX . 'ccat_temp_var_' . $temp_var); if (empty($stored_data)) { wp_die(__('無效的識別參數', 'ccat-for-woocommerce')); } // Delete temporary data delete_option(CCATPAYMENTS_PREFIX . 'ccat_temp_var_' . $temp_var); // Prepare store data $store_data = wp_json_encode(array( 'tempVar' => $temp_var, 'storeId' => $store_id, 'storeName' => $store_name, 'storeAddress' => $store_address, )); // Output JavaScript callback to parent window echo ''; exit; } ``` -------------------------------- ### Untitled No description -------------------------------- ### Abstract Base Class for CCAT Pay Shipping Methods in PHP Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt Defines an abstract base class for custom shipping methods in WooCommerce using CCAT Pay. It includes properties for payment requirements, store selection URL, and temperature type, along with methods for initialization, processing admin options, and calculating shipping rates. Dependencies include the WooCommerce WC_Shipping_Method class. ```php // In includes/shipping/class-ccatpay-shipping-abstract.php (base class) abstract class CCATPAY_Shipping_Abstract extends WC_Shipping_Method { protected bool $requires_payment = true; protected string $store_selection_url = ''; protected string $temperature_type = 'normal'; public function __construct($instance_id = 0) { $this->instance_id = absint($instance_id); $this->id = strtolower(static::class); $this->supports = array('shipping-zones', 'instance-settings'); $this->init_form_fields(); $this->init_settings(); add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options')); parent::__construct($instance_id); } public function init_form_fields() { $this->instance_form_fields = array( 'title' => array( 'title' => __('運送方式名稱', 'ccat-for-woocommerce'), 'type' => 'text', 'description' => __('顧客看到的名稱', 'ccat-for-woocommerce'), 'default' => $this->method_title, ), 'cost' => array( 'title' => __('運費', 'ccat-for-woocommerce'), 'type' => 'price', 'default' => '0', 'description' => __('運送費用', 'ccat-for-woocommerce'), ), ); } public function calculate_shipping($package = array()) { $rate = array( 'id' => $this->get_rate_id(), 'label' => $this->title, 'cost' => $this->get_option('cost'), ); $this->add_rate($rate); } } ``` -------------------------------- ### Register Custom Checkout Block Integration (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP code snippet demonstrates how to register a custom checkout block integration for WooCommerce Blocks. It defines a class `CCATPAY_711_Blocks_Integration` that implements an `IntegrationInterface`. The `initialize` method registers frontend and editor scripts, and the `register_main_integration` method handles script registration and localization using WordPress's `wp_register_script` and `wp_localize_script` functions. This is typically hooked into `woocommerce_blocks_checkout_block_registration`. ```php // In 711-checkout-block/class-ccatpay-711-blocks-integration.php class CCATPAY_711_Blocks_Integration implements IntegrationInterface { public function get_name(): string { return 'ccat711-block'; } public function initialize() { $this->register_block_frontend_scripts(); $this->register_block_editor_scripts(); $this->register_main_integration(); } public function register_main_integration() { $script_path = '/build/index.js'; $script_url = plugins_url($script_path, __FILE__); $script_asset_path = __DIR__ . '/build/index.asset.php'; $script_asset = file_exists($script_asset_path) ? require $script_asset_path : array('dependencies' => array(), 'version' => CCATPAYMENTS_VERSION); wp_register_script( 'ccatpay_for_woocommerce_ccat711-blocks-integration', $script_url, $script_asset['dependencies'], $script_asset['version'], true ); wp_localize_script( 'ccatpay_for_woocommerce_ccat711-blocks-integration', 'ccatpay_for_woocommerce_ccat711BlockData', array( 'nonce' => wp_create_nonce('ccat711_store_selection_nonce'), 'ajax_url' => admin_url('admin-ajax.php'), ) ); } public function get_script_handles(): array { return array('ccatpay_for_woocommerce_ccat711-blocks-integration'); } public function get_editor_script_handles(): array { return array('ccatpay_for_woocommerce_ccat711-blocks-editor'); } } // Register in main plugin file add_action('woocommerce_blocks_checkout_block_registration', function($integration_registry) { $integration_registry->register(new CCATPAY_711_Blocks_Integration()); }); ``` -------------------------------- ### Process Credit Card Payments via CCatPay API (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP function processes credit card payments by making a POST request to the CCatPay API. It constructs the API request body with order details, optionally includes invoice data, and handles the API response to update the WooCommerce order status and redirect the user to the payment gateway. It requires WooCommerce and PHP's DateTime and DateTimeZone classes. ```php public function process_payment($order_id): array { $order = wc_get_order($order_id); try { $api_url = $this->get_base_url() . 'api/Collect'; $api_token = $this->get_payment_api_token(); $order_no = $this->generate_unique_order_number($order); $datetime = new DateTime('now', new DateTimeZone('Asia/Taipei')); $post_data = array( 'cmd' => 'CocsOrderAppend', 'cust_id' => $this->get_account(), 'cust_order_no' => $order_no, 'order_amount' => $order->get_total(), 'order_detail' => 'Order #' . $order->get_id(), 'acquirer_type' => $this->acquirer_type(), // 'esun' for credit card 'send_time' => $datetime->format('Y-m-d H:i:s'), 'apn_url' => $this->get_apn_url(), ); // Add invoice data if enabled if ('yes' === get_option(CCATPAYMENTS_PREFIX . '_invoice_enable', 'no')) { $post_data = $this->add_invoice_data($post_data, $order); } // Make API call $response = wp_remote_post($api_url, array( 'body' => wp_json_encode($post_data), 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_token, ), 'timeout' => 45, )); if (is_wp_error($response)) { throw new Exception('API connection failed: ' . $response->get_error_message()); } $response_data = json_decode(wp_remote_retrieve_body($response), true); if ('OK' === $response_data['status']) { $order->update_meta_data('_final_order_no', $order_no); $order->update_status('pending', 'Awaiting payment'); $order->save(); WC()->cart->empty_cart(); return array( 'result' => 'success', 'redirect' => $response_data['url'], // Payment gateway URL ); } else { throw new Exception($response_data['msg']); } } catch (Exception $e) { wc_add_notice($e->getMessage(), 'error'); return array('result' => 'failure'); } } ``` -------------------------------- ### Concrete CCAT Pay Shipping Method for Refrigerated COD in PHP Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt Implements a concrete shipping method for CCAT Pay that supports refrigerated Cash on Delivery. This class extends the abstract CCATPAY_Shipping_Abstract class, specifically setting the temperature type to 'refrigerated' and defining the method title, name, and description for refrigerated COD. ```php // Concrete implementation for refrigerated COD shipping class CCATPAY_Shipping_COD_Refrigerated extends CCATPAY_Shipping_COD { public function __construct($instance_id = 0) { parent::__construct($instance_id); $this->temperature_type = 'refrigerated'; $this->method_title = __('黑貓宅配(冷藏) 貨到付款', 'ccat-for-woocommerce'); $this->title = __('黑貓宅配(冷藏) 貨到付款', 'ccat-for-woocommerce'); $this->method_description = __('黑貓宅配低溫冷藏商品 貨到付款', 'ccat-for-woocommerce'); } } ``` -------------------------------- ### Register Shipping Methods in WooCommerce (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP function, `add_ccatpay_shipping_methods`, is hooked into the `woocommerce_shipping_methods` filter in `ccat-for-woocommerce.php`. It registers various Black Cat logistics shipping methods, including standard, COD, prepaid, refrigerated, and frozen options, provided that shipping is enabled via a WordPress option. This allows these shipping methods to be available for selection in WooCommerce checkout. ```php // In ccat-for-woocommerce.php add_filter('woocommerce_shipping_methods', 'add_ccatpay_shipping_methods'); function add_ccatpay_shipping_methods(array $methods): array { if ('yes' === get_option('ccatpay-for-woocommerce_shipping_enable', 'yes')) { // Standard shipping methods $methods['ccatpay_shipping_cod'] = 'CCATPAY_Shipping_COD'; $methods['ccatpay_shipping_711_cod'] = 'CCATPAY_Shipping_711_COD'; $methods['ccatpay_shipping_prepaid'] = 'CCATPAY_Shipping_Prepaid'; $methods['ccatpay_shipping_711_prepaid'] = 'CCATPAY_Shipping_711_Prepaid'; // Refrigerated shipping methods $methods['ccatpay_shipping_cod_refrigerated'] = 'CCATPAY_Shipping_COD_Refrigerated'; $methods['ccatpay_shipping_711_cod_refrigerated'] = 'CCATPAY_Shipping_711_COD_Refrigerated'; $methods['ccatpay_shipping_prepaid_refrigerated'] = 'CCATPAY_Shipping_Prepaid_Refrigerated'; $methods['ccatpay_shipping_711_prepaid_refrigerated'] = 'CCATPAY_Shipping_711_Prepaid_Refrigerated'; // Frozen shipping methods $methods['ccatpay_shipping_cod_frozen'] = 'CCATPAY_Shipping_COD_Frozen'; $methods['ccatpay_shipping_711_cod_frozen'] = 'CCATPAY_Shipping_711_COD_Frozen'; $methods['ccatpay_shipping_prepaid_frozen'] = 'CCATPAY_Shipping_Prepaid_Frozen'; $methods['ccatpay_shipping_711_prepaid_frozen'] = 'CCATPAY_Shipping_711_Prepaid_Frozen'; } return $methods; } ``` -------------------------------- ### Acquire and Cache OAuth2 API Token (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This function retrieves an OAuth2 access token for the CCatPay API. It first checks for a cached token; if none exists, it makes a POST request to the token endpoint using provided credentials. The acquired token is then cached for a specific duration, with a buffer to ensure it's always valid before expiration. This is essential for authenticating subsequent API calls. ```php // In includes/class-ccatpay-gateway-abstract.php public function get_payment_api_token(): ?string { // Check for cached token $cached_token = get_transient(CCATPAYMENTS_PREFIX . 'api_access_token'); if ($cached_token) { return $cached_token; } // Request new token $api_endpoint = $this->get_base_url() . 'token'; $body = array( 'grant_type' => 'password', 'username' => $this->get_account(), 'password' => $this->get_password(), ); $response = wp_remote_post($api_endpoint, array( 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'), 'body' => http_build_query($body), 'timeout' => 45, )); if (is_wp_error($response)) { CCATPAY_Payments::log('Token request failed: ' . $response->get_error_message()); return null; } $decoded_response = json_decode(wp_remote_retrieve_body($response), true); $access_token = $decoded_response['access_token']; $expires_at = strtotime($decoded_response['.expires']); $current_time = time(); $expires_in = $expires_at - $current_time; // Cache token with 60-second buffer before expiration set_transient(CCATPAYMENTS_PREFIX . 'api_access_token', $access_token, $expires_in - 60); return $access_token; } ``` -------------------------------- ### Process Payment Refunds in WooCommerce (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP function, located in `includes/class-ccatpay-gateway-abstract.php`, handles payment refunds for WooCommerce orders. It supports full cancellations, cash requests (partial refunds), and standard refunds. It interacts with the CCAT API to process these refund types based on order status and amount. Dependencies include WooCommerce order functions and WordPress HTTP API. Returns a boolean on success or a WP_Error object on failure. ```php // In includes/class-ccatpay-gateway-abstract.php public function process_refund($order_id, $amount = null, $reason = ''): bool|WP_Error { $order = wc_get_order($order_id); if (!$order) { return new WP_Error('invalid_order', '找不到訂單'); } if ($amount <= 0) { return new WP_Error('invalid_amount', '無效的退款金額'); } $order_no = $order->get_meta('_final_order_no'); $processing = $order->get_meta('_payment_processing'); // Determine refund type based on order status if (empty($processing) && (is_null($amount) || empty($order->get_remaining_refund_amount()))) { // Full cancellation (not yet processed) $request_data = array( 'cmd' => 'CocsOrderCancel', 'cust_order_no' => $order_no, 'order_amount' => $order->get_total(), 'acquirer_type' => $this->acquirer_type(), ); } elseif (empty($processing)) { // Cash request (partial refund, not processed) $request_data = array( 'cmd' => 'CocsCashRequest', 'cust_order_no' => $order_no, 'cr_amount' => $order->get_remaining_refund_amount(), ); } else { // Refund (already processed payment) $request_data = array( 'cmd' => 'CocsOrderRefund', 'cust_order_no' => $order_no, 'refund_amount' => $amount, 'acquirer_type' => $this->acquirer_type(), ); } $api_url = $this->get_base_url() . 'api/Collect'; $api_token = $this->get_payment_api_token(); $response = wp_remote_post($api_url, array( 'body' => wp_json_encode($request_data), 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_token, ), 'timeout' => 45, )); if (is_wp_error($response)) { return new WP_Error('api_connection_error', 'API 請求失敗: ' . $response->get_error_message()); } $response_data = json_decode(wp_remote_retrieve_body($response), true); if ('OK' !== $response_data['status']) { return new WP_Error('api_response_error', 'API error: ' . $response_data['msg']); } $order->add_order_note(sprintf('Refund of %s processed successfully. Reason: %s', wc_price($amount), $reason)); return true; } ``` -------------------------------- ### Register Payment Method for WooCommerce Blocks (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP code registers a custom payment method for use with WooCommerce Blocks checkout. It defines a class that extends `AbstractPaymentMethodType` to provide necessary data and script handles for the block. The payment method is registered via the `woocommerce_blocks_payment_method_type_registration` action hook. Dependencies include WooCommerce Blocks and the main CCAT Pay plugin. ```php final class CCATPAY_Gateway_Credit_Card_Blocks_Support extends AbstractPaymentMethodType { private CCATPAY_Gateway_Abstract $gateway; protected $name = 'ccat_payment_credit_card'; public function initialize() { $gateways = WC()->payment_gateways->payment_gateways(); $this->gateway = $gateways[$this->name]; } public function is_active(): bool { return $this->gateway->is_available(); } public function get_payment_method_script_handles(): array { $script_path = '/resources/js/frontend/credit-card.js'; $script_url = CCATPAY_Payments::plugin_url() . $script_path; wp_register_script( 'wc-ccat-payments-blocks', $script_url, array('wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-html-entities'), CCATPAYMENTS_VERSION, true ); wp_set_script_translations('wc-ccat-payments-blocks', CCATPAYMENTS_DOMAIN); return array('wc-ccat-payments-blocks'); } public function get_payment_method_data(): array { return array( 'title' => $this->gateway->get_option('title'), 'description' => $this->gateway->get_option('description'), 'supports' => array_filter($this->gateway->supports, array($this->gateway, 'supports')), ); } } // Register in main plugin file add_action('woocommerce_blocks_payment_method_type_registration', function($payment_method_registry) { $payment_method_registry->register(new CCATPAY_Gateway_Credit_Card_Blocks_Support()); }); ``` -------------------------------- ### Filter Payment Gateways by Shipping Method (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP code snippet dynamically filters available payment gateways based on the selected shipping method in WooCommerce. It uses WordPress filters to hook into WooCommerce's payment gateway availability. It handles logic for Cash on Delivery (COD) shipping and specific 7-11 COD requirements, ensuring only compatible payment methods are shown to the user. Dependencies include WooCommerce and its session handling. ```php class CCATPAY_Shipping_Payment_Coordinator { public static function init() { add_filter( 'woocommerce_available_payment_gateways', array(__CLASS__, 'filter_payment_gateways_by_shipping') ); } public static function filter_payment_gateways_by_shipping(array $available_gateways): array { // Get selected shipping methods from session $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods'); if (empty($chosen_shipping_methods)) { return $available_gateways; } // Check if COD shipping is selected $is_cod_shipping = self::is_cod_shipping_selected($chosen_shipping_methods); if ($is_cod_shipping) { // Check if 7-11 shipping is selected $is_711_shipping = false; foreach ($chosen_shipping_methods as $method) { if (false !== strpos($method, '711')) { $is_711_shipping = true; break; } } if ($is_711_shipping) { // Only allow 7-11 COD payment gateway foreach ($available_gateways as $id => $gateway) { if ('ccat_cod_711' !== $id) { unset($available_gateways[$id]); } } } else { // Allow standard COD payment gateways foreach ($available_gateways as $id => $gateway) { if (!in_array($id, array('ccat_cod_card', 'ccat_cod_cash', 'ccat_cod_mobile'), true)) { unset($available_gateways[$id]); } } } } else { // Remove all COD payment gateways for prepaid shipping foreach ($available_gateways as $id => $gateway) { if (strpos($id, 'cod') !== false) { unset($available_gateways[$id]); } } } return $available_gateways; } private static function is_cod_shipping_selected(array $chosen_methods): bool { foreach ($chosen_methods as $method) { if (false !== strpos($method, 'cod')) { return true; } } return false; } } CCATPAY_Shipping_Payment_Coordinator::init(); ``` -------------------------------- ### Register Payment Method with WooCommerce Blocks (JavaScript) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This JavaScript code snippet registers a custom payment method (credit card) with the WooCommerce Blocks checkout. It retrieves payment configuration, sets the payment label and description, and defines properties like `name`, `label`, `content`, `edit`, `canMakePayment`, `ariaLabel`, and `supports` for the payment method. It relies on WooCommerce Blocks registry and WordPress utilities for HTML entities and internationalization. ```javascript // In resources/js/frontend/credit-card.js const ccatPaymentConfig = window.wc.wcSettings.getSetting('ccat_payment_credit_card_data', {}); const ccatPaymentLabel = window.wp.htmlEntities.decodeEntities(ccatPaymentConfig.title) || window.wp.i18n.__('玉山銀行', 'ccat-for-woocommerce'); const ccatPaymentContent = () => { return window.wp.htmlEntities.decodeEntities(ccatPaymentConfig.description || ''); }; const ccatPayment = { name: 'ccat_payment_credit_card', label: ccatPaymentLabel, content: Object(window.wp.element.createElement)(ccatPaymentContent, null), edit: Object(window.wp.element.createElement)(ccatPaymentContent, null), canMakePayment: () => true, ariaLabel: ccatPaymentLabel, supports: { features: ccatPaymentConfig.supports, }, }; window.wc.wcBlocksRegistry.registerPaymentMethod(ccatPayment); ``` -------------------------------- ### Register WooCommerce Payment Gateways (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This code snippet demonstrates how to register custom payment gateways with WooCommerce using a WordPress filter. It checks if the CCatPay plugin is enabled before adding gateway classes to the available options. This is crucial for enabling CCatPay as a payment method in the WooCommerce store. ```php // In ccat-for-woocommerce.php add_filter('woocommerce_payment_gateways', 'add_ccatpay_gateways'); function add_ccatpay_gateways($gateways) { if ('yes' === get_option('ccatpay-for-woocommerce_enable', 'yes')) { $gateways[] = 'CCATPAY_Gateway_Credit_Card'; $gateways[] = 'CCATPAY_Gateway_Cvs_Ibon'; $gateways[] = 'CCATPAY_Gateway_Cvs_Atm'; $gateways[] = 'CCATPAY_Gateway_App_Opw'; $gateways[] = 'CCATPAY_Gateway_App_Icash'; $gateways[] = 'CCATPAY_Gateway_COD_Cash'; $gateways[] = 'CCATPAY_Gateway_COD_711'; } return $gateways; } ``` -------------------------------- ### Handle CCatPay Payment Callback and Validation (PHP) Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP code handles incoming payment notifications from the CCatPay gateway and validates them using a checksum. It updates the WooCommerce order status based on the payment status received and returns an appropriate HTTP response. This function requires WP_REST_Request for input and WP_Error for validation failures. ```php public function handle_payment_callback(WP_REST_Request $request): WP_REST_Response { // Validate request $validate = $this->handle_payment_validation($request); if ($validate instanceof WP_Error) { return new WP_REST_Response($validate->get_error_message(), $validate->get_error_code()); } $data = json_decode($request->get_body(), true); $order = $this->get_order($data['order_no']); if (!$order) { return new WP_REST_Response('Order not found', 404); } $this->add_apn_notification($order, $data); $status = strtoupper($data['status']); switch ($status) { case 'B': // Authorization complete $order->payment_complete(); $order->add_order_note('Payment completed via CCatPay'); break; case 'F': // Authorization failed $order->update_status('failed', 'Payment authorization failed'); break; case 'M': // Transaction cancelled $order->update_status('cancelled', 'Payment cancelled by customer'); break; case 'I': // Invoice issued $order->update_meta_data('_invoice_no', $data['invoice_no']); $order->add_order_note('Invoice issued: ' . $data['invoice_no']); break; } $order->save(); return new WP_REST_Response('OK', 200); } // Callback validation with checksum verification protected function handle_payment_validation(WP_REST_Request $request): ?WP_Error { $data = json_decode($request->get_body(), true); $required_fields = array('api_id', 'trans_id', 'amount', 'status', 'nonce', 'checksum'); foreach ($required_fields as $field) { if (!isset($data[$field])) { return new WP_Error(400, "Missing required field: {$field}"); } } // Verify checksum $calculated_checksum = md5( $data['api_id'] . ':' . $data['trans_id'] . ':' . $data['amount'] . ':' . $data['status'] . ':' . $data['nonce'] ); if ($calculated_checksum !== $data['checksum']) { return new WP_Error(400, 'Checksum verification failed'); } return null; } ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Process ATM Virtual Account Payment in PHP Source: https://context7.com/ccatpay/ccat-for-woocommerce/llms.txt This PHP function handles the processing of ATM virtual account payments for WooCommerce orders. It validates customer and order details, constructs an API request to the CCatPay service, handles the API response, and updates the WooCommerce order status accordingly. Dependencies include WooCommerce core functions and PHP's DateTime and JSON handling. ```php public function process_payment($order_id): array { $order = wc_get_order($order_id); try { // Validate required fields $payer_name = $order->get_billing_first_name() . $order->get_billing_last_name(); $payer_email = $order->get_billing_email(); if (empty($payer_name)) { throw new Exception('姓名為必填'); } if (!filter_var($payer_email, FILTER_VALIDATE_EMAIL)) { throw new Exception('信箱格式錯誤或沒有填寫'); } $api_url = $this->get_base_url() . 'api/Collect'; $api_token = $this->get_payment_api_token(); $order_no = $this->generate_unique_order_number($order); $datetime = new DateTime('now', new DateTimeZone('Asia/Taipei')); $post_data = array( 'cmd' => 'CvsOrderAppend', 'cust_id' => $this->get_account(), 'cust_order_no' => $order_no, 'order_amount' => $order->get_total(), 'expire_date' => $datetime->modify('+7 days')->format('Y-m-d'), 'payer_name' => $payer_name, 'payer_postcode' => $order->get_billing_postcode(), 'payer_address' => $order->get_billing_address_1(), 'payer_mobile' => $order->get_billing_phone(), 'payer_email' => $payer_email, 'payment_type' => $this->payment_type(), // '1' for ATM 'payment_acquirerType' => $this->acquirer_type(), ); $response = wp_remote_post($api_url, array( 'body' => wp_json_encode($post_data), 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $api_token, ), 'timeout' => 45, )); if (is_wp_error($response)) { throw new Exception('API request failed'); } $response_data = json_decode(wp_remote_retrieve_body($response), true); if ('OK' === $response_data['status']) { // Store ATM details $order->update_meta_data('_bank_id', $response_data['bank_id']); $order->update_meta_data('_virtual_account', $response_data['virtual_account']); $order->update_meta_data('_expire_date', $response_data['expire_date']); $order->update_meta_data('_bill_amount', $response_data['bill_amount']); $order->update_meta_data('_final_order_no', $order_no); $order->update_status('pending', 'Awaiting ATM payment'); $order->save(); WC()->cart->empty_cart(); return array( 'result' => 'success', 'redirect' => $this->get_return_url($order), ); } else { throw new Exception($response_data['msg']); } } catch (Exception $e) { wc_add_notice($e->getMessage(), 'error'); return array('result' => 'failure'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.