Проблема с плагином кастомной оплаты?
По факту, сделать получилось.
Ссылка на оплату конфигурируется, всё работает по API.
Но есть проблема, при нажатии "Place Order" - ссылка в консоли сконфигурирована, но всё равно выдаёт ошибку платежа и на страницу оплаты не переходит.
Код плагина
Для конфиденциальности сенситив инфу заменил на ***
<?php /* Plugin Name: Pay Gateway Description: Custom Payment Gateway Author: Zutov Version: 1.0 */ add_filter('woocommerce_payment_gateways', '*****_add_gateway_class'); function milky_pay_add_gateway_class($gateways) { $gateways[] = 'WC_*****_Gateway'; return $gateways; } add_action('plugins_loaded', '*******_init_gateway_class'); function ******_init_gateway_class() { class WC_*******_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = '*****'; $this->method_title = '******'; $this->method_description = 'Оплата через ******'; $this->init_form_fields(); $this->init_settings(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->enabled = $this->get_option('enabled'); $this->testmode = $this->get_option('testmode') === 'yes' ? true : false; add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); } public function init_form_fields(){ $this->form_fields = array( 'enabled' => array( 'title' => 'Включить/Выключить', 'type' => 'checkbox', 'label' => 'Включить ******', 'default' => 'no' ), 'title' => array( 'title' => 'Название', 'type' => 'text', 'description' => 'Название метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => '******', 'desc_tip' => true, ), 'description' => array( 'title' => 'Описание', 'type' => 'textarea', 'description' => 'Описание метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => 'Оплата с помощью ******, ), 'testmode' => array( 'title' => 'Тестовый режим', 'type' => 'checkbox', 'label' => 'Включить тестовый режим', 'default' => 'yes', 'description' => 'В этом режиме платежи будут симулироваться, как если бы они проходили через платёжный шлюз ******.', ), 'api_key' => array( 'title' => 'API ключ', 'type' => 'text', 'description' => 'Ваш API ключ от ********.', ), ); } public function process_payment($order_id) { $order = wc_get_order($order_id); $total = $order->get_total(); $currency = get_woocommerce_currency(); $return_url = $this->get_return_url($order); $callback_url = 'https://example.com/payments/callback'; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => '*********, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "data": { "type": "payment-invoices", "attributes": { "reference_id": "'. $order_id .'", "description": "Payment by order#'. $order_id .'", "currency": "'. $currency .'", "amount": '. $total .', "service": "payment_card_eur_hpp", "return_url": "'. $return_url .'", "callback_url": "'. $callback_url .'", "test_mode": true } } }', CURLOPT_HTTPHEADER => array( 'Authorization: Basic ********************************************* 'Content-Type: application/json' ), )); $response = curl_exec($curl); echo '<pre>'; print_r(json_decode($response, true)); echo '</pre>'; curl_close($curl); $response_body = json_decode($response, true); if (isset($response_body['data']['attributes']['redirect_url'])) { $redirect_url = $response_body['data']['attributes']['redirect_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; } } } } |
<?php /* Plugin Name: Pay Gateway Description: Custom Payment Gateway Author: Zutov Version: 1.0 */ add_filter('woocommerce_payment_gateways', '*****_add_gateway_class'); function milky_pay_add_gateway_class($gateways) { $gateways[] = 'WC_*****_Gateway'; return $gateways; } add_action('plugins_loaded', '*******_init_gateway_class'); function ******_init_gateway_class() { class WC_*******_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = '*****'; $this->method_title = '******'; $this->method_description = 'Оплата через ******'; $this->init_form_fields(); $this->init_settings(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->enabled = $this->get_option('enabled'); $this->testmode = $this->get_option('testmode') === 'yes' ? true : false; add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); } public function init_form_fields(){ $this->form_fields = array( 'enabled' => array( 'title' => 'Включить/Выключить', 'type' => 'checkbox', 'label' => 'Включить ******', 'default' => 'no' ), 'title' => array( 'title' => 'Название', 'type' => 'text', 'description' => 'Название метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => '******', 'desc_tip' => true, ), 'description' => array( 'title' => 'Описание', 'type' => 'textarea', 'description' => 'Описание метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => 'Оплата с помощью ******, ), 'testmode' => array( 'title' => 'Тестовый режим', 'type' => 'checkbox', 'label' => 'Включить тестовый режим', 'default' => 'yes', 'description' => 'В этом режиме платежи будут симулироваться, как если бы они проходили через платёжный шлюз ******.', ), 'api_key' => array( 'title' => 'API ключ', 'type' => 'text', 'description' => 'Ваш API ключ от ********.', ), ); } public function process_payment($order_id) { $order = wc_get_order($order_id); $total = $order->get_total(); $currency = get_woocommerce_currency(); $return_url = $this->get_return_url($order); $callback_url = 'https://example.com/payments/callback'; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => '*********, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "data": { "type": "payment-invoices", "attributes": { "reference_id": "'. $order_id .'", "description": "Payment by order#'. $order_id .'", "currency": "'. $currency .'", "amount": '. $total .', "service": "payment_card_eur_hpp", "return_url": "'. $return_url .'", "callback_url": "'. $callback_url .'", "test_mode": true } } }', CURLOPT_HTTPHEADER => array( 'Authorization: Basic ********************************************* 'Content-Type: application/json' ), )); $response = curl_exec($curl); echo '<pre>'; print_r(json_decode($response, true)); echo '</pre>'; curl_close($curl); $response_body = json_decode($response, true); if (isset($response_body['data']['attributes']['redirect_url'])) { $redirect_url = $response_body['data']['attributes']['redirect_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; } } } }
Дополнительно
И вот какой ответ я получаю
<pre>Array ( [data] => Array ( [type] => payment-invoices [id] => ********* [attributes] => Array ( [status] => process_pending [serial_number] => ft9Y4rHkICbylNlY [resolution] => ok [moderation_required] => [amount] => 159 [payment_amount] => 159 [currency] => EUR [service_amount] => [payment_service_amount] => [exchange_rate] => [service_currency] => EUR [reference_id] => 1548 [test_mode] => 1 [description] => Payment by order#1548 [descriptor] => [fee] => 0 [deposit] => 159 [processed] => [processed_amount] => [refunded_amount] => [refunded_fee] => [processed_fee] => [processed_deposit] => [metadata] => Array ( ) [flow_data] => Array ( [action] => https://checkout****************** [method] => GET [params] => Array ( ) [metadata] => Array ( [sid] => ************ [token] => ************ ) ) [flow] => hpp [payment_flow] => charge [return_url] => https://************/checkout/order-received/1548/?key=wc_order_iyuzm8bWMjmhg [return_urls] => Array ( ) [callback_url] => https://example.com/payments/callback [created] => 1709026847 [updated] => 1709026847 [payload] => [original_data] => Array ( ) [rrn] => [arn] => [approval_code] => [reserved_amount] => [reserve_expires] => [unreserved] => [source] => merchant_api [callback_logs] => Array ( ) [charged_back_amount] => [hpp_url] => https://***************/redirect/hpp/?cpi=cpi_ft9Y4rHkICbylNlY [ledger_payload] => ) [relationships] => Array ( [payment-service] => Array ( [data] => Array ( [type] => payment-services [id] => payment_card_eur_hpp ) ) [payment-method] => Array ( [data] => Array ( [type] => payment-methods [id] => payment_card ) ) [payment-request] => Array ( [data] => Array ( [type] => payment-requests [id] => *********** ) ) [active-payment] => Array ( [data] => Array ( [type] => payments [id] => ************** ) ) [commerce-account] => Array ( [data] => Array ( [type] => commerce-accounts [id] => coma_************ ) ) [currency-account] => Array ( [data] => Array ( [type] => currency-accounts [id] => comca_*********** ) ) [customer] => Array ( [data] => ) ) [links] => Array ( [self] => /commerce/payment-invoices/************ ) ) ) </pre>{"result":"failure","messages":"<ul class="woocommerce-error" role="alert">nttt<li>ntttu041eu0448u0438u0431u043au0430 u043fu0440u0438 u043eu0431u0440u0430u0431u043eu0442u043au0435 u043fu043bu0430u0442u0435u0436u0430.tt</li>nt</ul>n","refresh":false,"reload":false} |
<pre>Array ( [data] => Array ( [type] => payment-invoices [id] => ********* [attributes] => Array ( [status] => process_pending [serial_number] => ft9Y4rHkICbylNlY [resolution] => ok [moderation_required] => [amount] => 159 [payment_amount] => 159 [currency] => EUR [service_amount] => [payment_service_amount] => [exchange_rate] => [service_currency] => EUR [reference_id] => 1548 [test_mode] => 1 [description] => Payment by order#1548 [descriptor] => [fee] => 0 [deposit] => 159 [processed] => [processed_amount] => [refunded_amount] => [refunded_fee] => [processed_fee] => [processed_deposit] => [metadata] => Array ( ) [flow_data] => Array ( [action] => https://checkout****************** [method] => GET [params] => Array ( ) [metadata] => Array ( [sid] => ************ [token] => ************ ) ) [flow] => hpp [payment_flow] => charge [return_url] => https://************/checkout/order-received/1548/?key=wc_order_iyuzm8bWMjmhg [return_urls] => Array ( ) [callback_url] => https://example.com/payments/callback [created] => 1709026847 [updated] => 1709026847 [payload] => [original_data] => Array ( ) [rrn] => [arn] => [approval_code] => [reserved_amount] => [reserve_expires] => [unreserved] => [source] => merchant_api [callback_logs] => Array ( ) [charged_back_amount] => [hpp_url] => https://***************/redirect/hpp/?cpi=cpi_ft9Y4rHkICbylNlY [ledger_payload] => ) [relationships] => Array ( [payment-service] => Array ( [data] => Array ( [type] => payment-services [id] => payment_card_eur_hpp ) ) [payment-method] => Array ( [data] => Array ( [type] => payment-methods [id] => payment_card ) ) [payment-request] => Array ( [data] => Array ( [type] => payment-requests [id] => *********** ) ) [active-payment] => Array ( [data] => Array ( [type] => payments [id] => ************** ) ) [commerce-account] => Array ( [data] => Array ( [type] => commerce-accounts [id] => coma_************ ) ) [currency-account] => Array ( [data] => Array ( [type] => currency-accounts [id] => comca_*********** ) ) [customer] => Array ( [data] => ) ) [links] => Array ( [self] => /commerce/payment-invoices/************ ) ) ) </pre>{"result":"failure","messages":"<ul class="woocommerce-error" role="alert">nttt<li>ntttu041eu0448u0438u0431u043au0430 u043fu0440u0438 u043eu0431u0440u0430u0431u043eu0442u043au0435 u043fu043bu0430u0442u0435u0436u0430.tt</li>nt</ul>n","refresh":false,"reload":false}
И соответсвенно пользователя не редиректит на страницу оплаты - выдаёт ошибку, хотя ссылку сгенерировал.
Спасибо заранее за помощь!
Михаил Р. @Mike_Ro Python, JS, WordPress, SEO, Bots, Adversting Здесь что лежит?
$response_body['data']['attributes']['redirect_url']; |
$response_body['data']['attributes']['redirect_url'];
А здесь?
$response_body['data']['attributes'];
Подозреваю, что нужно так:
$response_body['data']['attributes']['hpp_url'];
Еще интересный момент со статусом оплаты [status] => process_pending, возможно, платеж еще не обработан и нужно время.
- Ты гений)))
- @Mike_Ro
Сработало, но почему-то в woocommerce даже если платёж не одобрен возвращает на страницу с якобы удачной страницей выполнения заказа.
Хотя платёж не прошёл. -
Еще интересный момент со статусом оплаты [status] => process_pending, возможно, платеж еще не обработан и нужно время.
Это норм, человека должно перекинуть по ссылке - и статус проведения платежа мы получим только после оплаты на той странице.
- zutov,
Сработало, но почему-то в woocommerce даже если платёж не одобрен возвращает на страницу с якобы удачной страницей выполнения заказа.
Хотя платёж не прошёл.Все верно, т.к. у Вас всего 1 условие проверки платежа, и то проверяет не статус платежа, а его факт:
if (isset($response_body['data']['attributes']['redirect_url'])) { $redirect_url = $response_body['data']['attributes']['redirect_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; }
if (isset($response_body['data']['attributes']['redirect_url'])) { $redirect_url = $response_body['data']['attributes']['redirect_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; }
Для проверки статуса, Вам необходимо обратиться в WC wc_get_order() примерно со следующим кодом:
$order_id = $_GET['order_id']; $payment_status = $_GET['payment_status']; $order = wc_get_order($order_id); if ($payment_status == 'success') { $order->payment_complete(); $order->add_order_note('The payment has been processed successfully.'); } else { $order->update_status('failed', 'The payment failed.'); }
$order_id = $_GET['order_id']; $payment_status = $_GET['payment_status']; $order = wc_get_order($order_id); if ($payment_status == 'success') { $order->payment_complete(); $order->add_order_note('The payment has been processed successfully.'); } else { $order->update_status('failed', 'The payment failed.'); }
- @Mike_Ro
Всё равно не работает, что интересно.
Я уже несколько часов копаюсь, посмотри.<?php /* Plugin Name: ***** Pay Gateway Description: Custom Payment Gateway for ***** Pay Author: Zutov Version: 1.0 */ add_filter('woocommerce_payment_gateways', '*****_pay_add_gateway_class'); function ****_pay_add_gateway_class($gateways) { $gateways[] = 'WC_****_Pay_Gateway'; return $gateways; } add_action('plugins_loaded', '*****_pay_init_gateway_class'); function *****_pay_init_gateway_class() { class WC_*****_Pay_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = '*****_pay'; $this->method_title = '***** Pay'; $this->method_description = 'Custom Payment Gateway for ***** Pay'; $this->init_form_fields(); $this->init_settings(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->enabled = $this->get_option('enabled'); $this->testmode = $this->get_option('testmode') === 'yes' ? true : false; add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); } public function init_form_fields(){ $this->form_fields = array( 'enabled' => array( 'title' => 'Включить/Выключить', 'type' => 'checkbox', 'label' => 'Включить ***** Pay Gateway', 'default' => 'no' ), 'title' => array( 'title' => 'Название', 'type' => 'text', 'description' => 'Название метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => '***** Pay', 'desc_tip' => true, ), 'description' => array( 'title' => 'Описание', 'type' => 'textarea', 'description' => 'Описание метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => 'Оплата с помощью ***** Pay.', ), 'testmode' => array( 'title' => 'Тестовый режим', 'type' => 'checkbox', 'label' => 'Включить тестовый режим', 'default' => 'yes', 'description' => 'В этом режиме платежи будут симулироваться, как если бы они проходили через платёжный шлюз ***** Pay.', ), 'api_key' => array( 'title' => 'API ключ', 'type' => 'text', 'description' => 'Ваш API ключ от ***** Pay.', ), ); } public function process_payment($order_id) { $order = wc_get_order($order_id); $total = $order->get_total(); $currency = get_woocommerce_currency(); $return_url = $this->get_return_url($order); $callback_url = 'https://*******tech.com/*****_pay_callback'; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://***********/payment-invoices', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "data": { "type": "payment-invoices", "attributes": { "reference_id": "'. $order_id .'", "description": "Payment by order#'. $order_id .'", "currency": "'. $currency .'", "amount": '. $total .', "service": "payment_card_eur_hpp", "return_url": "'. $return_url .'", "callback_url": "'. $callback_url .'", "test_mode": true } } }', CURLOPT_HTTPHEADER => array( 'Authorization: Basic Y29tYV9OZ0dsU0I2VWdidUFCc1pYOjVqQWw0MkdzbGZTcjhVcTllRFF3bTBjNU1YVDM3MDFXYTZmaWh6Q00tVEU=', 'Content-Type: application/json' ), )); $response = curl_exec($curl); error_log('***** Pay API Response: ' . print_r($response, true)); curl_close($curl); $response_body = json_decode($response, true); if (isset($response_body['data']['attributes']['hpp_url'])) { $redirect_url = $response_body['data']['attributes']['hpp_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; } } } } // Добавление endpoint для обработки callback от ***** Pay function add_*****_pay_callback_endpoint() { add_rewrite_endpoint('*****_pay_callback', EP_ROOT); } add_action('init', 'add_*****_pay_callback_endpoint'); // Обработка запросов к endpoint function handle_*****_pay_callback() { global $wp_query; if (!isset($wp_query->query_vars['*****_pay_callback'])) { return; } $request_body = file_get_contents('php://input'); $data = json_decode($request_body, true); error_log('***** Pay Callback Data: ' . print_r($data, true)); if (isset($data['status'])) { $order_id = $data['reference_id']; // Убедитесь, что это правильный ключ для идентификатора заказа $order = wc_get_order($order_id); if (!$order) { error_log('Order not found: ' . $order_id); return; } switch ($data['status']) { case 'processed': $order->update_status('completed', 'Платеж успешно обработан через ***** Pay'); break; case 'process_failed': $order->update_status('failed', 'Ошибка при обработке платежа через ***** Pay'); break; case 'process_pending': $order->update_status('processing', 'Платёж в обработке через ***** Pay'); break; } } status_header(200); echo 'Callback received and processed'; exit; } add_action('template_redirect', 'handle_*****_pay_callback');
<?php /* Plugin Name: ***** Pay Gateway Description: Custom Payment Gateway for ***** Pay Author: Zutov Version: 1.0 */ add_filter('woocommerce_payment_gateways', '*****_pay_add_gateway_class'); function ****_pay_add_gateway_class($gateways) { $gateways[] = 'WC_****_Pay_Gateway'; return $gateways; } add_action('plugins_loaded', '*****_pay_init_gateway_class'); function *****_pay_init_gateway_class() { class WC_*****_Pay_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = '*****_pay'; $this->method_title = '***** Pay'; $this->method_description = 'Custom Payment Gateway for ***** Pay'; $this->init_form_fields(); $this->init_settings(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->enabled = $this->get_option('enabled'); $this->testmode = $this->get_option('testmode') === 'yes' ? true : false; add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); } public function init_form_fields(){ $this->form_fields = array( 'enabled' => array( 'title' => 'Включить/Выключить', 'type' => 'checkbox', 'label' => 'Включить ***** Pay Gateway', 'default' => 'no' ), 'title' => array( 'title' => 'Название', 'type' => 'text', 'description' => 'Название метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => '***** Pay', 'desc_tip' => true, ), 'description' => array( 'title' => 'Описание', 'type' => 'textarea', 'description' => 'Описание метода оплаты, которое видит пользователь при оформлении заказа.', 'default' => 'Оплата с помощью ***** Pay.', ), 'testmode' => array( 'title' => 'Тестовый режим', 'type' => 'checkbox', 'label' => 'Включить тестовый режим', 'default' => 'yes', 'description' => 'В этом режиме платежи будут симулироваться, как если бы они проходили через платёжный шлюз ***** Pay.', ), 'api_key' => array( 'title' => 'API ключ', 'type' => 'text', 'description' => 'Ваш API ключ от ***** Pay.', ), ); } public function process_payment($order_id) { $order = wc_get_order($order_id); $total = $order->get_total(); $currency = get_woocommerce_currency(); $return_url = $this->get_return_url($order); $callback_url = 'https://*******tech.com/*****_pay_callback'; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://***********/payment-invoices', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "data": { "type": "payment-invoices", "attributes": { "reference_id": "'. $order_id .'", "description": "Payment by order#'. $order_id .'", "currency": "'. $currency .'", "amount": '. $total .', "service": "payment_card_eur_hpp", "return_url": "'. $return_url .'", "callback_url": "'. $callback_url .'", "test_mode": true } } }', CURLOPT_HTTPHEADER => array( 'Authorization: Basic Y29tYV9OZ0dsU0I2VWdidUFCc1pYOjVqQWw0MkdzbGZTcjhVcTllRFF3bTBjNU1YVDM3MDFXYTZmaWh6Q00tVEU=', 'Content-Type: application/json' ), )); $response = curl_exec($curl); error_log('***** Pay API Response: ' . print_r($response, true)); curl_close($curl); $response_body = json_decode($response, true); if (isset($response_body['data']['attributes']['hpp_url'])) { $redirect_url = $response_body['data']['attributes']['hpp_url']; return array( 'result' => 'success', 'redirect' => $redirect_url, ); } else { wc_add_notice('Ошибка при обработке платежа.', 'error'); return; } } } } // Добавление endpoint для обработки callback от ***** Pay function add_*****_pay_callback_endpoint() { add_rewrite_endpoint('*****_pay_callback', EP_ROOT); } add_action('init', 'add_*****_pay_callback_endpoint'); // Обработка запросов к endpoint function handle_*****_pay_callback() { global $wp_query; if (!isset($wp_query->query_vars['*****_pay_callback'])) { return; } $request_body = file_get_contents('php://input'); $data = json_decode($request_body, true); error_log('***** Pay Callback Data: ' . print_r($data, true)); if (isset($data['status'])) { $order_id = $data['reference_id']; // Убедитесь, что это правильный ключ для идентификатора заказа $order = wc_get_order($order_id); if (!$order) { error_log('Order not found: ' . $order_id); return; } switch ($data['status']) { case 'processed': $order->update_status('completed', 'Платеж успешно обработан через ***** Pay'); break; case 'process_failed': $order->update_status('failed', 'Ошибка при обработке платежа через ***** Pay'); break; case 'process_pending': $order->update_status('processing', 'Платёж в обработке через ***** Pay'); break; } } status_header(200); echo 'Callback received and processed'; exit; } add_action('template_redirect', 'handle_*****_pay_callback');
- @Mike_Ro
Что по факту было проделано - добавлен endpoint, в который заходит инфа от API платёжного шлюза
Заходит успешно, по логам видно.
Также было замечено что идентификаторы статуса платежа в Woocomerce и в шлюзе разные - для этого был добавлен switch.Ошибок нет никаких.
Но всё же, статус оплаты никак не меняется.
Вот тут тупик, правда (часов 6 не могу с мёртвой точки сдвинуться)P.S Важно, что сам прцоесс платежа работает идеально, редиректит отлично (за что Михаил Р. спасибо), отправляет статус платежа, в логах его видно, в платёжке тоже, видно что он отправлен. Но статус не меняется.
- zutov, слегка не понятно, что именно не работает (после основной работы, десятков вопросов на этом сайте и этой простыни кода), значит:
1. Редирект после попытки оплаты происходит успешно?
2. Статус в WC не изменяется, хотя оплата прошла успешно? - Михаил Р.:
1) Да, даже после неудачной оплаты - всё равно отправляет на экран с якобы прошедшей оплатой (в это логике WP я ничего не менял.)
2) Не важно как, успешно или нет - статус стоит Pending Payment.
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос

Если ссылка оплаты в консоли сформирована, но WooCommerce всё равно показывает ошибку платежа и не редиректит, чаще всего метод
process_payment()возвращает не тот формат. В checkout WooCommerce ждёт массивresult/redirect, а не простой echo, console log или прямой редирект.Должно быть так:
public function process_payment($order_id) { $order = wc_get_order($order_id); $payment_url = $this->create_payment_url($order); if (! $payment_url) { wc_add_notice('Не удалось создать ссылку на оплату.', 'error'); return ['result' => 'failure']; } $order->update_status('pending', 'Ожидает оплаты.'); return [ 'result' => 'success', 'redirect' => $payment_url, ]; }
Если внутри есть PHP warning/notice, AJAX checkout получит невалидный JSON и WooCommerce покажет общую ошибку оплаты. Поэтому включите лог WooCommerce и проверьте response в Network.
Также проверьте, что URL начинается с
https://, не содержит лишнего пробела и не экранирован дважды. После оплаты статус меняйте только через callback/webhook, а не сразу при создании ссылки.Итог: проблема обычно не в API, если ссылка реально создаётся, а в ответе метода оплаты WooCommerce. Верните корректный массив success + redirect и проверьте AJAX response.