supports = array( 'products','refunds' ); $this->id = 'allinpay_intl'; $this->icon =rtrim(plugin_dir_url(__FILE__),'/'). '/icon/allinpay164.png'; $this->has_fields = false; $this->method_title = __('Allinpay INTL','woocommerce'); $this->init_form_fields(); $this->title = $this->get_option ( 'title' ); $this->method_description = $this->get_option('description');//'This is a payment gateway that uses RSA signature for payment security.'; //$this->init_settings(); $this->gateway_url = $this->get_option('trace_url'); $this->merchant_id = $this->get_option( 'merchant_id' ); $this->private_key = $this->get_option( 'private_key' ); $this->public_key = $this->get_option( 'public_key' ); $this->version = $this->get_option('version'); $this->debug_log =$this->get_option('debug_log'); if('yes'== $this->debug_log){ $this->log = new WC_Logger(); } add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) ); add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) ); add_action('woocommerce_api_allinpay_payment_callback', array($this,'allinpay_payment_callback')); add_action('woocommerce_api_allinpay_front_payment_callback', array($this,'allinpay_front_payment_callback')); add_filter('woocommerce_order_number', 'allinpay_woocommerce_order_number', 10, 2); add_action('woocommerce_checkout_update_order_meta', 'allinpay_save_order_number'); //add_action('woocommerce_order_status_refunded', array($this, 'allinpay_process_refund')); add_action( 'allinpay_check_refund_status_hook', 'allinpay_check_refund_status_function', 10, 1 ); add_action('woocommerce_order_refunded',array($this,'handle_api_refund_after_wc_refund'),10,2); if ( !self::$button_added ) { add_action('woocommerce_order_item_add_action_buttons',array($this, 'add_allinpay_query_button')); self::$button_added = true; } add_action('admin_enqueue_scripts', array($this,'enqueue_allinpay_query_button_script')); add_action('wp_ajax_query_order', array($this,'allinpay_query')); add_action('wp_ajax_nopriv_query_order', array($this,'allinpay_query')); add_filter('woocommerce_gateway_description', 'custom_payment_descriptions', 10, 2); add_action('wp_enqueue_scripts',array($this,'add_allinpay_style')); $this->register_activation_hook(); } public function register_activation_hook() { register_activation_hook(__FILE__, array($this, 'activation_function')); } function activation_function(){ add_action('wp_ajax_query_order', array($this,'allinpay_query')); add_action('wp_ajax_nopriv_query_order', array($this,'allinpay_query')); } function add_allinpay_query_button($order) { $order_id = $order->get_id(); $order_status = $order->get_status(); // Display the button only if the order is in a specific status if ($order_status === 'pending' || $order_status==='processing' || $order_status==='completed') { $button_text = __('Order Query', 'custom-payment-integration'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped $showInfo = ''; $allowed_html=array( 'button'=> array( 'type' => array(), 'class' => array(), 'id' => array(), 'data-order-id' => array() ) ); echo wp_kses($showInfo,$allowed_html); } } function enqueue_allinpay_query_button_script($hook) { // 确保在订单编辑页面加载脚本 if ('woocommerce_page_wc-orders' !== $hook) { return; } $screen = get_current_screen(); if (!isset($screen->post_type) || 'shop_order' !== $screen->post_type) { return; } //$this->allinpay_log('加载的页面为'.$hook); //$this->allinpay_log('加载的方法为:'.$screen->post_type); // 确保jQuery已经加载 wp_enqueue_script('jquery'); // 加载查询按钮脚本 $script_url = rtrim(plugin_dir_url(__FILE__),'/').'/js/custom-query-button.js'; wp_enqueue_script('allinpay-query-button-script', $script_url, array('jquery'), '1.7', true); //$this->allinpay_log('加载的js路径为'.$script_url); // 添加调试信息 // 本地化脚本变量 wp_localize_script( 'allinpay-query-button-script', 'custom_script_vars', array( 'nonce' => wp_create_nonce( 'allinpay_query' ), 'ajaxurl' => admin_url('admin-ajax.php') ) ); } private function _api_query_request( $oriAccessOrderId ) { if ( empty( $oriAccessOrderId ) ) { return new WP_Error( 'missing_param', '查询失败:必须提供原始支付订单号。' ); } $this->allinpay_log( "核心查询方法: 准备查询订单号 {$oriAccessOrderId}" ); $query_data = array( 'version' => $this->version, 'mchtId' => $this->merchant_id, 'transType' => 'Query', // 固定的接口类型 'oriAccessOrderId' => $oriAccessOrderId, 'signType' => 'RSA2' ); $signature = $this->generate_signature( $query_data ); $query_data['sign'] = $signature; $respResult = $this->request( $this->gateway_url, $query_data ); $this->allinpay_log( "核心查询方法返回原始报文: " . $respResult ); $parseJson = json_decode( $respResult, true ); if ( ! $parseJson || ! isset( $parseJson['status'] ) ) { $this->allinpay_log( "核心查询方法错误: 无法解析API响应或缺少状态信息。" ); return new WP_Error( 'api_error', '查询失败:无法解析API响应或响应格式不正确。' ); } // 返回成功解析的JSON数组 return $parseJson; } function allinpay_query() { check_ajax_referer( 'allinpay_query', 'nonce' ); $this->allinpay_log( '开始执行自定义AJAX订单查询操作' ); if ( ! isset( $_POST['order_id'] ) ) { wp_send_json_error( '无效的请求:缺少订单ID。' ); wp_die(); } $order_id = intval( $_POST['order_id'] ); $order = wc_get_order( $order_id ); if ( ! $order ) { wp_send_json_error( '查询失败:找不到指定的订单。' ); wp_die(); } $oriAccessOrderId = $order->get_meta( 'custom_order_number' ); if ( ! $oriAccessOrderId ) { wp_send_json_error( '查询失败:找不到用于API查询的订单号。' ); wp_die(); } // ... (您的API请求代码保持不变) ... $parseJson = $this->_api_query_request( $oriAccessOrderId ); $this->allinpay_log( 'AJAX查询接口返回的信息为:' . $parseJson ); if ( ! $parseJson || ! isset( $parseJson['status'] ) ) { wp_send_json_error( '查询失败:无法解析API响应或缺少状态信息。' ); wp_die(); } $api_status = $parseJson['status']; $current_wc_status = $order->get_status(); switch ( $api_status ) { // ... (case 'PAIED', 'CLOSE', 'FAILED' 等保持不变) ... case 'PAIED': if ( ! $order->is_paid() ) { $transaction_id = $parseJson['orderId'] ?? $oriAccessOrderId; $order->payment_complete( $transaction_id ); $order->add_order_note( '通过API查询确认订单已支付。' ); } wp_send_json_success( 'processing' ); // 通常支付完成后是 processing break; case 'CLOSE': case 'REVOKED': case 'COLSED': if ( $current_wc_status !== 'cancelled' ) { $order->update_status( 'cancelled', '通过API查询确认订单已关闭或撤销。' ); } wp_send_json_success( 'cancelled' ); break; case 'FAILED': if ( $current_wc_status !== 'failed' ) { $order->update_status( 'failed', '通过API查询确认订单支付失败。' ); } wp_send_json_success( 'failed' ); break; case 'REFUND': // ---------------------------------------------------- // 核心逻辑:当API只告知“有退款”时,我们相信WC自己的金额记录 // ---------------------------------------------------- $order->add_order_note( 'API查询确认:网关记录此订单存在退款。系统将根据WooCommerce内部金额记录更新状态。' ); $order_total = (float) $order->get_total(); $refunded_total = (float) $order->get_total_refunded(); // **金额检查** if ( $refunded_total <= 0 ) { // API说有退款,但WC记录里没有。这是一种状态不一致。 // 我们应该相信API,并提示用户可能需要手动同步。 $order->add_order_note( '警告:API表明有退款,但WooCommerce内部没有找到退款记录。可能需要手动处理。' ); wp_send_json_success( 'needs-manual-check' ); // 返回自定义状态给前端 } elseif ( $refunded_total < $order_total ) { // **部分退款** // 确认订单状态不是 'refunded'。如果是,就纠正它。 if ( $current_wc_status === 'refunded' ) { // 这是一个需要修复的错误状态 $order->update_status( 'completed', '状态纠正:根据部分退款金额,将状态从“已退款”恢复为“已完成”。' ); wp_send_json_success( 'completed' ); // 返回修复后的状态 } else { // 状态正确(比如 'completed'),无需改变 wp_send_json_success( $current_wc_status ); } } else { // $refunded_total >= $order_total // **全额退款** // 确保订单状态是 'refunded' if ( $current_wc_status !== 'refunded' ) { $order->update_status( 'refunded', '状态同步:根据全额退款金额,将订单状态更新为“已退款”。' ); } wp_send_json_success( 'refunded' ); } break; default: wp_send_json_success( 'handler' ); // 其他状态 break; } wp_die(); } function add_allinpay_style(){ wp_register_style('allinpay-css-default',rtrim(plugin_dir_url(__FILE__),'/'). '/css/default.css'); wp_enqueue_style('allinpay-css-default'); } public function init_form_fields() { // Payment gateway settings initialization $this->form_fields = array( 'enabled' => array( 'title' => __('Enable/Disable','allinpay_intl'), 'type' => 'checkbox', 'label' => 'Enable Allinpay INTL', 'default' => 'no' ), 'title' => array( 'title' => 'Title', 'type' => 'text', 'description' => 'This controls the title which the user sees during checkout.', 'default' => __('Allinpay INTL','allinpay_intl'), 'desc_tip' => true ), 'description' => array( 'title' => 'Description', 'type' => 'textarea', 'description' => 'This controls the description which the user sees during checkout.', 'default' => 'Pay with Allinpay INTL', ), 'version' => array( 'title' => 'Version', 'type' => 'text', 'description' => 'This controls the title which the user sees during checkout.', 'default' => 'V2.0.0', 'desc_tip' => true ), 'trace_url' => array( 'title' => 'Trace Url', 'type' => 'text', 'description' => 'Enter the trace url provided by Payment Gateway.', 'default' => '', 'desc_tip' => true ), 'merchant_id' => array( 'title' => 'Merchant ID', 'type' => 'text', 'description' => 'Enter your merchant ID provided by Payment Gateway.', 'desc_tip' => true ), 'private_key' => array( 'title' => 'Private Key', 'type' => 'textarea', 'description' => 'Enter your private key provided by Payment Gateway.', 'desc_tip' => true ), 'public_key' => array( 'title' => 'Public Key', 'type' => 'textarea', 'description' => 'Enter your public key provided by Payment Gateway.', 'desc_tip' => true ), 'debug_log' => array( 'title' => __('debug_log','allinpay_intl'), 'type' => 'checkbox', 'description' => __('Log payment events,such as trade status,insidewp-content/uploads/wc-logs/ ','allinpay_intl'), 'default' => 'no' ) ); } public function payment_fields(){ if ( $this->method_description) { echo wpautop( wptexturize($this->method_description) ); } } public function process_payment( $order_id ) { // Construct payment request data $order = wc_get_order( $order_id ); $items = $order->get_items(); $weldpay_items = array(); $weldpay_item = array(); foreach($items as $item){ $weldpay_item = array( 'sku' => $item['product_id'], 'productName' => $item['name'], 'price'=> $item['total'], 'quantity'=> $item['quantity'], ); $weldpay_items[]=json_encode($weldpay_item); } //var_dump($weldpay_items); $payment_data = array( 'version' => $this->version, 'mchtId' => $this->merchant_id, 'transType' => 'CashierPay', //'accessOrderId' => $order->get_id(), 'accessOrderId' => $order->get_meta('custom_order_number'), 'currency' => $order->get_currency(), 'amount' => $order->get_total(), 'language' =>substr(get_locale(), 0, 2), //'payPageStyle' => 'DEFAULT', 'email' => $order->get_billing_email(), 'returnUrl' => WC()->api_request_url('allinpay_front_payment_callback'), 'notifyUrl' => WC()->api_request_url('allinpay_payment_callback'), //'timeZone' //持卡人时区,可选 'signType' => 'RSA2',//签名类型 //'txnTitle' => $order->get_title(), //'txnDetail' => $order->get_title(), 'shippingFirstName' => !empty($order->get_shipping_first_name()) ? $order->get_shipping_first_name():$order->get_billing_first_name(), //'shippingFirstName' => $order->get_shipping_first_name(), 'shippingLastName' => !empty($order->get_shipping_last_name()) ? $order->get_shipping_last_name():$order->get_billing_last_name(), 'shippingAddress1' => !empty($order->get_shipping_address_1())? $order->get_shipping_address_1():$order->get_billing_address_1(), //'shippingAddress2' => $order->get_shipping_address_2(), //可选 'shippingCity' => !empty($order->get_shipping_city())? $order->get_shipping_city():$order->get_billing_city(), //'shippingState'=> $order->get_shipping_state(), 'shippingState'=>!empty($order->get_shipping_state()) ? $order->get_shipping_state() :( !empty($order->get_shipping_city())?$order->get_shipping_city():$order->get_billing_city()), 'shippingCountry'=>!empty($order->get_shipping_country())?$order->get_shipping_country():$order->get_billing_country(), 'shippingZipCode' => !empty($order->get_shipping_postcode())?$order->get_shipping_postcode():$order->get_billing_postcode(), 'shippingPhone' => $order->get_billing_phone(), 'billingFirstName' => $order->get_billing_first_name(), 'billingLastName' => $order->get_billing_last_name(), 'billingAddress1' => $order->get_billing_address_1(), //'billingAddress2' => $order->get_billing_address_2(), 'billingCity' => $order->get_billing_city(), 'billingState' => $order->get_billing_state(), 'billingCountry' => $order->get_billing_country(), 'billingZipCode' => $order->get_billing_postcode(), 'billingPhone' => $order->get_billing_phone()); $productInfo = '[' . implode(',', $weldpay_items) . ']'; $payment_data['productInfo'] = $productInfo; // Generate signature using private key $signature = $this->generate_signature( $payment_data ); // Add signature to payment request data $payment_data['sign'] = $signature; $respResult = $this->request($this->gateway_url,$payment_data); $this->allinpay_log('交易接口同步返回的参数为:'.$respResult); $parseJson = json_decode($respResult,true); if($parseJson ==null){ $this->allinpay_log('解析同步返回交易报文失败!!!'); wp_die(); } if($parseJson['resultCode']!='0000'){ wc_add_notice( __('Payment error:', 'woothemes') . $parseJson['resultDesc'], 'error' ); return; } return array( 'result' => 'success', 'redirect' => $parseJson['payUrl'] ); } // 将 iframe 插入页面,没啥用 public function thankyou_page( $order_id ) { $order = wc_get_order($order_id); } /** * 在 WooCommerce 创建退款后,触发此函数来调用第三方 API。 * * @param int $order_id 订单ID。 * @param int $refund_id 新创建的退款的ID。 */ public function handle_api_refund_after_wc_refund( $order_id, $refund_id ) { static $processed_refund_ids = array(); if ( in_array( $refund_id, $processed_refund_ids ) ) { $this->allinpay_log( "钩子重复触发:退款ID {$refund_id} 已在本次请求中处理,跳过。" ); return; } $processed_refund_ids[] = $refund_id; $this->allinpay_log( "开始处理退款ID {$refund_id} (由钩子触发)..." ); $order = wc_get_order( $order_id ); $refund = wc_get_order( $refund_id ); // 获取退款对象 if ( ! $order || ! $refund ) { return; // 如果订单或退款无效,则退出 } // 从退款对象中获取准确的退款金额 $amount_to_refund = $refund->get_amount(); // 获取退款原因 $reason = $refund->get_reason() ? $refund->get_reason() : '由管理员操作的退款'; // ---- 开始调用您的第三方API ---- $platId = $order->get_meta( 'custom_order_number' ); if ( ! $platId ) { $order->add_order_note( '退款失败:无法找到用于API调用的 custom_order_number。' ); return; } $refundOrderId = allinpay_order_id(); // 假设这是生成唯一退款ID的函数 $payment_data = array( 'version' => $this->version, 'mchtId' => $this->merchant_id, 'transType' => 'Refund', 'accessOrderId' => $refundOrderId, 'refundAmount' => $amount_to_refund, // 使用从退款对象获取的金额 'oriAccessOrderId' => $platId, 'signType' => 'RAS2', ); $signature = $this->generate_signature( $payment_data ); $payment_data['sign'] = $signature; $this->allinpay_log( '调用退款接口请求的参数为:' . print_r( $payment_data, true ) ); $respResult = $this->request( $this->gateway_url, $payment_data ); $this->allinpay_log( '退款接口返回的信息为:' . $respResult ); $parseJson = json_decode( $respResult, true ); // ---- 根据API响应更新订单备注 ---- if ( $parseJson && isset($parseJson['resultCode']) ) { if ( $parseJson['resultCode'] === '0000' ) { // **情况一:同步成功 (小概率但需要处理)** $order->add_order_note( sprintf( '第三方网关退款已同步成功。金额: %s。退款交易ID: %s', wc_price( $amount_to_refund ), $refundOrderId )); // 标记退款已确认 $refund->update_meta_data( '_allinpay_refund_status', 'completed' ); $refund->save(); } elseif ( $parseJson['resultCode'] === 'P000' || $parseJson['resultCode'] === '0006' ) { // **情况二:异步处理中 (核心逻辑)** $order->add_order_note( sprintf( '退款请求已提交至第三方网关,正在处理中。金额: %s。查询ID: %s。系统将在后台自动查询最终结果。', wc_price( $amount_to_refund ), $refundOrderId )); // 将查询所需的信息存入退款 meta $refund->update_meta_data( '_allinpay_refund_status', 'pending_query' ); $refund->update_meta_data( '_allinpay_refund_query_id', $refundOrderId ); $refund->update_meta_data( '_allinpay_query_attempts', 0 ); // 初始化尝试次数 $refund->save(); // **调度一个一次性的后台任务,在5分钟后执行查询** wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'allinpay_check_refund_status_hook', array( $refund_id ) ); } else { // **情况三:请求立即失败** $error_desc = $parseJson['resultDesc'] ?? '未知错误'; $order->add_order_note( sprintf( '严重警告:退款请求被第三方网关拒绝。原因: %s。WooCommerce中的退款记录可能需要手动删除。', $error_desc )); $refund->update_meta_data( '_allinpay_refund_status', 'failed' ); $refund->save(); } } else { // ... 处理API请求本身失败的情况 ... $order->add_order_note( '严重警告:调用退款API失败,无法提交请求。请检查网络或配置。' ); } } public function process_refund($order_id, $amount = null, $reason = ''){ return true; } /** * [业务逻辑] WP-Cron 异步退款状态查询处理。 * 调用核心查询方法,并根据结果执行后台状态更新和修复。 * * @param int $refund_id 要查询的退款的ID。 */ public function allinpay_check_refund_status_function( $refund_id ) { $refund = wc_get_order( $refund_id ); if ( ! $refund ) { return; } $order_id = $refund->get_parent_id(); $order = wc_get_order( $order_id ); if ( ! $order || $refund->get_meta( '_allinpay_refund_status' ) !== 'pending_query' ) { return; } $oriAccessOrderId = $order->get_meta( 'custom_order_number' ); // --- 调用通用核心查询方法 --- $api_response = $this->_api_query_request( $oriAccessOrderId ); // --- 处理核心方法返回的结果 --- if ( is_wp_error( $api_response ) ) { // API调用失败,记录日志并重新调度 $order->add_order_note( '警告:后台自动查询退款状态失败,将在稍后重试。原因:' . $api_response->get_error_message() ); wp_schedule_single_event( time() + ( 30 * MINUTE_IN_SECONDS ), 'allinpay_check_refund_status_hook', array( $refund_id ) ); return; } // API调用成功,根据返回的状态处理业务逻辑 $api_status = $api_response['status']; $refundOrderId = $refund->get_meta('_allinpay_refund_query_id'); // 这是退款请求ID,用于日志 // 在Cron任务中,我们只关心API是否还是REFUND状态 if ( $api_status === 'REFUND' ) { // 因为API不返回具体金额,我们无法100%确认是哪笔退款成功了。 // 但我们可以假设,既然发起了退款查询,这笔退款大概率是成功了。 // 这是一个基于现有API限制的合理推断。 $refund->update_meta_data( '_allinpay_refund_status', 'completed' ); $order->add_order_note( sprintf( '退款状态后台确认:网关状态为REFUND。假定退款请求 %s 已成功。', $refundOrderId )); } else { // 如果API返回了其他状态(例如PAID),说明退款可能失败了或被冲正。 // 这是需要人工干预的严重情况。 $refund->update_meta_data( '_allinpay_refund_status', 'failed' ); $critical_note = sprintf( '严重警告:退款失败!后台查询发现订单状态已不再是REFUND(当前为 %s)。退款请求 %s 可能已失败,请立即手动核查!', $api_status, $refundOrderId ); if ( $order->get_status() === 'refunded' ) { $critical_note .= ' 订单状态已从“已退款”自动恢复为“已完成”。'; $order->update_status( 'completed', '全额退款失败,状态自动恢复。' ); } $order->add_order_note( $critical_note ); } $refund->save(); $order->save(); } private function toUrlParams(array $array, $isUrlEncode) { $buff = ""; foreach ($array as $k => $v) { if ($v != "" && !is_array($v)) { $buff .= $k . "="; if ($isUrlEncode) { $buff .= urlencode($v); } else { $buff .= $v; } $buff .= "&"; } } $buff = trim($buff, "&"); return $buff; } private function request($url, array $array) { // url encode request data $paramsStr = $this->toUrlParams($array, true); $args = array( 'body' => $paramsStr, 'timeout' => '30', 'redirection' => '30', 'headers' =>array( 'content-type'=> 'application/x-www-form-urlencoded;charset=utf-8' ) ); $this->allinpay_log("发送到渠道的请求参数为:".$paramsStr); $response = wp_remote_post($url,$args); $body = wp_remote_retrieve_body( $response ); return $body; } private function generate_signature( $data ) { ksort($data, SORT_STRING); $query_string = $this->toUrlParams($data,false); $this->allinpay_log('签名串的明文为:'.$query_string); // 签名生成的字符串 $sign_data = utf8_encode($query_string); // 进行签名 $signature = ''; //$privateKey = "-----BEGIN RSA PRIVATE KEY-----\n".wordwrap($this->private_key, 64, "\n", true)."\n-----END RSA PRIVATE KEY-----"; $privateKeyResource = openssl_pkey_get_private($this->private_key); if ($privateKeyResource === false) { $error = openssl_error_string(); var_dump($error); } openssl_sign($query_string, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256); //openssl_free_key( $privateKeyResource ); return base64_encode( $signature ); } private function build_query_string($data) { $query_string = ''; foreach ($data as $key => $value) { $query_string .= $key . '=' . $value . '&'; } // 去除末尾的 '&' $query_string = rtrim($query_string, '&'); return $query_string; } //异步通知 function allinpay_payment_callback() { if (empty($_POST)) { $this->allinpay_log('后台通知返回参数为空'); return; } // 获取所有POST参数并过滤 $params = array_map('wc_clean', $_POST); $signature = $params['sign'] ?? ''; if (empty($signature)) { $this->allinpay_log('回调参数中缺少签名字段'); return; } // 检查必填参数 if (empty($params['resultCode']) || empty($params['accessOrderId'])) { $this->allinpay_log('回调参数中缺少必填字段: resultCode或accessOrderId'); echo 'SUCCESS'; wp_die(); } $customerNo = $params['accessOrderId']; $order_id = (strlen($customerNo) >= 14) ? substr($customerNo, 14) : null; if (!$order_id) { $this->allinpay_log("无效的订单号格式: $customerNo"); echo 'SUCCESS'; wp_die(); } $order = wc_get_order($order_id); if (!$order || $order->get_status() === 'completed') { echo 'SUCCESS'; wp_die(); } // 删除不需要参与签名的字段 unset( $params['sign'], $params['wc-api'] ); // 构建签名串 ksort($params); $signStr = $this->toUrlParams($params,false); $signResult = $this->verify_signature($signStr,$signature); if(!$signResult){ $this->allinpay_log('异步通知订单验签失败,订单号:'.$order_id); $this->allinpay_log('验签的字符串为:'.$signStr); $this->allinpay_log('收到异步通知的报文为'.print_r($params,1)); echo 'SUCCESS'; wp_die(); } $this->allinpay_log('收到异步通知的报文为'.print_r($params,1)); // 根据回调参数进行相应的处理逻辑 if ($params['resultCode'] === '0000') { // 更新订单状态为处理中 $order = wc_get_order($order_id); $custom_data = array( 'localCurrency' => $params['localCurrency'], 'localAmount' => $params['localAmount'] ); foreach ($custom_data as $key => $value) { $order->update_meta_data($key, $value); } $order->payment_complete($transaction_id); echo 'SUCCESS'; wp_die(); } else { $order->update_meta_data('resultCode', $params['resultCode']); $order->update_meta_data('resultDesc', $params['resultDesc']); $order->update_status( 'failed', $params['resultDesc'] ); $order->save(); echo 'SUCCESS'; wp_die(); } } function allinpay_front_payment_callback() { // 获取回调参数 if(!isset($_GET['resultCode'])){ $this->allinpay_log('前台通知返回参数异常,resultCode为空!!!'); return; } $result_code = wc_clean($_GET['resultCode']); $customerNo= wc_clean($_GET['accessOrderId']); // 从回调参数中获取订单ID $order_id = substr($customerNo,14); // 从回调参数中获取订单ID $card_no = wc_clean($_GET['cardNo']); $result_desc = wc_clean($_GET['resultDesc']); $transaction_id = wc_clean($_GET['orderId']); // 从回调参数中获取交易ID // 根据回调参数进行相应的处理逻辑 if ($result_code === '0000') { // 更新订单状态为处理中 $order = wc_get_order($order_id); $order->add_order_note(__('Payment completed via Allinpay on front-end return.')); // 处理支付成功后的逻辑,例如发送订单确认邮件、更新库存等 $redirect_url = $order->get_checkout_order_received_url(); wp_redirect($redirect_url); exit; } else { // 重定向用户到支付失败页面 $this->allinpay_log('前端页面通知订单异常!,订单号'.$order_id); $redirect_url = wc_get_page_permalink('checkout') . '?payment_status=failure'; wp_redirect($redirect_url); exit; } } private function verify_signature( $data, $signature ) { // 对数据进行 SHA256 哈希运算 $public_key_resource = openssl_pkey_get_public("-----BEGIN PUBLIC KEY-----\n" . wordwrap($this->public_key, 64, "\n", true) . "\n-----END PUBLIC KEY-----"); //$data=utf8_encode($data); $public_key_resource = openssl_pkey_get_public($this->public_key); // 对签名进行解码(通常使用 Base64 解码) $decodedSignature = base64_decode($signature); // 验签 $result = openssl_verify($data, $decodedSignature, $public_key_resource, OPENSSL_ALGO_SHA256); //openssl_free_key( $public_key_resource ); return $result === 1; } private function allinpay_log($message){ if('yes'==$this->debug_log){ if(is_array($message)|| is_object($message)){ $this->log->add('allinpay_intl',print_r($message,1)); }else{ $this->log->add('allinpay_intl',$message); } } } } function custom_payment_descriptions($description, $payment_id) { switch ($payment_id) { case 'allinpay_intl': $description .= '

This is the description for allInPay.

'; break; // Add descriptions for other payment methods as needed default: break; } return $description; } function allinpay_woocommerce_order_number($order_number, $order) { if ($order->get_date_created() instanceof WC_DateTime && $order->get_date_created()->getTimestamp() > time()) { // 新订单,使用自定义订单号生成逻辑 $custom_order_number = gmdate('YmdHis').$order->get_id(); // 这里将订单号设置为 "MY-订单ID" return $custom_order_number; } // 非新订单,保持原订单号不变 return $order_number; } function allinpay_order_id(){ $custom_order_number = gmdate('YmdHis'); // 自定义订单号生成逻辑 return 'RF'.$custom_order_number; } function allinpay_save_order_number($order_id) { $order = wc_get_order($order_id); $custom_order_number = gmdate('YmdHis') . $order_id; // 自定义订单号生成逻辑 $order->update_meta_data('custom_order_number', $custom_order_number); $order->save(); } $my_plugin = new Allinpay_INTL(); } ?>