A
A
Andrey Sverlin2021-11-11 18:07:23
MODX
Andrey Sverlin, 2021-11-11 18:07:23

How to tie acquiring from Sber to the site?

There is a site on MODX. Not a shop. Those. no extensions for the store are installed there (and are not planned). The site presents products (confectionery courses) for which the user is invited to enroll. Now the visitor fills out the form, the form handler sends the request to the mail. You need to make sure that after filling out the form, the visitor is redirected to the payment page. And after a successful payment, they returned it back to send a request to the mail.

I have no experience with connecting online payment at all. So what follows is just my speculation. As I see it.
In the form handler, instead of the mail() function, I need to place a query string to the bank's payment page. In this line, I need to transfer my login data, as well as order data (name of the course, buyer's data: full name, phone, email, city; amount). I need to transfer the order data so that after a successful payment they come back, and I can (somehow) send an email with an application based on them.

The question is in this line. How should she look? I could not find examples of what I need on the site with a certificate from Sberbank. And in general, is my train of thought correct, about the fact that the query string should be sent by the form handler? I just really have no idea how it should look like.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Sverlin, 2021-11-12
@imhateb

In general, I succeeded. Thanks to everyone who tried to help.
In case someone suddenly has a similar problem, I will write how I solved it. Because the support of Sberbank is useless as a goat's milk. Those are freaks. They constantly refer to the API help, where my question is stupidly not answered.
I’ll make a reservation right away, my method may seem wildly crutch, but it works. For the first time I attached this payment to a finished project. I do not pretend to the correctness and ideality of the solution. I just want to help people like me.
Actually the subject is described above in a question. And my assumptions were only partially correct. Namely, I cannot send information about the order in the request to the bank (course name, buyer's data: full name, phone number, email, city), and then get them back to send the application. It is possible to pass this information via &jsonParams= {"Name":"Parameter"}, but it will not be returned later. These parameters can only be used in the personal account as an add. transaction information.
So.
Information about the order must be saved somewhere before sending a request to the bank, and then, after the response, it must be found and used to send a message. I decided to use a text file for this, which is created during the formation of the request and has the name = order ID. We put all the necessary information in the file, and then, upon returning after payment, we take it out and send a letter.
The actual form handler code. More precisely, only the part that sends a request to the bank.

$timestamp = date('dmYHis');  // это у нас будет номер заказа 
// $pre_order - это сумма, которую надо заплатить. Берётся из формы. 
$pre_order = str_replace(' ', '', $pre_order); // Надо убрать пробел разделяющий разряды (ну типа 1 000 -> 1000)
$pre_order = $pre_order*100; // и умножить на сто, т.к. в запросе в банк надо указывать сумму в копейках.
        
// Отправляем запрос в банк
$myCurl = curl_init();
curl_setopt_array($myCurl, array(
    CURLOPT_URL => 'https://securepayments.sberbank.ru/payment/rest/register.do?userName=XXXXXXXXXXXXX-api&password=XXXXXXXXXXXXX&amount='.$pre_order.'&language=ru&orderNumber='.$timestamp.'&returnUrl=https://yoursite.com/send',   
// Вот эта строка и есть запрос в банк. Тут нужно указать только свой userName, password, сумму и номер заказа, а так же returnUrl= адрес страницы куда мы вернёмся после оплаты. 
// Сюда же можно добавить &jsonParams= {"Имя":"Параметр"}, о котором я писал выше. Но это такое...
// Вообще в справке там много всяких доп. параметров описано, но я там ничего особо полезного не нашёл.  
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query(array(''))
));
$response = curl_exec($myCurl);
curl_close($myCurl);
// Всё. Запрос отправлен. В ответ мы получаем строку с ID заказа и ссылкой на оплату.
// Если выполнить echo $response, то можно эту строку увидеть.
// Теперь нам надо из этой строки, полученной в ответ от банка, получить отдельно ID заказа, отдельно ссылку на оплату
// Обрезаем ответ, чтобы получить url
$url = strstr($response, 'https:');
$url = strstr($url, '"', true);
// Обрезаем ответ, чтобы получить id заказа
$orderid = strstr($response, '","formUrl"', true);
$orderid = mb_substr($orderid, 12); 

// Создаём файл с именем = id заказа. Именно так, потому что потом мы по этому id этот файл и будем находить.
$myfile='../orders/'.$orderid.'.txt';   
 
// Заполняем его данными из формы
$text .= $familiya.";";
$text .= $imya.";";
$text .= $otchestvo.";";
$text .= $tel.";";
$text .= $email.";";
$text .= $city.";";
$text .= $course_info.";";
$text .= $price.";";
$text .= $pre_order."";
    
$file=fopen($myfile,'x+');
fputs($file,$text);
fclose($file);
    
// Переходим на страницу оплаты. $url мы получили из ответа от банка
header('Location: '.$url);

This is all I placed in the form handler in the place where the mail () function used to be, sending the letter. What happened as a result? Now after filling out the form and pressing the "Submit" button, the person gets to the payment page. And after a successful payment, it is returned back to the address specified in the returnUrl. Only the same order ID will be added to the address, which will help us find the desired text file.
On the return page (in the example, this is https://yoursite.com/send ), we need to prepare another form that will already send the application to the mail.
<form action="forms/send_mail.php" method="post" id="send_page">
        <input type="text" name="familiya" value="" >
        <input type="text" name="imya" value="" >
        <input type="text" name="otchestvo" value="" >
        <input type="tel" name="tel" value="" >
        <input type="email" name="email" value="" >
        <input type="text" name="city" value="" >
        <input type="text" name="course_info" value="" >
        <input type="text" name="pre_order" value="" >
        <input type="text" name="price" value="" >
</form>

Here we don’t need a send button, we will send it with a script, after we fill in all the fields with the script. We make this form invisible so that it does not flicker when the page loads.
Script that finds the desired text file and fills in the form fields:
var url = document.location.href; // Палим урл страницы
url = url.slice(url.indexOf('=')+1, url.lastIndexOf('&')); // режем его и получаем orderID, который отдал нам банк. Он нам нужен, чтобы найти соответствующий текстовый документ

// Обращаемся к конкретному текстовому документу
fetch('/orders/'+url+'.txt').then(response => response.text()).then((data) => {  
    var vars = ['familiya', 'imya', 'otchestvo', 'tel', 'email', 'city', 'course_info', 'price', 'pre_order'], // создаём массив с именами импутов
    info, i=0;            
    info = data.split(';'); // создаём массив со значениями, которые берём из текстового документа
            
    for (i; i<vars.length; i++) {  // перебираем массив и заполняем инпуты
        if (vars[i] == 'pre_order') {info[i] = info[i]/100;} // сумма оплаты у нас записана в копейках, поэтому надо привести к рублям
            $('.send_page').find('input[name='+vars[i]+']').attr('value', info[i]); // заполняем инпуты
        }
    });

// отправляем форму спустя 300мс, чтобы инпуты успели заполниться
setTimeout(function(){$("#send_page").submit()},300);

Everything. The inputs are filled, the form was sent with a simple send_mail.php handler.
I will be glad if my hard experience will be useful to someone. I feel that the method is very crutch, but, I repeat, I am not strong in PHP at all and I connected acquiring for the first time. I closed my task described in the question.

J
Julia Lis, 2021-11-11
@julia1990

Good afternoon) if there is no experience in connecting, then it will be directly difficult for you.
Sberbank has a good api, I figured it out myself when it was necessary to transfer an installment plan from Sberbank acquiring to Sberbank.
Here is the documentation
link to the docks
For comparison, open any module that is already created, but if you have no experience, it will be difficult.
Here are test cards
Below is an example of a POST request and what the Sber should answer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question