Plugin Directory

Changeset 3258184


Ignore:
Timestamp:
03/19/2025 05:51:49 AM (13 months ago)
Author:
mustangpay
Message:

cn to en

Location:
mustangpay/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • mustangpay/trunk/mustangpay.php

    r3258140 r3258184  
    2222}
    2323
    24 // 在 WooCommerce 订单页面添加自定义退款按钮 mustangpay
    25 //add_action('woocommerce_admin_order_data_after_order_details', 'mustangpay_custom_refund_button', 10, 2); //访客下面
    26 //add_action('woocommerce_admin_order_data_after_shipping_address', 'mustangpay_custom_refund_button', 10, 2);//配送下面
    27 
    28 add_action('woocommerce_order_item_add_action_buttons', 'mustangpay_custom_refund_button', 10, 2);//配送下面
     24// Add a custom refund button 'mustangpay' on the WooCommerce order page
     25
     26add_action('woocommerce_order_item_add_action_buttons', 'mustangpay_custom_refund_button', 10, 2);
    2927
    3028remove_action('admin_init', 'check_admin_referer');
     
    3634    //is add
    3735    if ($order->get_status() == 'processing' && $merchantPayMethon=='CardPayment') {
    38         // 获取订单总金额
     36        // Get the total order amount
    3937        $order_total = $order->get_total();
    40         // 获取订单退款金额
     38        // Get the total refund amount of the order
    4139        $total_refunded = 0;
    4240        foreach ($order->get_refunds() as $refund) {
     
    9896                                success:function(data){
    9997                                    if (data.success == true) {
    100                                         //付款层高
     98                                     
    10199                                        if(data.success == true){
    102100                                            //orderStatus
     
    148146
    149147function mustangpay_custom_currency( $currencies ) {
    150     $currencies['ZAR'] = __('ZAR Currency', 'mustangpay'); // ZAR 是货币代码,'ZAR Currency' 是显示名称
     148    $currencies['ZAR'] = __('ZAR Currency', 'mustangpay'); // 'ZAR' is the currency code, and 'ZAR Currency' is the display name
    151149    return $currencies;
    152150}
     
    169167
    170168if ( PHP_VERSION_ID < 70200 ) {
    171     // 显示警告信息
     169
    172170    if ( is_admin() ) {
    173171        add_action( 'admin_notices', function ()
    174172        {
    175             // translators: %1$s 代表所需的最低 PHP 版本,%2$s 代表当前使用的 PHP 版本
    176             printf('<div class="error"><p>%s</p></div>', esc_html__('mustangpay支付需要PHP%1$s以上版本才能运行,您当前的PHP版本为%2$s,请升级到PHP到%1$s或更新的版本,否则插件没有任何作用.', 'mustangpay')); 
     173           printf('<div class="error"><p>%s</p></div>', esc_html__('The Mustangpay payment plugin requires PHP %1$s or higher to run. Your current PHP version is %2$s. Please upgrade to PHP %1$s or a later version; otherwise, the plugin will not function.', 'mustangpay'));   
    177174        } );
    178175    }
  • mustangpay/trunk/src/Init.php

    r3258140 r3258184  
    4949   
    5050    /**
    51      * 避免 TranslatePress 插件翻译签名字符串
     51     * Avoid translating signature strings with the TranslatePress plugin
    5252     */
    5353    function ignore_translate_strings( $options ) {
     
    5858
    5959    /**
    60      * 插件插件设置链接
     60     * Plugin settings link
    6161     */
    6262    function add_settings_link( $links ) {
  • mustangpay/trunk/src/MustangpayApiConstantsV1.php

    r3258143 r3258184  
    1212    const BASE_URL = 'https://openapi.mustangpay.co.za';
    1313    //The address is the official testing environment access request address for mustangpay
    14     // https://openapi-dev.mstpay-inc.com;
     14    //
    1515    const TEST_BASE_URL = 'https://openapi.mustangpay.co.za';
    1616
  • mustangpay/trunk/src/MustangpayApiUtilsV1.php

    r3258140 r3258184  
    1616{
    1717   
    18     /** @var \WC_Logger Logger 实例 */
     18    /** @var \WC_Logger Logger */
    1919    public $log = false;
    2020    /**
    21      * @var bool 日志是否启用
     21     * @var bool
    2222     */
    2323    public $is_debug_mod = false;
     
    5858       
    5959            if (isset($_POST['nonce']) && check_ajax_referer('mustangpay', 'nonce', false)) {
    60                 // 处理请求
     60                //
    6161            } else {
    62                 // Nonce 验证失败,拒绝请求
     62                // Nonce
    6363                die('Nonce verification failed');
    6464            }
    6565       
    66             // 获取订单 ID(你可以通过 AJAX 请求传递订单 ID)
     66            // get order ID
    6767            $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    6868            if ($order_id <= 0) {
     
    8989            //var_dump($return_url);exit;
    9090           
    91             // 获取 $_POST 中的 selectedPayments 数组
    92            
    93             // 检查 $_POST['selectedPayments'] 是否存在并进行清理
    9491            $payMethods = isset($_POST['selectedPayments'])
    9592                ? array_map('sanitize_text_field', $_POST['selectedPayments'])
    9693                : [];
    9794           
    98             // 定义合法的支付方式列表
    9995            $validPayMethods = ['CardPayment', 'InstantEFT'];
    10096           
    101             // 验证每个支付方式是否合法
    10297            foreach ($payMethods as $key => $method) {
    10398                if (!in_array($method, $validPayMethods)) {
    104                     // 如果存在非法支付方式,移除该元素
    10599                    unset($payMethods[$key]);
    106100                }
    107101            }
    108102           
    109             // 重新索引数组
    110103            $payMethods = array_values($payMethods);
    111104           
     
    206199       
    207200            if (isset($_POST['refund_nonce']) && check_ajax_referer('mustangpay', 'refund_nonce', false)) {
    208                 // 处理请求
     201               
    209202            } else {
    210203                 wp_send_json_error(array('message' => __( 'Nonce verification failed', 'mustangpay' )));
     
    214207            $config=new PaymentGateway();
    215208             
    216              // 验证请求是否有效
    217209            if (!isset($_POST['refund_amount']) || !isset($_POST['order_id'])) {
    218210                wp_send_json_error(array('message' => __( 'Missing refund amount or order ID', 'mustangpay' )));
    219211            }
    220212       
    221             // 获取退款金额和原因
     213            // Obtain refund amount and reason
    222214            $refund_amount = floatval($_POST['refund_amount']);
    223215           
     
    226218            $refund_reason = sanitize_text_field($_POST['refund_reason']);
    227219       
    228             // 验证退款金额和原因
     220            // Verify refund amount and reason
    229221            if ($refund_amount <= 0) {
    230222                wp_send_json_error(array('message' => __( 'Invalid refund amount', 'mustangpay' )));
     
    232224           
    233225       
    234             // 获取订单 ID(你可以通过 AJAX 请求传递订单 ID)
    235226            $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
    236227           
     
    239230            }
    240231       
    241             // 获取订单对象
    242232            $order = wc_get_order($order_id);
    243233            if (!$order) {
     
    256246            }
    257247           
    258             // 获取订单总金额
     248            // Obtain the total amount of the order
    259249            $order_total = $order->get_total();
    260             // 获取订单退款金额
     250            // Order refund amount
    261251            $total_refunded = 0;
    262252            foreach ($order->get_refunds() as $refund) {
     
    301291           
    302292            if(isset($respose['data']['orderStatus']) && $respose['data']['orderStatus'] == 'Success'){
    303                 //执行退款操作(通过 WooCommerce 的退款功能或者自定义退款逻辑)
     293                //Perform refund operation
    304294                $refund = wc_create_refund(array(
    305295                    'amount'           => $refund_amount,
    306296                    'reason'           => $refund_reason,
    307297                    'order_id'         => $order->get_id(),
    308                     'line_items'       => array(), // 可根据需要填写退款的商品项目
    309                     'refund_payment'   => false,   // 是否退款支付
    310                     'restock_items'    => true,   // 是否退还库存
     298                    'line_items'       => array(), // You can fill in the refund items as needed
     299                    'refund_payment'   => false,   // Whether to refund payment
     300                    'restock_items'    => true,   // Do you want to return the inventory
    311301                ));
    312302           
    313                 // 检查退款结果
     303                // Check the refund result
    314304                if (is_wp_error($refund)) {
    315                     wp_send_json_error(array('message' => '退款失败: ' . $refund->get_error_message()));
     305                    wp_send_json_error(array('message' => 'Refund failed: ' . $refund->get_error_message()));
    316306                }
    317307                $refund_note = 'Refund OrderNO:' . $trade_order_id; 
    318                 $order->add_order_note($refund_note);  // 将备注添加到订单的历史记录中
     308                $order->add_order_note($refund_note);  // Add notes to the order history
    319309                wp_send_json_success(array('message' => 'Refund successful', 'data' => array('orderStatus' => 'Success')));
    320310            }else if(isset($respose['data']['orderStatus']) && $respose['data']['orderStatus'] == 'Pending'){
     
    360350            if ($body === null) {
    361351                 wp_send_json_error(array('message' => __( 'Verification failed, please check if your configuration information is correct', 'mustangpay' )));
    362                 //throw new \RuntimeException("收到的响应:验签失败");
     352           
    363353            }
    364354
     
    366356
    367357        } catch (RequestException $e) {
    368             //error_log("Mustangpay接口失败: " . $e->getMessage());
    369358            return null;
    370359        }
     
    444433
    445434    private static function http_post($url, $data) {
    446         // 使用 wp_remote_post 代替 cURL
     435       
    447436        $response = wp_remote_post($url, array(
    448437            'method'    => 'POST',
     
    456445            ),
    457446            'timeout'   => 60,
    458             'sslverify' => false, // SSL 证书验证关闭
     447            'sslverify' => false,
    459448        ));
    460449   
     
    463452        }
    464453   
    465         // 获取响应体
     454       
    466455        $body = wp_remote_retrieve_body($response);
    467456   
     
    469458    }
    470459
    471 /*
    472      private static function http_post($url,$data){
    473         if(!function_exists('curl_init')){
    474             throw new Exception('php未安装curl组件',500);
    475         }
    476         $ch = curl_init();
    477         curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    478         curl_setopt($ch,CURLOPT_URL, $url);
    479         curl_setopt($ch,CURLOPT_REFERER,get_option('siteurl'));
    480         curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    481         curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    482         curl_setopt($ch, CURLOPT_HEADER, FALSE);
    483         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    484         curl_setopt($ch, CURLOPT_POST, TRUE);
    485         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    486         curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
    487         curl_setopt($ch,CURLOPT_HTTPHEADER,[
    488             "Accept-Encoding: gzip, deflate, br",
    489             "Connection: keep-alive",
    490             "Content-Type: application/json",
    491             "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
    492         ]);
    493        
    494         $response = curl_exec($ch);
    495         $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    496         $error=curl_error($ch);
    497         curl_close($ch);
    498    
    499         return $response;
    500     }
    501  */   
    502         function get_user_ip() {
     460function get_user_ip() {
    503461    $ip = '';
    504     // 检查 HTTP_X_FORWARDED_FOR 是否存在,常用于代理服务器或负载均衡器
     462    // Check if HTTP_X_FORWARDED_FOR exists, commonly used in proxy servers or load balancers
    505463    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    506464        $forwarded_for = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
    507         // 如果有多个代理,X_FORWARDED_FOR 会包含一个逗号分隔的IP链,取第一个非私有IP
     465        // If there are multiple proxies, X_FORWARDED_FOR will contain a comma-separated IP chain. Take the first non-private IP
    508466        $ip_array = explode(',', $forwarded_for);
    509         $ip = trim($ip_array[0]); // 获取第一个IP
     467        $ip = trim($ip_array[0]); // Get the first IP
    510468        $ip = filter_var($ip, FILTER_VALIDATE_IP);
    511469        if (!$ip) {
     
    513471        }
    514472    }
    515     // 如果没有 HTTP_X_FORWARDED_FOR,检查 HTTP_CLIENT_IP
     473    // If HTTP_X_FORWARDED_FOR is not available, check HTTP_CLIENT_IP
    516474    elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    517475        $client_ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
    518476        $ip = filter_var($client_ip, FILTER_VALIDATE_IP);
    519477        if (!$ip) {
    520             // 处理无效 IP 地址的情况
     478            // Handle the case of an invalid IP address
    521479            $ip = '';
    522480        }
    523481    }
    524     // 如果都没有,使用 REMOTE_ADDR
     482    // If neither of the above is available, use REMOTE_ADDR
    525483    else {
    526484        if (isset($_SERVER['REMOTE_ADDR'])) {
     
    528486            $ip = filter_var($remote_ip, FILTER_VALIDATE_IP);
    529487            if (!$ip) {
    530                 // 处理无效 IP 地址的情况
     488                // Handle the case of an invalid IP address
    531489                $ip = '';
    532490            }
     
    535493   
    536494    return $ip;
    537 }
    538    
     495}
    539496    public function get_order_title($order, $limit = 98) {
    540497        $order_id = method_exists($order, 'get_id')? $order->get_id():$order->id;
  • mustangpay/trunk/src/PaymentGateway.php

    r3258140 r3258184  
    1111class PaymentGateway extends \WC_Payment_Gateway
    1212{
    13     /** @var \WC_Logger Logger 实例 */
     13    /** @var \WC_Logger */
    1414    public $log = false;
    1515    /**
    16      * @var bool 日志是否启用
     16     * @var bool Whether the log is enabled
    1717     */
    1818    public $is_debug_mod = false;
    1919    /**
    20      * 网关支持的功能
     20     * Supported functions of the gateway
    2121     *
    2222     * @var array
     
    2929       
    3030   
    31         // 支付方法的全局 ID
     31       
    3232        $this->id = Mustangpay_Custom_Payment_ID;
    33         // 支付网关页面显示的支付网关标题
    34         //$this->method_title = __('Mustang Pay',Mustangpay_Custom_Payment);
     33       
    3534        $this->method_title = __('Mustang Pay', 'mustangpay');
    3635
    3736       
    38         //$this->method_title='12';
    39        
    40         // 支付网关设置页面显示的支付网关标题
    41         //$this->method_description = __('Mustang Pay gateway payment provides functions such as cash register payment.',Mustangpay_Custom_Payment);
    4237        $this->method_description = __('Mustang Pay gateway payment provides functions such as cash register payment.', 'mustangpay');
    43         // 被 init_settings() 加载的基础设置
     38        //  init_settings()
    4439        $this->init_form_fields();
    4540        $this->init_settings();
    4641
    47         // 前端显示的支付网关名称
     42        // The payment gateway name displayed on the front-end
    4843        $this->title = $this->get_option( 'title' );
    4944       
     
    5449        $this->title =  'Mustang Pay';
    5550       
    56         // 支付网关标题
     51        // Payment gateway title
    5752       
    5853        $this->icon = apply_filters( 'mustangpay_wechat_icon', Mustangpay_Custom_Payment_URL . '/images/pay.svg' );
     
    6358        $this->has_fields = false;
    6459        //$this->multi_currency_enabled = in_array( 'woocommerce-multilingual/wpml-woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true ) && get_option( 'icl_enable_multi_currency' ) === 'yes';
    65         // 保存设置
     60        // Save Settings
    6661        if ( is_admin() ) {
    6762            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, [ $this, 'process_admin_options' ] );
     
    6964       
    7065       
    71         // 添加 URL
     66        // add URL
    7267        add_action( 'woocommerce_api_hpj-wc-wechatpay-query', [ $this, 'query_order' ] );
    7368        add_action( 'woocommerce_api_hpj-wc-wechatpay-notify', [ $this, 'listen_notify' ] );
     
    7974   
    8075    /**
    81      * 网关设置
     76     * Gateway settings
    8277     */
    8378    public function init_form_fields() {
     
    146141                        'description'=>''
    147142                ),
    148                 /*'appid' => array(
    149                         'title'       => __( 'APP ID', Mustangpay_Custom_Payment ),
    150                         'type'        => 'text',
    151                         'css'         => 'width:400px',
    152                         'default'=>'',
    153                         'section'     => 'default',
    154                         'description'=>''
    155                 ),
    156                 'appsecret' => array(
    157                         'title'       => __( 'APP Secret', Mustangpay_Custom_Payment ),
    158                         'type'        => 'text',
    159                         'css'         => 'width:400px',
    160                         'default'=>'',
    161                         'section'     => 'default'
    162                 ),*/
    163             /*  'tranasction_url' => array(
    164                         'title'       => __( 'Transaction_url', Mustangpay_Custom_Payment ),
    165                         'type'        => 'text',
    166                         'css'         => 'width:400px',
    167                         'default'=>'http://43.135.157.188:8812',
    168                         'section'     => 'default',
    169                         'description'=>''
    170                 ),*/
    171                
    172143        );
    173144    }
    174145
    175146    /**
    176      * 管理选项
     147     * Manage Options
    177148     */
    178149    public function admin_options() { ?>
     
    201172
    202173    /**
    203      * WooCommerce 支付处理 function/method.
     174     * WooCommerce Payment Processing function/method.
    204175     *
    205176     * @inheritdoc
     
    235206
    236207    function getCurrentUrl() {
    237         // 检查是否是 HTTPS
    238         $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
    239        
    240         $host='';
    241         // 获取主机名(域名)
    242         if (isset($_SERVER['HTTP_HOST'])) {
    243             // 去除可能存在的反斜杠
    244             $host = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST']));
    245         } else {
    246             // 如果 HTTP_HOST 不存在,可以根据实际需求进行处理,比如设置为空字符串
    247             $host = '';
    248         }
    249        
    250        
    251         if (isset($_SERVER['REQUEST_URI'])) {
    252             $uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']));
    253         } else {
    254             // 如果 REQUEST_URI 不存在,可以根据实际需求进行处理,比如设置为空字符串
    255             $uri = '';
    256         }
    257    
    258         // 拼接完整 URL
    259         $url = $protocol . "://" . $host . $uri;
    260    
    261         return $url;
    262     }
     208            // Check if it is HTTPS
     209            $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
     210           
     211            $host='';
     212            // Get the hostname (domain name)
     213            if (isset($_SERVER['HTTP_HOST'])) {
     214                // Remove possible backslashes
     215                $host = sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST']));
     216            } else {
     217                // If HTTP_HOST does not exist, it can be handled according to actual needs, such as setting it to an empty string
     218                $host = '';
     219            }
     220           
     221           
     222            if (isset($_SERVER['REQUEST_URI'])) {
     223                $uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']));
     224            } else {
     225                // If REQUEST_URI does not exist, it can be handled according to actual needs, such as setting it to an empty string
     226                $uri = '';
     227            }
     228       
     229            // Concatenate the complete URL
     230            $url = $protocol . "://" . $host . $uri;
     231       
     232            return $url;
     233        }
    263234
    264235
     
    286257        //var_dump($total_amount);
    287258       
    288         //创建订单接口
     259       
    289260        $create_order_url= WC()->api_request_url('hpj-wc-mustangpay-create-order');
    290261       
     
    414385                .payment-option {
    415386                    align-items: center;
    416                     margin-right: 20px; /* 控制选项之间的间距 */
     387                    margin-right: 20px;
    417388                }
    418389               
    419390                .payment-option input[type='checkbox'] {
    420391                    margin-right: 8px;
    421                     transform: scale(1.2); /* 适当增大复选框尺寸 */
     392                    transform: scale(1.2);
    422393                }
    423394               
     
    486457                    if (\$(this).hasClass('disabled')) {
    487458                        console.log('disabled');
    488                         return; // 阻止进一步执行
     459                        return;
    489460                    }
    490461
     
    493464                    var url = '{$escaped_create_order_url}';
    494465                    \$('input[name=\"payMethod\"]:checked').each(function() {
    495                         selectedPayments.push(\$(this).val()); // 获取选中的复选框的值
     466                        selectedPayments.push(\$(this).val());
    496467                    });
    497468
     
    556527                        let currentDate = new Date();
    557528                   
    558                         // 获取年、月、日、小时、分钟、秒
     529                       
    559530                        let year = currentDate.getFullYear();
    560                         let month = currentDate.getMonth() + 1;  // 月份是从 0 开始的,所以加 1
     531                        let month = currentDate.getMonth() + 1; 
    561532                        let day = currentDate.getDate();
    562533                        let hours = currentDate.getHours();
     
    564535                        let seconds = currentDate.getSeconds();
    565536                   
    566                         // 格式化:如果小于 10 补充 0
     537                       
    567538                        month = month < 10 ? '0' + month : month;
    568539                        day = day < 10 ? '0' + day : day;
     
    571542                        seconds = seconds < 10 ? '0' + seconds : seconds;
    572543                   
    573                         // 拼接成订单号格式(YYYYMMDDHHMMSS)
     544                       
    574545                        let orderNumber = year + month + day +  hours + minutes + seconds;
    575546                        return orderNumber;
     
    593564
    594565    /**
    595      * 监听支付返回
     566     * Monitor payment returns
    596567     */
    597568    public function query_order() {
     
    646617
    647618    /**
    648      * 处理支付接口异步返回的信息
     619     * Handle the asynchronous return information from the payment interface.
    649620     */
    650621    public function listen_notify() {
    651        // $this->log('-------------------------------------');
    652        // $data = $_POST;
    653         //$this->log($data);
    654        
    655        
    656          // 1. 验证请求方法
    657         if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    658             status_header(405);
    659             exit(esc_html__('Method Not Allowed', 'mustangpay'));
    660         }
    661        
    662         $rawData = $_POST;
    663         if(empty($rawData)){
    664             $rawData = file_get_contents("php://input");
    665         }
    666      
    667         // 基础验证
    668         if (empty($rawData)) {
    669             $this->log(__('Empty notification data received', 'mustangpay'));
    670             status_header(400);
    671             exit(esc_html__('Bad Request', 'mustangpay'));
    672         }
    673        
    674        
    675         $this->log($rawData);
    676         $content=json_decode($rawData,true);
    677        
    678         //$mp=new MustangpayApiUtilsV1();
    679         $data=MustangpayApiUtilsV1::merchantDecrypt($content);
    680        
    681         $data=json_decode($data,true);
    682        
    683        if ($data === null && json_last_error()!== JSON_ERROR_NONE) {
    684             $this->log('data_json_decode_error');
    685             return;
    686         }
    687        
    688        
    689          // 5. 严格验证数据结构
    690         $required_keys = ['merchantOrderNo', 'orderStatus', 'merchantId'];
    691         foreach ($required_keys as $key) {
    692             if (!isset($data[$key])) {
    693                  exit('Missing required field:'.$key);
    694             }
    695         }
    696        
    697        
    698         $merchantOrderNo = sanitize_text_field(wp_unslash($data['merchantOrderNo']));
    699        
    700         $orderStatus = sanitize_text_field(wp_unslash($data['orderStatus']));
    701          
    702         $merchantId = sanitize_text_field(wp_unslash($data['merchantId']));
    703        
     622        // $this->log('-------------------------------------');
     623        // $data = $_POST;
     624        // $this->log($data);
     625   
     626        // 1. Validate the request method
     627        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
     628            status_header(405);
     629            exit(esc_html__('Method Not Allowed', 'mustangpay'));
     630        }
     631   
     632        $rawData = $_POST;
     633        if (empty($rawData)) {
     634            $rawData = file_get_contents("php://input");
     635        }
     636   
     637        // Basic validation
     638        if (empty($rawData)) {
     639            $this->log(__('Empty notification data received', 'mustangpay'));
     640            status_header(400);
     641            exit(esc_html__('Bad Request', 'mustangpay'));
     642        }
     643   
     644        $this->log($rawData);
     645        $content = json_decode($rawData, true);
     646   
     647        // $mp = new MustangpayApiUtilsV1();
     648        $data = MustangpayApiUtilsV1::merchantDecrypt($content);
     649   
     650        $data = json_decode($data, true);
     651   
     652        if ($data === null && json_last_error()!== JSON_ERROR_NONE) {
     653            $this->log('data_json_decode_error');
     654            return;
     655        }
     656   
     657        // 5. Strictly validate the data structure
     658        $required_keys = ['merchantOrderNo', 'orderStatus', 'merchantId'];
     659        foreach ($required_keys as $key) {
     660            if (!isset($data[$key])) {
     661                exit('Missing required field: ' . $key);
     662            }
     663        }
     664   
     665        $merchantOrderNo = sanitize_text_field(wp_unslash($data['merchantOrderNo']));
     666        $orderStatus = sanitize_text_field(wp_unslash($data['orderStatus']));
     667        $merchantId = sanitize_text_field(wp_unslash($data['merchantId']));
     668   
    704669        if (!is_numeric($merchantId)) {
    705             exit('merchant Id is not a valid number!');
    706         }
    707        
    708        
    709         // 验证 $orderStatus 是否为 success 或者 error
    710         if (!in_array($orderStatus, ['Success', 'Error'])) {
    711             exit('OrderStatus must be either success or error');
    712         }
    713          
     670            exit('merchant Id is not a valid number!');
     671        }
     672   
     673        // Validate if $orderStatus is either success or error
     674        if (!in_array($orderStatus, ['Success', 'Error'])) {
     675            exit('OrderStatus must be either Success or Error');
     676        }
     677   
    714678        $parts = explode("_", $merchantOrderNo);
    715         // 验证分割后数组长度是否足够
    716         if (count($parts) < 2) {
    717             exit('merchantOrderNo Error!');
    718         }
    719      
    720         $order_id = $parts[1];
    721         // 验证 $order_id 是否为有效的数字
    722         if (!is_numeric($order_id)) {
    723             exit('The obtained order ID is not a valid number!');
    724         }
    725 
    726        
    727         $order = wc_get_order($order_id);
    728         if(!$order){
    729             exit(esc_html__('Unknow Order (id:'.esc_html($order_id).')', 'mustangpay'));
    730         }
    731      
    732         if(!(method_exists($order, 'is_paid')?$order->is_paid():in_array($order->get_status(),  array( 'processing', 'completed' )))&&$data['orderStatus']=='Success'){
    733             $this->log('payment_complete');
    734             $order->payment_complete($merchantOrderNo);
    735             //$order->payment_complete($data['transacton_id']);
    736             WC()->cart->empty_cart();
    737             update_post_meta($order_id, '_merchant_order_no', $merchantOrderNo);
    738             // translators: %s 代表交易的商户订单号
    739             $order->add_order_note(sprintf( __( 'payment complete (Transaction ID: %s)', 'mustangpay' ),$merchantOrderNo));
    740            
    741             $mp=$this->get_order($merchantId,$merchantOrderNo);
    742             if(empty($mp)){
    743                 $this->log('Order status not obtained:'.$merchantOrderNo);
    744             }else{
    745                 update_post_meta($order_id, '_merchant_order_pay_method',$mp);
    746             }
    747            
    748         }
    749         print 'SUCCESS';
    750         exit;
    751     }
    752    
     679        // Validate if the length of the split array is sufficient
     680        if (count($parts) < 2) {
     681            exit('merchantOrderNo Error!');
     682        }
     683   
     684        $order_id = $parts[1];
     685        // Validate if $order_id is a valid number
     686        if (!is_numeric($order_id)) {
     687            exit('The obtained order ID is not a valid number!');
     688        }
     689   
     690        $order = wc_get_order($order_id);
     691        if (!$order) {
     692            exit(esc_html__('Unknown Order (id: ' . esc_html($order_id) . ')', 'mustangpay'));
     693        }
     694   
     695        if (!(method_exists($order, 'is_paid')? $order->is_paid() : in_array($order->get_status(), array('processing', 'completed'))) && $data['orderStatus'] == 'Success') {
     696            $this->log('payment_complete');
     697            $order->payment_complete($merchantOrderNo);
     698            // $order->payment_complete($data['transacton_id']);
     699            WC()->cart->empty_cart();
     700            update_post_meta($order_id, '_merchant_order_no', $merchantOrderNo);
     701            // translators: %s represents the merchant order number of the transaction
     702            $order->add_order_note(sprintf(__('Payment complete (Transaction ID: %s)', 'mustangpay'), $merchantOrderNo));
     703   
     704            $mp = $this->get_order($merchantId, $merchantOrderNo);
     705            if (empty($mp)) {
     706                $this->log('Order status not obtained: ' . $merchantOrderNo);
     707            } else {
     708                update_post_meta($order_id, '_merchant_order_pay_method', $mp);
     709            }
     710        }
     711        print 'SUCCESS';
     712        exit;
     713    }   
    753714    public function listen_refund() {
    754715        print 'SUCCESS';
     
    769730    }
    770731
    771 /*    private function http_post($url,$data){
    772         if(!function_exists('curl_init')){
    773             throw new Exception('php未安装curl组件',500);
    774         }
    775         $ch = curl_init();
    776         curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    777         curl_setopt($ch,CURLOPT_URL, $url);
    778         curl_setopt($ch,CURLOPT_REFERER,get_option('siteurl'));
    779         curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    780         curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    781         curl_setopt($ch, CURLOPT_HEADER, FALSE);
    782         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    783         curl_setopt($ch, CURLOPT_POST, TRUE);
    784         curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    785         $response = curl_exec($ch);
    786         $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    787         $error=curl_error($ch);
    788         curl_close($ch);
    789    
    790         return $response;
    791     }*/
     732
    792733   
    793734   
    794735private function http_post($url, $data) {
    795     // 检查是否启用了 HTTP 请求功能
     736    // Check if the wp_remote_post function exists
    796737    if (!function_exists('wp_remote_post')) {
    797          wp_send_json_error(array('message' => __( 'WordPress HTTP request function wp_remote_post is not available' )));
     738        wp_send_json_error(array('message' => __('WordPress HTTP request function wp_remote_post is not available')));
    798739    }
    799740
    800     // 定义请求头
     741    // Set request headers
    801742    $headers = array(
    802         'Content-Type'  => 'application/json',
    803         'User-Agent'    => 'PostmanRuntime/1.1.0',
    804         'Accept'        => '*/*',
     743        'Content-Type' => 'application/json',
     744        'User-Agent' => 'PostmanRuntime/1.1.0',
     745        'Accept' => '*/*',
    805746        'Accept-Encoding' => 'gzip, deflate, br',
    806747    );
    807748
    808     // 使用 wp_remote_post 发送请求
     749    // Send the request using wp_remote_post
    809750    $response = wp_remote_post($url, array(
    810         'body'        => $data,  // 请求体(数据)
    811         'headers'     => $headers,  // 请求头
    812         'timeout'     => 60,  // 设置超时时间
    813         'sslverify'   => false,  // 禁用 SSL 验证(视需求可更改)
     751        'body' => $data, // Request body (data)
     752        'headers' => $headers, // Request headers
     753        'timeout' => 60, // Set the timeout
     754        'sslverify' => false, // Disable SSL verification (can be changed as needed)
    814755    ));
    815756
    816     // 检查是否有错误
     757    // Check for errors
    817758    if (is_wp_error($response)) {
    818759        $error_message = $response->get_error_message();
    819          wp_send_json_error(array('message' => "Request failed: ".esc_html($error_message)));
     760        wp_send_json_error(array('message' => "Request failed: ".esc_html($error_message)));
    820761    }
    821762
    822     // 获取响应数据
     763    // Get the response body
    823764    $response_body = wp_remote_retrieve_body($response);
    824765    return $response_body;
    825 }
     766}   
    826767   
    827    
    828    /* public function isWebApp(){
    829         $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    830         $mobile_browser = '0';
    831         if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
    832             $mobile_browser++;
    833         if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false))
    834             $mobile_browser++;
    835         if(isset($_SERVER['HTTP_X_WAP_PROFILE']))
    836             $mobile_browser++;
    837         if(isset($_SERVER['HTTP_PROFILE']))
    838             $mobile_browser++;
    839            
    840         $mobile_ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower(substr(sanitize_text_field($_SERVER['HTTP_USER_AGENT']), 0, 4)) : '';
    841    
    842            
    843        // $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
    844         $mobile_agents = array(
    845             'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    846             'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    847             'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    848             'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    849             'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    850             'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    851             'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    852             'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    853             'wapr','webc','winw','winw','xda','xda-'
    854             );
    855         if(in_array($mobile_ua, $mobile_agents))
    856             $mobile_browser++;
    857         if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
    858             $mobile_browser++;
    859         // Pre-final check to reset everything if the user is on Windows
    860         if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
    861             $mobile_browser=0;
    862         // But WP7 is also Windows, with a slightly different characteristic
    863         if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
    864             $mobile_browser++;
    865         if($mobile_browser>0)
    866             return true;
    867         else
    868             return false;
    869     }*/
     768 
    870769
    871770    public function get_order_title($order, $limit = 98) {
     
    891790   
    892791   
    893     function get_user_ip() {
     792function get_user_ip() {
    894793    $ip = '';
    895     // 检查 HTTP_X_FORWARDED_FOR 是否存在,常用于代理服务器或负载均衡器
     794    // Check if HTTP_X_FORWARDED_FOR exists, commonly used in proxy servers or load balancers
    896795    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    897796        $forwarded_for = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
    898         // 如果有多个代理,X_FORWARDED_FOR 会包含一个逗号分隔的IP链,取第一个非私有IP
     797        // If there are multiple proxies, X_FORWARDED_FOR will contain a comma-separated IP chain. Take the first non-private IP
    899798        $ip_array = explode(',', $forwarded_for);
    900         $ip = trim($ip_array[0]); // 获取第一个IP
     799        $ip = trim($ip_array[0]); // Get the first IP
    901800        $ip = filter_var($ip, FILTER_VALIDATE_IP);
    902801        if (!$ip) {
     
    904803        }
    905804    }
    906     // 如果没有 HTTP_X_FORWARDED_FOR,检查 HTTP_CLIENT_IP
     805    // If HTTP_X_FORWARDED_FOR is not available, check HTTP_CLIENT_IP
    907806    elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    908807        $client_ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
    909808        $ip = filter_var($client_ip, FILTER_VALIDATE_IP);
    910809        if (!$ip) {
    911             // 处理无效 IP 地址的情况
     810            // Handle the case of an invalid IP address
    912811            $ip = '';
    913812        }
    914813    }
    915     // 如果都没有,使用 REMOTE_ADDR
     814    // If neither of the above is available, use REMOTE_ADDR
    916815    else {
    917816        if (isset($_SERVER['REMOTE_ADDR'])) {
     
    919818            $ip = filter_var($remote_ip, FILTER_VALIDATE_IP);
    920819            if (!$ip) {
    921                 // 处理无效 IP 地址的情况
     820                // Handle the case of an invalid IP address
    922821                $ip = '';
    923822            }
     
    926825   
    927826    return $ip;
    928 }
     827}   
    929828   
    930829    /**
    931      * Logger 辅助功能
     830     * Logger
    932831     *
    933832     * @param $message
Note: See TracChangeset for help on using the changeset viewer.