Files
crm.clientright.ru/include/utils/Debexpert-curl.php

554 lines
26 KiB
PHP
Raw Normal View History

<?php
/*********************************************************************************
* Набор методов для работы с ej.sudrf.ru через сервис debex.ru
* All Rights Reserved.
* Contributor(s): Группа компаний АйТи Трейд.
********************************************************************************/
require_once 'include/utils/utils.php';
require_once 'include/Webservices/Revise.php';
require_once 'modules/Users/Users.php';
require_once 'includes/Loader.php';
vimport ('includes.runtime.Globals');
vimport ('includes.runtime.BaseModel');
vimport ('includes.runtime.LanguageHandler');
function Send2Court($projectid, $version) {
file_put_contents('send2court.log', PHP_EOL.date('Y-m-d H:i:s').' - Запущена процедура отправки искового по Проекту '.$projectid.' в режиме '.$version.PHP_EOL, FILE_APPEND);
global $adb;
$query = 'select u.index_notice, u.addr_notice, u.id as userid, a.accountid, a.accountname, a.inn, a.kpp, la.bill_code, la.bill_city, la.bill_street, ra.ship_code, ra.ship_city, ra.ship_street, a.phone, a.email1, pcf.cf_1511 as price, ca.mailingstreet, acf.cf_1951 as ogrn
from vtiger_project p
left join vtiger_projectcf pcf on pcf.projectid = p.projectid
left join vtiger_contactdetails cd on cd.contactid = p.linktoaccountscontacts
left join vtiger_contactaddress ca on ca.contactaddressid = p.linktoaccountscontacts
left join vtiger_account a on a.accountid = pcf.cf_1994
left join vtiger_accountscf acf on acf.accountid = pcf.cf_1994
left join vtiger_accountbillads la on la.accountaddressid = pcf.cf_1994
left join vtiger_accountshipads ra on ra.accountaddressid = pcf.cf_1994
left join vtiger_crmentity e on e.crmid = p.projectid
left join vtiger_users u on u.id = e.smownerid
where e.deleted = 0 and p.projectid = '.$projectid;
$result = $adb->pquery($query);
if ($adb->num_rows($result) == 0) {
$output = 'Проект не найден';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - Проект с id '.$projectid.' не найден'.PHP_EOL, FILE_APPEND);
} else {
$accountid = $adb->query_result($result, 0, 'accountid');
$userid = $adb->query_result($result, 0, 'userid');
$authdoc = getAuthDoc($accountid, $userid); // Поднимаем доверку на представителя Заявителя (он же ответственный по Проекту)
if ($authdoc['result'] == 'NO') {
$output = 'У Ответственного по Проекту '.$projectid. ' в Контрагенте '.$accountid.' нет доверенности от Заявителя';
} else {
$price = $adb->query_result($result, 0, 'price');
$address = $adb->query_result($result, 0, 'mailingstreet');
$court = getCourt(0, $address, $price); // Ищем суд по адресу и сумме цены иска
if ($court['result'] <> 'YES') {
$output = $court['result'];
} else {
$claim = getClaim($projectid);
if ($claim['result'] == 'NO') {
$output = 'В Проекте '.$projectid. 'отсутствует Исковое заявление';
} else {
$multipart = []; // Этот массив будем отдавать в вызове
// Доверенность
$multipart[] = [
'name' => 'files',
'contents' => fopen($authdoc['filepath'], 'r'),
'path' => $authdoc['filepath'],
'filename' => $authdoc['filename']
];
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$authdoc['filename'].'"'.PHP_EOL, FILE_APPEND);
// Исковое
$multipart[] = [
'name' => 'files',
'contents' => fopen($claim['filepath'], 'r'),
'path' => $claim['filepath'],
'filename' => $claim['filename']
];
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$claim['filename'].'"'.PHP_EOL, FILE_APPEND);
$data = []; // А тут мы соберем огромный массив, который потом превратится в json для fillData
$data['appealType'] = 2; // Подает Представитель
$data['mySelfAdditionalData']['courtNoticesAddressIndex'] = $adb->query_result($result, 0, 'index_notice');
$data['mySelfAdditionalData']['courtNoticesAddress'] = $adb->query_result($result, 0, 'addr_notice');
$data['mySelfAdditionalData']['authorizationDocument']['fileIndex'] = 0;
$data['mySelfAdditionalData']['authorizationDocument']['description'] = $authdoc['description'];
$data['mySelfAdditionalData']['authorizationDocument']['pagesCount'] = $authdoc['pages'];
$data['additionalForRepresentativeApplicants'][0]['dataType'] = 'entity';
$data['additionalForRepresentativeApplicants'][0]['entity']['name'] = htmlspecialchars_decode($adb->query_result($result, 0, 'accountname'));
$data['additionalForRepresentativeApplicants'][0]['entity']['international'] = false;
$data['additionalForRepresentativeApplicants'][0]['entity']['inn'] = $adb->query_result($result, 0, 'inn');
$data['additionalForRepresentativeApplicants'][0]['entity']['kpp'] = $adb->query_result($result, 0, 'kpp');
$data['additionalForRepresentativeApplicants'][0]['entity']['ogrnip'] = $adb->query_result($result, 0, 'ogrn');
$data['additionalForRepresentativeApplicants'][0]['entity']['proceduralStatus'] = '50710010';
$data['additionalForRepresentativeApplicants'][0]['entity']['legalIndex'] = $adb->query_result($result, 0, 'bill_code');
$data['additionalForRepresentativeApplicants'][0]['entity']['legalAddress'] = $adb->query_result($result, 0, 'bill_city').', '.$adb->query_result($result, 0, 'bill_street');
$data['additionalForRepresentativeApplicants'][0]['entity']['isLegalAdressEqualToActualResidenceAddress'] = false;
$data['additionalForRepresentativeApplicants'][0]['entity']['actualResidenceIndex'] = $adb->query_result($result, 0, 'ship_code');
$data['additionalForRepresentativeApplicants'][0]['entity']['actualResidenceAddress'] = $adb->query_result($result, 0, 'ship_city').', '.$adb->query_result($result, 0, 'ship_street');
$data['additionalForRepresentativeApplicants'][0]['entity']['email'] = $adb->query_result($result, 0, 'email1');
$data['additionalForRepresentativeApplicants'][0]['entity']['phoneNumber'] = $adb->query_result($result, 0, 'phone');
$data['court']['region'] = $court['region'];
$data['court']['judicialAuthority'] = $court['code'];
$data['appealDocument']['fileIndex'] = 1;
$data['appealDocument']['description'] = $claim['description'];
$data['appealDocument']['pagesCount'] = $claim['pages'];
$otherDocs = getOtherDocs($projectid, $accountid);
if (count($otherDocs) > 0) {
for ($i=0; $i<count($otherDocs); $i++) {
$newdoc = array();
$newdoc['fileIndex'] = $i + 2;
$newdoc['description'] = $otherDocs[$i]['description'];
$newdoc['pagesCount'] = $otherDocs[$i]['pages'];
$data['additionalAppealDocuments'][] = $newdoc;
$multipart[] = [
'name' => 'files',
'contents' => fopen($otherDocs[$i]['filepath'], 'r'),
'filename' => $otherDocs[$i]['filename']
];
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - добавили в массив файл "'.$otherDocs[$i]['filename'].'"'.PHP_EOL, FILE_APPEND);
}
}
$data['tax']['type'] = '1';
$data['processType'] = '201.01';
$multipart[] = [
'name' => 'certificate',
'contents' => fopen('storage/cert.pfx', 'r'),
'filename' => 'cert.pfx'
];
$multipart[] = [
'name' => 'fillData',
'contents' => json_encode($data)
];
$cookies = GetCookies($version);
if ($cookies != 'Не удалось получить куки') {
// Формируем заголовок запроса
$key = GetKey($version);
$headers = array(
// Content-Type: multipart/form-data автоматически добавляется cURL с правильным boundary
'x-api-key: '.$key,
'hidden-authorization-cookies:' .htmlspecialchars_decode($cookies),
'hidden-certificate-pin: yft,fkjdj1',
'custom: Zx123456'
);
//$url = GetUrl($version);
$url = 'https://webhook.nodul.ru/765/dev/eea1b30c-14db-4499-9fc2-4d13e394bae6';
//$url = 'https://eoj0ndhyykckfh.m.pipedream.net';
//$url = 'https://webhook.nodul.ru/13/dev/test-some-error';
// Отправляем запрос
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - непосредственно отправляем запрос на '.$url.PHP_EOL, FILE_APPEND);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $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_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => json_encode($multipart)
));
//
$output = curl_exec($curl);
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - получили ответ при выполнении запроса: '.$output.PHP_EOL, FILE_APPEND);
curl_close($curl);
/*
if ($version == 'Prod') {
// Сохраним в Проекте входящий номер, если он есть
$arrResponse = json_decode($output, true);
$number = $arrResponse['data']['appealNumber'];
if (!empty($number) and !is_null($number)) {
$user = Users::getActiveAdminUser(); // Получаем пользователя, под которым будем создавать записи
try {
$params = array (
'id' => '33x'.$projectid,
'cf_2204' => $number
);
//file_put_contents('send2court.log', date('Y-m-d H:i:s').' - подготовлен массив для изменения Проекта: '.print_r($params, true).PHP_EOL, FILE_APPEND);
//file_put_contents('send2court.log', date('Y-m-d H:i:s').' - от имени пользователя: '.print_r($user, true).PHP_EOL, FILE_APPEND);
$result = vtws_revise($params, $user);
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - сохранили в Проект рег.номер входящего: '.$number.PHP_EOL, FILE_APPEND);
} catch (WebServiceException $ex) {
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - не получилось сохранить в Проект рег.номер входящего: '.$ex->getMessage().PHP_EOL, FILE_APPEND);
}
//$query = 'update vtiger_projectcf set cf_2204 = "'.$number.'" where projectid = '.$projectid;
//$result = $adb->pquery($query);
//file_put_contents('send2court.log', date('Y-m-d H:i:s').' - сохранили в Проект рег.номер входящего: '.$number.PHP_EOL, FILE_APPEND);
}
}
*/
//$output = json_encode($multipart);
}
}
}
}
}
return $output;
}
function getAuthDoc($accountid, $userid) {
global $adb;
$output = [];
$query = 'select n.title, ncf.cf_1953 as pages, concat(a.`path`, a.attachmentsid, "_", a.storedname) as filepath, concat(a.attachmentsid, "_", a.storedname) as filename, a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where e.smownerid = ? and r.crmid = ? and e.deleted = 0 and n.filename like "%подтверждающий_полномочия%"';
$result = $adb->pquery($query, array($userid, $accountid));
if ($adb->num_rows($result) == 0) {
$output['result'] = 'NO';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - доверенность с подстрокой "подтверждающий_полномочия" в Контрагенте '.$accountid.' не найдена'.PHP_EOL, FILE_APPEND);
} else {
$output['result'] = 'YES';
$output['description'] = $adb->query_result($result, 0, 'title');
$output['filepath'] = $adb->query_result($result, 0, 'filepath');
//$output['filename'] = $adb->query_result($result, 0, 'filename');
$output['filename'] = $adb->query_result($result, 0, 'title').'.pdf';
$output['type'] = $adb->query_result($result, 0, 'type');
$output['pages'] = $adb->query_result($result, 0, 'pages');
if (empty($output['pages']) or $output['pages'] == 0) {
$output['pages'] = getPDFPageCount($output['filepath']);
}
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - Нашли доверенность в Контрагенте '.$accountid.PHP_EOL, FILE_APPEND);
}
return $output;
}
function getClaim($projectid) {
global $adb;
$output = [];
$query = 'select n.title, ncf.cf_1953 as pages, concat(a.`path`, a.attachmentsid, "_", a.storedname) as filepath, concat(a.attachmentsid, "_", a.storedname) as filename, a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid = ? and e.deleted = 0 and n.filename like "сковоеаявление%"';
$result = $adb->pquery($query, array($projectid));
if ($adb->num_rows($result) == 0) {
$output['result'] = 'NO';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - Исковое заявление с подстрокое "Исковоеаявление" в Проекте '.$projectid.' не найдено'.PHP_EOL, FILE_APPEND);
} else {
$output['result'] = 'YES';
$output['description'] = $adb->query_result($result, 0, 'title');
$output['filepath'] = $adb->query_result($result, 0, 'filepath');
//$output['filename'] = $adb->query_result($result, 0, 'filename');
$output['filename'] = $adb->query_result($result, 0, 'title').'.pdf';
$output['type'] = $adb->query_result($result, 0, 'type');
$output['pages'] = $adb->query_result($result, 0, 'pages');
if (empty($output['pages']) or $output['pages'] == 0) {
$output['pages'] = getPDFPageCount($output['filepath']);
}
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - Нашли исковое заявление в Проекте '.$projectid.PHP_EOL, FILE_APPEND);
}
return $output;
}
function getOtherDocs($projectid, $accountid) {
global $adb;
$output = [];
//$i = 0;
// Сначала вытащим доки из Проекта
$query = 'select n.title, ncf.cf_1953 as pages, concat(a.`path`, a.attachmentsid, "_", a.storedname) as filepath, concat(a.attachmentsid, "_", a.storedname) as filename, a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid = ? and e.deleted = 0 and n.filename not like "сковоеаявление%" and a.`type` = "application/pdf"';
$result = $adb->pquery($query, array($projectid));
if ($adb->num_rows($result) > 0) {
for ($i=0; $i<$adb->num_rows($result); $i++) {
$output[$i]['description'] = $adb->query_result($result, $i, 'title');
$output[$i]['filepath'] = $adb->query_result($result, $i, 'filepath');
//$output[$i]['filename'] = $adb->query_result($result, $i, 'filename');
$output[$i]['filename'] = $adb->query_result($result, $i, 'title').'.pdf';
$output[$i]['type'] = $adb->query_result($result, $i, 'type');
$output[$i]['pages'] = $adb->query_result($result, $i, 'pages');
if (empty($output[$i]['pages']) or $output[$i]['pages'] == 0) {
$output[$i]['pages'] = getPDFPageCount($output[$i]['filepath']);
}
//echo $i.' - '.$output[$i]['filename'].'<br>';
}
}
// А теперь из Контрагента, но только те, которые лежат в папке "Суд"
$query = 'select n.title, ncf.cf_1953 as pages, concat(a.`path`, a.attachmentsid, "_", a.storedname) as filepath, concat(a.attachmentsid, "_", a.storedname) as filename, a.`type`
from vtiger_senotesrel r
left join vtiger_notes n on n.notesid = r.notesid
left join vtiger_crmentity e on e.crmid = r.notesid
left join vtiger_notescf ncf on ncf.notesid = r.notesid
left join vtiger_seattachmentsrel r2 on r2.crmid = r.notesid
left join vtiger_attachments a on a.attachmentsid = r2.attachmentsid
where r.crmid = ? and e.deleted = 0 and a.`type` = "application/pdf" and n.folderid = 3';
$result = $adb->pquery($query, array($accountid));
if ($adb->num_rows($result) > 0) {
for ($j=0; $j<$adb->num_rows($result); $j++) {
$output[$i]['description'] = $adb->query_result($result, $j, 'title');
$output[$i]['filepath'] = $adb->query_result($result, $j, 'filepath');
//$output[$i]['filename'] = $adb->query_result($result, $j, 'filename');
$output[$i]['filename'] = $adb->query_result($result, $j, 'title').'.pdf';
$output[$i]['type'] = $adb->query_result($result, $j, 'type');
$output[$i]['pages'] = $adb->query_result($result, $j, 'pages');
if (empty($output[$i]['pages']) or $output[$i]['pages'] == 0) {
$output[$i]['pages'] = getPDFPageCount($output[$i]['filepath']);
}
//echo $i.' - '.$output[$i]['filename'].'<br>';
$i++;
}
}
return $output;
}
function getCourt($contactid, $address, $price) {
$output = [];
$output['result'] = 'YES';
if (empty($address) and empty($contactid)) {
$output['result'] = 'Не указаны исходные данные';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - не указан адрес для поиска суда'.PHP_EOL, FILE_APPEND);
} elseif (empty($address) and !empty($contactid)) {
$query = 'select a.mailingstreet
from vtiger_contactaddress a
left join vtiger_crmentity e on e.crmid = a.contactaddressid
where e.deleted = 0 and a.contactaddressid = '.$contactid;
$result = $adb->pquery($query);
if ($adb->num_rows($result) == 0) {
$output['result'] = 'Контакт не найден';
} else {
$address = $adb->query_result($result, 0, 'mailingstreet');
}
}
if ($output['result'] == 'YES') {
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - начинаем поиск суда для адреса '.$address.PHP_EOL, FILE_APPEND);
$host = "https://api.xn----7sbarabva2auedgdkhac2adbeqt1tna3e.xn--p1ai/api"; // адрес сервера api
$token = "y4kNd3Li2NDxyOgaG37ZDuGTWg5CfF2A2dERwbFUjas"; // указать полученный токен
// запрос по адресу
$url = $host."?token=".$token."&address=".urlencode($address);
// запрос по координатам
//$coords = "49.099524 55.794340"; // координаты точки, разделитель - пробел
//$url = $host . "?token=" . $token . "&coords=" . urlencode($coords);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$court = json_decode($response, true);
if ($price > 100000) {
// Если цена иска - от 100 тысяч, то нам будем нужен федеральный суд
$need = 'court_fs';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - сумма иска более 100к - нужен федеральный суд'.PHP_EOL, FILE_APPEND);
} else {
// А если меньше, то мировой
$need = 'court_ms';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - сумма иска менее 100к - нужен мировой суд'.PHP_EOL, FILE_APPEND);
}
if (isset($court['request'][$need])) {
$output['code'] = $court['request'][$need]['code'];
$output['region'] = substr($output['code'], 0, 2); // Первые две цифры кода суда - это регион
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - и он найден в бесплатной версии API. Код суда: '.$output['code'].PHP_EOL, FILE_APPEND);
} else {
// В бесплатной версии поиска подсудности нужного суда не нашлось - придется лезть в платный сервис
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - но в бесплатной версии API его нет - полезем в платную'.PHP_EOL, FILE_APPEND);
$apikey = GetKey('Prod');
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-yc.explorer.debex.ru/production/jurisdiction',
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 =>'{
"address": "'.addslashes($address).'",
"get_fssp_geo": 1
}',
CURLOPT_HTTPHEADER => array(
'x-api-key: '.$apikey,
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$court = json_decode($response, true);
if ($price > 100000) {
// Если цена иска - от 100 тысяч, то нам будем нужен федеральный суд
$need = 'court';
} else {
// А если меньше, то мировой
$need = 'higher_court';
}
if (isset($court['result'][$need])) {
$output['code'] = $court['result'][$need]['code'];
$output['region'] = substr($output['code'], 0, 2); // Первые две цифры кода суда - это регион
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - а тут мы его и нашли: '.$output['code'].PHP_EOL, FILE_APPEND);
} else {
// Нужный суд не нашелся ни в платном, ни в бесплатном сервисе - не можем продолжать
$output['result'] = 'Суд не найден';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - но его и в платном API тоже нет'.PHP_EOL, FILE_APPEND);
}
}
}
return $output;
}
function GetCookies($version) {
//$version = 'Dev';
if ($version == 'Dev') {
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - поднимаем бесплатные куки для версии Dev'.PHP_EOL, FILE_APPEND);
$curl = curl_init();
$apiKey = GetKey('Dev');
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-yc.explorer.debex.ru/dev/sudrf-auth',
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_HTTPHEADER => array(
'x-api-key: '.$apiKey
),
));
$response = curl_exec($curl);
curl_close($curl);
} else {
$response = 'No';
if (file_exists('cookies.txt')) {
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - Найден файл со старыми куками'.PHP_EOL, FILE_APPEND);
$created = filemtime('cookies.txt'); // Дата создания файла (получения и сохранения cookies)
$now = time();
$diff = $now - $created;
if ($diff < 10800) {
// Если старый файл создан более 3 часов назад
$response = file_get_contents('cookies.txt');
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - создан менее 3 часов назад - берем куки из него'.PHP_EOL, FILE_APPEND);
} else {
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - создан более 3 часов назад - будем получать новые'.PHP_EOL, FILE_APPEND);
}
}
if ($response == 'No') {
// Будем получать новые
$url = "https://api-yc.explorer.debex.ru/production/sudrf-auth-chatbot";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'x-api-key: ' . GetKey('Prod'),
'hidden-bot-phone-number: +79262306381'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, []);
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - отправляем запрос с СМС-подтверждением'.PHP_EOL, FILE_APPEND);
$response = curl_exec($ch);
curl_close($ch);
// И сохраним их на будущее
if (strpos($response, "error") !== false) {
$response = 'Не удалось получить куки';
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - в ответ получили ошибку. Куков нет.'.PHP_EOL, FILE_APPEND);
} else {
file_put_contents('cookies.txt', $response);
file_put_contents('send2court.log', date('Y-m-d H:i:s').' - ответ получен, новые куки сохранены в файле cookies.txt'.PHP_EOL, FILE_APPEND);
}
}
}
return $response;
}
function GetUrl($version) {
if ($version == 'Dev') {
$url = 'https://explorer-proxy.debex.ru/api/dev/sudrf';
} elseif ($version == 'Stage') {
$url = 'https://explorer-proxy.debex.ru/api/stage/sudrf';
} elseif ($version == 'Prod') {
$url = 'https://explorer-proxy.debex.ru/api/production/sudrf';
}
return $url;
}
function GetKey($version) {
if ($version == 'Dev') {
$key = 'sandboxklientpravdjknkjsdndsd8y789!';
} else {
$key = 'productionklientpravkjnkjnhkhj87y!';
}
return $key;
}
?>