@zutov

Проблема с плагином кастомной оплаты?

По факту, сделать получилось.
Ссылка на оплату конфигурируется, всё работает по 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;
            }
        }
    }
}
  • Вопрос задан
  • 79 просмотров
Решения вопроса 1
Mike_Ro
@Mike_Ro
Python, JS, WordPress, SEO, Bots, Adversting
Здесь что лежит?
$response_body['data']['attributes']['redirect_url'];

А здесь?
$response_body['data']['attributes'];
Подозреваю, что нужно так:
$response_body['data']['attributes']['hpp_url'];
Еще интересный момент со статусом оплаты [status] => process_pending, возможно, платеж еще не обработан и нужно время.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы