Files
crm.clientright.ru/server22.php

287 lines
9.3 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
header('Access-Control-Allow-Origin: *'); // Разрешаем доступ с любого источника
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: origin, Content-Type, X-Requested-With, XMLHttpRequest');
// Настройка логирования
$log_dir = 'logs';
if (!is_dir($log_dir)) {
mkdir($log_dir);
}
function log_message($message) {
global $log_dir;
$date = date('Y-m-d H:i:s');
file_put_contents("$log_dir/form_log.log", "[$date] $message" . PHP_EOL, FILE_APPEND);
}
// Получаем данные из POST
$upload_urls_real = $_POST['upload_urls_real'] ?? [];
$appends = $_POST['appends'] ?? [];
$docs_names = $_POST['docs_names'] ?? [];
$docs_ticket_files_ids = $_POST['docs_ticket_files_ids'] ?? [];
$sub_dir = $_POST['sub_dir'] ?? '';
$lastname = str_replace(' ', '', $_POST['lastname'] ?? '');
// Логируем полученные данные
log_message("Полученные данные: " . json_encode($_POST));
// Подготовка тела письма
$mail_body = 'Пользователь заполнил форму! <br><br>';
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
$mail_body .= $key . ' : ' . $item->field_val . '<br>';
}
// Логируем тело письма
log_message("Тело письма: $mail_body");
// Отправка почты
require 'send_mail.php';
$mail_data = ['body' => $mail_body];
$mail_sent = send_mail($mail_data);
if ($mail_sent) {
log_message("Письмо успешно отправлено.");
} else {
log_message("Ошибка при отправке письма.");
}
// Логирование отправленных данных
log_message("Отправленные данные на CRM: " . json_encode($upload_urls_real));
// Прочая логика (например, работа с API и т.д.)
$endpointUrl = "https://crm.clientright.ru/webservice.php";
// 1) Вынимаем временный токен из ответа
$ch = curl_init();
$url = $endpointUrl . "?operation=getchallenge&username=api";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$response = curl_exec($ch);
$jsonResponse = json_decode($response, true);
$challengeToken = $jsonResponse['result']['token'];
$result['challengeToken'] = $challengeToken;
$userAccessKey = '4r9ANex8PT2IuRV';
$generatedKey = md5($challengeToken.$userAccessKey);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'operation' => 'login',
'username' => 'api',
'accessKey' => $generatedKey
)
));
$response = curl_exec($ch);
$jsonResponse = json_decode($response, true);
$sessionId = $jsonResponse['result']['sessionName'];
log_message("Получен sessionId: " . $sessionId);
// 2) Создание клиента-физлица
$client_array = array(
'operation' => 'CreateContact',
'sessionName' => $sessionId,
);
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "client") {
$client_array[$item->ws_name] = $item->field_val;
if ($item->ws_name == "code") $sms = $item->field_val;
}
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $client_array
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
$client_id = $output['result'];
log_message("Создан клиент с ID: " . $client_id);
// 3) Создание/обновление Контрагента-исполнитель
$contractor_array = array(
'operation'=>'CreateAccount',
'sessionName'=>$sessionId,
);
foreach($appends as $key => $itemjson){
$item=json_decode($itemjson);
if($item->ws_type=="contractor" && $item->field_val != "") {
$contractor_array[$item->ws_name] = $item->field_val;
}
}
print_r($contractor_array);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $contractor_array
));
$response = curl_exec($ch);
$output = json_decode($response,TRUE);
$contractor_id=$output['result'];
echo 'Контрагент исполнитель id= '.$contractor_id;
log_message("Создан контрагент с ID: " . $contractor_id);
// 3.1) Агент
if($_POST['getservice']=="agent") {
$agent_array = array(
'operation'=>'CreateAccount',
'sessionName'=>$sessionId,
);
foreach($appends as $key => $itemjson){
$item=json_decode($itemjson);
if($item->ws_type=="agent" && $item->field_val != "") {
$agent_array[$item->ws_name] = $item->field_val;
}
}
print_r($agent_array);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $agent_array
));
$response = curl_exec($ch);
$output = json_decode($response,TRUE);
$agent_id=$output['result'];
log_message("Создан клиент с ID: " . $agent_id);
}
// 4) Проект
$project_array = array(
'operation' => 'CreateProject',
'sessionName' => $sessionId,
'contactid' => $client_id,
'offenderid' => $contractor_id,
'agentid' => $agent_id,
'sms' => $sms
);
// Пушим в массив остальные поля
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type != "contractor" && $item->ws_type != "client" && $item->ws_type != "agent" && $item->ws_type != "other") {
$project_array[$item->ws_name] = $item->field_val;
}
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $project_array
));
$response = curl_exec($ch);
$project_id = preg_replace('/[^0-9]/', '', $response);
log_message("Создан проект с ID: " . $project_id);
// 5) Прикрепление файлов к проекту
if ($upload_urls_real) {
foreach ($upload_urls_real as $index => $upload_url) {
if ($docs_ticket_files_ids && $docs_ticket_files_ids[$index] != "simple") continue;
if ($upload_url) {
$params = array(
'operation' => 'AddPDF',
'sessionName' => $sessionId,
'crmid' => $project_id,
'file' => $upload_url,
'description' => $docs_names[$index]
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
log_message("Прикреплен файл к проекту: " . $response);
}
}
}
// 6) Остальные поля
$other_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "other") {
$other_array[$item->ws_name] = $item->field_val;
}
}
$params = array(
'operation' => 'UpdateEntity',
'sessionName' => $sessionId,
'crmid' => $project_id,
'element' => json_encode($other_array)
);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
log_message("Обновлены остальные поля: " . json_encode($other_array));
// 7 Создание заявок
$ticket_id_array = array();
foreach ($appends as $key => $itemjson) {
$item = json_decode($itemjson);
if ($item->ws_type == "ticket") {
$params = array(
'operation' => 'CreateERVTicket',
'sessionName' => $sessionId,
'title' => $item->field_val,
'contactid' => $client_id,
'projectid' => $project_id
);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_URL => $endpointUrl,
CURLOPT_POSTFIELDS => $params
));
$response = curl_exec($ch);
$output = json_decode($response, TRUE);
log_message("Создана заявка: " . json_encode($output));
$ticket_id_array[$item->ws_name] = preg_replace("/[^0-9]/", '', $response);
}
}
log_message("Массив ID заявок: " . json_encode($ticket_id_array));
// Логируем ответ клиенту
$response = ['status' => 'success', 'message' => 'Данные успешно обработаны.'];
log_message("Ответ клиенту: " . json_encode($response));
echo json_encode($response);
?>