1198 lines
44 KiB
PHP
1198 lines
44 KiB
PHP
<?php
|
||
|
||
class WebAppRaiserAPI {
|
||
private $war_id;
|
||
private $war_owner_uid;
|
||
private $war_user_id;
|
||
private $war_username;
|
||
private $war_client_id;
|
||
private $war_client_secret;
|
||
private $war_access_token;
|
||
private $war_refresh_token;
|
||
private $war_expires_in;
|
||
public $war_expired;
|
||
private $is_owner;
|
||
|
||
private $operation = 'prod'; // [dev||prod]
|
||
private $uri = 'webappraiser.ru/api/v1/';
|
||
private $auth_uri;
|
||
private $api_uri;
|
||
private $appraisalCompanyId; // [2 | 1] // Идентификатор оценочной компании
|
||
|
||
private static $dict_list = array(
|
||
'MESSAGE_TYPE'=> 'Словарь №1,Тип сообщения',
|
||
'OBJECT_TYPE'=> 'Словарь №2, Тип объекта оценки',
|
||
'BUILDING_STAGE'=> 'Словарь №3, Стадия строительства',
|
||
'DECORATION_TYPE'=> 'Словарь №4, Состояние отделки помещения',
|
||
'WALL_MATERIAL'=> 'Словарь №5, Материал стен дома',
|
||
'VERIFICATION_STATUS'=> 'Словарь №6, Статус проверки',
|
||
'EGRN_EXTRACT_REQUEST_STATUS'=> 'Словарь №7, Статус заказа справки об объекте неждвижимости',
|
||
'APPRAISAL_SERVICE_TYPE'=> 'Словарь №8, Тип услуги при заказеоценки',
|
||
'REPORT_USAGE_TYPE' => 'Словарь №9, Цель оценки',
|
||
'ORDER_STATE'=> 'Словарь №10, Статус заказа',
|
||
'ORDER_STATE_COLOR'=> 'Цвета статусов заказа',
|
||
'VERIFICATION_RESULT'=> 'Словарь №11, Результат проверки',
|
||
'ACCOUNT_TYPE' => 'Типы учетных записей в системе',
|
||
);
|
||
|
||
// Словарь №1,Тип сообщения
|
||
private static $MESSAGE_TYPE = array(
|
||
'ORDER_ACCEPTED' => 'Заказ принят',
|
||
'ORDER_DECLINED'=> 'Заказ отклонен',
|
||
'CALCULATION_READY'=> 'Выполнен расчет',
|
||
'REQUEST_STATE_UPDATED'=> 'Заказ обновлен',
|
||
'REPORT_READY'=> 'Отчет готов',
|
||
'CHAT_MESSAGE_RECEIVED' => 'Получено текстовое сообщение',
|
||
'CHAT_MESSAGE' => 'Сообщение',
|
||
);
|
||
|
||
// Словарь №2, Тип объекта оценки
|
||
private static $OBJECT_TYPE = array(
|
||
'ROOM' => 'Комната',
|
||
'FLAT'=> 'Квартира',
|
||
'HOUSE'=> 'Дом',
|
||
//'LAST_ROOM'=> 'Последняя комната',
|
||
'TOWNHOUSE' => 'Таунхаус',
|
||
'APARTMENTS'=> 'Апартаменты',
|
||
'FLAT_PART'=> 'Доля в квартире',
|
||
//'AUTO'=> 'Автомобиль',
|
||
'PARKING_PLACE'=> 'Парковочное место',
|
||
//'BUSINESS'=> 'Бизнес',
|
||
'COMMERCIAL'=> 'Коммерческая недвижимость',
|
||
//'COURT'=> 'Для суда',
|
||
//'EQUIPMENT'=> 'Оборудование',
|
||
//'INVESTMENT'=> 'Инвестиции',
|
||
'LAND_PLOT'=> 'Земельный участок',
|
||
);
|
||
|
||
// Словарь №3, Стадия строительства
|
||
private static $BUILDING_STAGE = array(
|
||
'NEW'=> 'Новостройка',
|
||
'BUILT'=> 'Дом построен',
|
||
);
|
||
|
||
// Словарь №4, Состояние отделки помещения
|
||
private static $DECORATION_TYPE = array(
|
||
'NO_DECORATION'=> 'Без отделки',
|
||
'OVERHAUL_REQUIRED'=> 'Требуется капитальный ремонт',
|
||
'FOR_FINISHING'=> 'Предчистовая отделка',
|
||
'COSMETIC_REQUIRED'=> 'Требуется косметический ремонт',
|
||
'GOOD'=> 'Хорошее состояние',
|
||
'IMPROVED'=> 'Улучшенная отделка',
|
||
'EURO'=> 'Евроремонт',
|
||
'EXCLUSIVE'=> 'Эксклюзивный ремонт',
|
||
);
|
||
|
||
// Словарь №5, Материал стен дома
|
||
private static $WALL_MATERIAL = array(
|
||
'PANEL'=> 'Панельный',
|
||
'BLOCK'=> 'Блочный',
|
||
'MONOLITHIC_BRICK'=> 'Монолитно-кирпичный',
|
||
'BRICK'=> 'Кирпичный',
|
||
'MONOLITHIC'=> 'Монолитный',
|
||
'WOOD'=> 'Деревянный',
|
||
);
|
||
|
||
// Словарь №6, Статус проверки
|
||
private static $VERIFICATION_STATUS = array(
|
||
'NOT_VERIFIED'=> 'Проверка не производилась',
|
||
'IN_PROGRESS' => 'Идет проверка',
|
||
'COMPLETED'=> 'Проверка завершена успешно',
|
||
'ERROR'=> 'Проверка завершена с ошибками',
|
||
);
|
||
|
||
// Словарь №7, Статус заказа справки об объекте неждвижимости
|
||
private static $EGRN_EXTRACT_REQUEST_STATUS = array(
|
||
'NOT_REQUESTED'=> 'Справка не заказывалась',
|
||
'REQUESTED'=> 'Справка заказан и ожидает получения',
|
||
'READY' => 'Справка сформирована',
|
||
'ERROR' => 'При формировании справки произошла ошибка',
|
||
);
|
||
|
||
// Словарь №8, Тип услуги при заказеоценки
|
||
private static $APPRAISAL_SERVICE_TYPE = array(
|
||
'APPRAISAL'=> 'Оценка',
|
||
'CALCULATION'=> 'Расчет стоимости',
|
||
);
|
||
|
||
// Словарь №9, Цель оценки
|
||
private static $REPORT_USAGE_TYPE = array(
|
||
'COLLATERAL'=> 'Для целей залога',
|
||
'MORTGAGE'=> 'Для оформления закладной',
|
||
'PROCEEDING'=> 'Для судопроизводства',
|
||
'CHILD_SERVICES' => 'Для органов опеки',
|
||
'BUYING_SELLING' => 'Для купли-продажи',
|
||
'NOTARY' => 'Для нотариуса',
|
||
'CADASTRAL_VALUE_CONTEST'=> 'Оспаривание кадастровой стоимости',
|
||
'ANOTHER'=> 'Другое',
|
||
);
|
||
|
||
// Словарь №10, Статус заказа
|
||
private static $ORDER_STATE = array(
|
||
'CREATED'=> 'Создан',
|
||
'SENT'=> 'Отправлен',
|
||
'WORK'=> 'В работе',
|
||
'CLOSED'=> 'Закрыт (выполнен)',
|
||
'DECLINED'=> 'Отклонен',
|
||
'CANCELED'=> 'Отменен',
|
||
);
|
||
// color, border
|
||
private static $ORDER_STATE_COLOR = array(
|
||
'CREATED'=> ['#237ef7', '#3a8efa'], // обычный
|
||
'SENT'=> ['#237ef7', '#3a8efa'], //'Отправлен', // синий
|
||
'WORK'=> ['orange', 'orange'], //'В работе', // желтый
|
||
'CLOSED'=> ['#4CAF50', '#43a047'], // 'Закрыт (выполнен)', // зеленый
|
||
'DECLINED'=> ['#e2574cd9', '#9436295e'], // 'Отклонен', // красный
|
||
'CANCELED'=> ['#757575', '#d0d0d0'], // 'Отменен', // серый
|
||
);
|
||
|
||
// Словарь №11, Результат проверки
|
||
private static $VERIFICATION_RESULT = array(
|
||
'PROCESSING'=> 'Идет получение данных',
|
||
'GOOD'=> 'Проверка пройдена успешно',
|
||
'ATTENTION' => 'Результат проверки требует внимания',
|
||
'BAD'=> 'Результат проверки критический',
|
||
'ERROR'=> 'Отклонен',
|
||
);
|
||
|
||
// Словарь №12, Типы учетных записей в системе
|
||
private static $ACCOUNT_TYPE = array(
|
||
'APPRAISER'=> 'Оценочная компания',
|
||
'BANK'=> 'Банк',
|
||
'AGENCY' => 'Агентство',
|
||
);
|
||
|
||
public function __construct(User $user) {
|
||
if ($this->operation == 'dev') {
|
||
$this->auth_uri = 'https://beta.'.$this->uri;
|
||
$this->api_uri = 'https://r.beta.'.$this->uri;
|
||
$this->appraisalCompanyId = 2;
|
||
}
|
||
else {
|
||
$this->auth_uri = 'https://app.'.$this->uri;
|
||
$this->api_uri = 'https://r.'.$this->uri;
|
||
$this->appraisalCompanyId = 1;
|
||
}
|
||
if(empty($user->id))
|
||
$user->id = $_SESSION['id'];
|
||
|
||
$this->war_user_id = $user->id;
|
||
$this->war_expired = NULL;
|
||
// Это флаг, который позволяет нам отличить владельца ключа от пользователя.
|
||
$this->is_owner = true;
|
||
$user->api['is_owner'] = true;
|
||
|
||
$sql = "SELECT aw.*, wu.* FROM user_api_war aw
|
||
INNER JOIN war_users wu ON wu.api_id = aw.id
|
||
WHERE wu.uid = {$this->war_user_id}";
|
||
|
||
$q = mysql_query($sql);
|
||
$r = mysql_fetch_assoc($q);
|
||
|
||
if (!empty($r)) {
|
||
$this->war_id = $r['id'];
|
||
$this->war_owner_uid = $r['user_id'];
|
||
$this->war_username = $r['username'];
|
||
$this->war_client_id = $r['client_id'];
|
||
$this->war_client_secret = $r['client_secret'];
|
||
$this->war_access_token = $r['access_token'];
|
||
$this->war_refresh_token = $r['refresh_token'];
|
||
$this->war_expires_in = $r['expires_in'];
|
||
$user->api['war_id'] = $r['id'];
|
||
$user->api['war_owner_uid'] = $r['user_id'];
|
||
$user->api['war_username'] = $r['username'];
|
||
$user->api['war_pincode'] = $r['pincode'];
|
||
$user->api['war_client_id'] = $r['client_id'];
|
||
$user->api['war_client_secret'] = $r['client_secret'];
|
||
$user->api['war_access_token'] = $r['access_token'];
|
||
$user->api['war_refresh_token'] = $r['refresh_token'];
|
||
$user->api['war_expires_in'] = $r['expires_in'];
|
||
if(empty($r['expires_in'])) {
|
||
$this->war_expired = NULL;
|
||
}
|
||
elseif($r['expires_in'] < time()) {
|
||
$res = $this->auth_request('refresh_token');
|
||
if($res['status'] == 'success') {
|
||
$this->war_expired = false;
|
||
}
|
||
else {
|
||
$this->war_expired = true;
|
||
}
|
||
}
|
||
else {
|
||
$this->war_expired = false;
|
||
}
|
||
if(!empty($r['user_id']) && $r['user_id'] != $r['uid'] ) {
|
||
$this->is_owner = false;
|
||
$user->api['is_owner'] = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
public static function save($fields)
|
||
{
|
||
// valid_fields format: 'form data field' => 'DB data field'
|
||
$valid_fields = array(
|
||
'war_id'=> 'id',
|
||
'war_user_id'=> 'user_id',
|
||
'war_username'=> 'username',
|
||
'war_pincode' => 'pincode',
|
||
'war_client_id'=> 'client_id',
|
||
'war_client_secret'=> 'client_secret',
|
||
'war_access_token'=> 'access_token',
|
||
'war_refresh_token'=> 'refresh_token',
|
||
'war_expires_in'=> 'expires_in',
|
||
'war_token_type'=> 'token_type',
|
||
);
|
||
$id = WebAppRaiserDB::save('user_api_war', $fields, $valid_fields);
|
||
if($id){
|
||
$uid = $fields['war_user_id'];
|
||
$user_fields = array(
|
||
'uid' => $uid,
|
||
'api_id' => $id,
|
||
'updateDate' => time(),
|
||
);
|
||
$user_valid_fields = array(
|
||
'uid' => 'uid',
|
||
'api_id' => 'api_id',
|
||
'updateDate' => 'updateDate',
|
||
);
|
||
//print_r($user_fields);
|
||
$sql = "DELETE FROM `war_users` WHERE `uid`=$uid AND `api_id`=$id";
|
||
mysql_query($sql);
|
||
WebAppRaiserDB::save('war_users', $user_fields, $user_valid_fields);
|
||
}
|
||
return $id;
|
||
}
|
||
|
||
|
||
// 3.Polling (Опрос сервисом Внешней системой о получении новых сообщений)
|
||
public function apiMessages($id = false, $del = false)
|
||
{
|
||
$entry_point = 'messages';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
if($id === false){
|
||
// Получение списка новых сообщений
|
||
$res = $this->request($entry_point.'/new');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
// Ответ - массив: [id, date, type]
|
||
if ($return['info']['http_code'] == '200'){
|
||
// Запрос прошел без ошибок
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser при получении списка новых сообщений. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
else {
|
||
$id = (int)$id;
|
||
if ($del == false) {
|
||
// Получение полного содержимого сообщения
|
||
$res = $this->request($entry_point.'/'.$id);
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
// Ответ - элемент: [id, date, type, ... ]
|
||
if ($return['info']['http_code'] == '200'){
|
||
// Запрос прошел без ошибок сохраняем запись в базу данных
|
||
$valid_fields = array(
|
||
'id' => 'id',
|
||
'out_id' => 'out_id',
|
||
'api_id' => 'api_id',
|
||
'date' => 'date',
|
||
'type' => 'type',
|
||
'orderId' => 'orderId',
|
||
'fields' => 'fields',
|
||
);
|
||
$fields_fields = array();
|
||
foreach(['comment', 'value', 'text'] as $key){
|
||
if(isset($return['result'][$key]))
|
||
$fields_fields[$key] = $return['result'][$key];
|
||
}
|
||
$msg_id = 0;
|
||
$test_records = WebAppRaiserDB::select('war_msg', 'out_id', $return['result']['id']);
|
||
foreach($test_records as $test_record){
|
||
if($test_record['api_id'] == $this->war_id){
|
||
$msg_id = $test_record['id'];
|
||
}
|
||
}
|
||
$fields = array(
|
||
'id' => $msg_id,
|
||
'out_id' => $return['result']['id'],
|
||
'api_id' => $this->war_id,
|
||
'date' => strtotime($return['result']['date']),
|
||
'type' => $return['result']['type'],
|
||
'orderId' => $return['result']['orderId'],
|
||
'fields' => base64_encode(serialize($fields_fields)),
|
||
);
|
||
$inner_id = WebAppRaiserDB::save('war_msg', $fields, $valid_fields);
|
||
if($inner_id){
|
||
$return["msg"] = "Сообщение сохранено.";
|
||
//$return["status"] = 'success';
|
||
}
|
||
else{
|
||
$return["msg"] = "Возникла проблема при сохранении сообщения в базу данных.";
|
||
$return["status"] = 'error';
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser при чтении одного сообщения. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
else {
|
||
// Удаление сообщения из очереди
|
||
$res = $this->request($entry_point.'/'.$id, [], 'DELETE');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
// Ответ - нет
|
||
if ($return['info']['http_code'] == '200'){
|
||
// Запрос прошел без ошибок
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser при удалении сообщения. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
}
|
||
return $return;
|
||
}
|
||
// Получаем список сообщений
|
||
public function getMessages()
|
||
{
|
||
return $this->apiMessages();
|
||
}
|
||
// Получаем одно сообщение
|
||
public function getMessage($id)
|
||
{
|
||
return $this->apiMessages($id);
|
||
}
|
||
// Удаляем сообщение из очереди
|
||
public function deleteMessage($id)
|
||
{
|
||
return $this->apiMessages($id, true);
|
||
}
|
||
|
||
// 4. Работа с заказами
|
||
// $op = list | get | create | delete
|
||
public function apiOrders($id = 0, $op = 'list', $fields = [])
|
||
{
|
||
$entry_point = 'orders';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
if ($id === 0) {
|
||
if($op == 'list') {
|
||
// 4.1.Получение списка заказов
|
||
if(empty($fields)){
|
||
// page - страница, size - элементов на странице
|
||
$fields = ['page'=>1, 'size'=>50];
|
||
}
|
||
$return['result'] = $this->request($entry_point, $fields, 'GET');
|
||
// Ответ - массив [content[id,number,serviceType,objectType,state,customerName,address,requestDate], size, totalElements, totalPages, pageNumber]
|
||
}
|
||
elseif($op == 'create'){
|
||
// 4.2.Отправка заказа
|
||
$valid_fields = array(
|
||
'api_id' => 'api_id',
|
||
'orderId' => 'orderId', // 'Целое число', // Идентификатор заказа во Внешней системе
|
||
'serviceType' => 'serviceType', // 'Код', // обязательно, Тип услуги оценки, Словарь №8
|
||
'objectType' => 'objectType', // 'Код', // обязательно, Тип объекта оценки, Словарь №2
|
||
'reportUsageType'=> 'reportUsageType', // 'Код', // обязательно, Цель оценки, Словарь №9
|
||
'address' => 'address', // 'Текст', // обязательно, Адрес объекта оценки
|
||
'customerName' => 'customerName', // 'Текст', // ФИО клиента
|
||
'customerPhone' => 'customerPhone', // 'Текст', // Контактный телефон клиента
|
||
'customerEmail' => 'customerEmail', // 'Текст', // Email клиента
|
||
'сontactName' => 'сontactName', // ФИО контактного лица
|
||
'сontactPhone' => 'сontactPhone', // Номер телефона контактного лица
|
||
'сontactEmail' => 'сontactEmail', // Email контактного лица
|
||
'inspectionContactName' => 'inspectionContactName', // 'Текст', // ФИО, ответственного за осмотр
|
||
'inspectionContactPhone' => 'inspectionContactPhone', // 'Текст', // Контактный телефон, ответственного за осмотр
|
||
'bankId' => 'bankId', // 'Целое число', // Идентификатор банка в Системе
|
||
'bankManagerName' => 'bankManagerName', // 'Текст', // ФИО менеджера банка
|
||
'bankManagerEmail' => 'bankManagerEmail', // 'Текст', // Email менеджера банка
|
||
'managerComment' => 'managerComment', // 'Текст', // Комментарий менеджера
|
||
'managerEmail' => 'managerEmail', // 'Текст', // Email менеджера
|
||
'deliveryRequired' => 'deliveryRequired', // true\false // Требуется доставка отчета
|
||
'deliveryAddress' => 'deliveryAddress', // Текст // Адрес доставки
|
||
'deliveryContactName' => 'deliveryContactName', // Текст // Контактное лицо для доставки
|
||
'deliveryContactPhone' => 'deliveryContactPhone', // Текст // Номер телефона контактного лица для доставки
|
||
//'customerPassportSerial' => 'Текст', // Серия паспорта клиента
|
||
//'customerPassportNumber' => 'Текст', // Номер паспорта клиента
|
||
//'customerPassportSub' => 'Текст', // Код подразделения, выдавшего паспорт клиенту
|
||
//'customerPassportIssuedBy' => 'Текст', // Название отделения, кем выдан паспорт клиенту
|
||
//'customerPassportIssueDate' => 'Дата', // Дата выдачи паспорта
|
||
//'customerPassportAddress' => 'Текст', // Адрес регистрации клиента
|
||
'appraisalCompanyId' => 'appraisalCompanyId', // 'Целое число', // Обязательно, Идентификатор оценочной компании
|
||
'contractCost' => 'contractCost', // 'Целое число', // Стоимость объекта при покупке
|
||
'allowMessaging' => 'allowMessaging', // Разрешить обмен сообщениями
|
||
'calculationId' => 'calculationId', 'Целое число', // Идентификатор автоматического расчета из п.6
|
||
/*'files' => 'files', /* array(
|
||
'name' => 'Название категории',
|
||
'files' => ['name' => 'название', 'data' => 'Base64:data']
|
||
), // Прикрепляемые файлы // */
|
||
);
|
||
//TODO Файлы обрабатывать отдельно из массива $_FILES
|
||
// Ответ - элемент: [id - идентификатор заказа]
|
||
$match = WebAppRaiserDB::matchFieldsToSave($fields, $valid_fields);
|
||
$res = $this->request($entry_point.'/create', $match['fields_to_save'], 'POST');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
$return['body'] = $res['body'];
|
||
$return['match'] = $match;
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, сохраняем заказ в свою базу
|
||
$fields['id'] = $return['result']['id'];
|
||
$fields['requestDate'] = time();
|
||
$fields['api_id'] = $this->war_id;
|
||
$return['fields'] = $fields;
|
||
$inner_id = WebAppRaiserOrder::save($fields);
|
||
if($inner_id){
|
||
$return["msg"] = "Заказ сохранен.";
|
||
//$return["status"] = 'success';
|
||
}
|
||
else{
|
||
$return["msg"] = "Возникла проблема при сохранении в базу данных.";
|
||
$return["status"] = 'error';
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
}
|
||
elseif(is_numeric($id) && $id > 0 && $op == 'get'){
|
||
// 4.3.Получение информации о заказе
|
||
//$result = $this->request('orders/'.$id);
|
||
/* Ответ - элемент: [
|
||
'id' => 'Целое число' - Да Идентификатор заказа
|
||
'externalId' => 'Целое число' - Идентификатор заказа во Внешней системе
|
||
'number' => 'Текст' - Номер заказа
|
||
'state' => 'Код' - Статус заказа. Словарь №10
|
||
'serviceType' => 'Код' - Тип услуги оценки, Словарь №8
|
||
'objectType' => 'Код' - Тип объекта оценки, Словарь №2
|
||
'reportUsageType' => 'Код' - Цель оценки, Словарь №9
|
||
'preliminaryCalculationValue' => 'Число' - Стоимость, полученная в результате расчета
|
||
'address' => 'Текст' - Адрес объекта оценки
|
||
'customerName' => 'Текст' - ФИО клиента
|
||
'requestDate' => 'Дата и время' - Дата заказа
|
||
'payed' => 'true\false' - обязательно, Оплачено
|
||
'reportPrinted' => 'true\false' - обязательно, Отчет распечатан
|
||
'reportReady' => 'true\false' - обязательно, Отчет готов
|
||
'deliveryRequired' => 'true/false' - обязательно, Требуется доставка
|
||
'deliveryAddress' => 'Текст' - Адрес доставки
|
||
'documentsChecked' => 'true/false' - обязательно, Документы проверены
|
||
'inspectionRequired' => 'true/false' - обязательно, Требуется осмотр
|
||
'inspectionConfirmed' => 'true/false' - обязательно, Осмотр согласован
|
||
'inspectionDate' => 'Дата и время' - Дата осмотра
|
||
'inspected' => 'true/false' - обязательно, Осмотр проведен
|
||
'appraisalManagerName' => 'Текст' - ФИО менеджера оценочной компании
|
||
|
||
* ] */
|
||
$res = $this->request($entry_point.'/'.$id, [], 'GET');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, сохраняем заказ в свою базу
|
||
$api_fields = $return['result'];
|
||
unset($api_fields['requestDate']);
|
||
unset($api_fields['externalId']);
|
||
//$api_fields['requestDate'] = strtotime($api_fields['requestDate']);
|
||
$api_fields['readyDate'] = strtotime($api_fields['readyDate']);
|
||
$api_fields['inspectionDate'] = strtotime($api_fields['inspectionDate']);
|
||
$api_fields['woid'] = $fields['woid'];
|
||
$api_fields['api_id'] = $this->war_id;
|
||
$api_fields['updateDate'] = time();
|
||
$return['fields'] = $api_fields;
|
||
$inner_id = WebAppRaiserOrder::save($api_fields);
|
||
if($inner_id){
|
||
$return["msg"] = "Заказ сохранен.";
|
||
//$return["status"] = 'success';
|
||
//$return["match_fields"] = $inner_id;
|
||
}
|
||
else{
|
||
$return["msg"] = "Возникла проблема при сохранении в базу данных.";
|
||
$return["status"] = 'error';
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
elseif(is_numeric($id) && $id > 0 && $op == 'delete'){
|
||
// 4.7.Удаление заказа
|
||
$res = $this->request($entry_point.'/'.$id, [], 'DELETE');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, удаляем заказ из своей базы
|
||
$rowsNum = WebAppRaiserOrder::delete($id);
|
||
if($rowsNum > 0){
|
||
$return["msg"] = "Заказ удален.";
|
||
//$return["status"] = 'success';
|
||
}
|
||
else{
|
||
$return["msg"] = "Возникла проблема при удалении заказа из базы данных.";
|
||
$return["status"] = 'error';
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
}
|
||
|
||
return $return;
|
||
}
|
||
|
||
// Список заказов для данной страницы в данном объеме
|
||
public function listOrders($fields)
|
||
{
|
||
if(empty($fields)){
|
||
$fields = ['page'=>1, 'size'=>50];
|
||
}
|
||
return $this->apiOrders(0, 'list', $fields);
|
||
}
|
||
// Создание заказа на оценку
|
||
public function createOrder($fields)
|
||
{
|
||
return $this->apiOrders(0,'create', $fields);
|
||
}
|
||
// Показать один объект
|
||
public function getOrder($fields)
|
||
{
|
||
return $this->apiOrders($fields['order_id'], 'get', $fields);
|
||
}
|
||
// Удалить один объект
|
||
public function deleteOrder($fields)
|
||
{
|
||
return $this->apiOrders($fields['order_id'], 'delete');
|
||
}
|
||
|
||
// 4.4.Отправка дополнительных документов к заказу
|
||
public function addDocuments($id, $fields)
|
||
{
|
||
$entry_point = 'orders/'.$id.'/addDocuments';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
//msg('Fields for API', [$entry_point, $fields]);
|
||
|
||
$res = $this->request($entry_point, $fields, 'POST');
|
||
//msg('API result', [$res]);
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
$return['body'] = $res['body'];
|
||
$return['fields'] = $fields;
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, файлы отправлены
|
||
$return["msg"] = "Файлы отправлены.";
|
||
//$return["status"] = 'success';
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
|
||
return $return;
|
||
}
|
||
|
||
// 4.5.Получение отчета об оценке
|
||
public function getRaiserReport($fields){
|
||
$entry_point = 'orders/'.$fields['order_id'].'/downloadReportPackage';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
// ответ Набор документов в формате zip.
|
||
$res = $this->requestFile($entry_point, $fields, 'GET');
|
||
//msg('API result', [$res]);
|
||
//$return['info'] = $res['info'];
|
||
//$return['result'] = $res['result'];
|
||
//$return['body'] = $res['body'];
|
||
//return $return;
|
||
}
|
||
|
||
// 4.6.Получение списка сообщений в заказе
|
||
public function сhatMessages($id){
|
||
$entry_point = 'orders/'.$id.'/chatMessages';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
$res = $this->request($entry_point, [], 'GET');
|
||
//msg('API result', [$res]);
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
$return['body'] = $res['body'];
|
||
if ($return['info']['http_code'] == '200'){
|
||
// Запрос прошел без ошибок сохраняем запись в базу данных
|
||
$valid_fields = array(
|
||
'id' => 'id',
|
||
'out_id' => 'out_id',
|
||
'api_id' => 'api_id',
|
||
'date' => 'date',
|
||
'type' => 'type',
|
||
'orderId' => 'orderId',
|
||
'fields' => 'fields',
|
||
);
|
||
//msg('RETURN', $return['result']);
|
||
if(is_array($return['result'])){
|
||
foreach($return['result'] as $msg_item){
|
||
$fields_fields = array();
|
||
foreach(['sourceType', 'userName', 'text', 'unread'] as $key){
|
||
if(isset($msg_item[$key]))
|
||
$fields_fields[$key] = $msg_item[$key];
|
||
}
|
||
$msg_id = 0;
|
||
$test_records = WebAppRaiserDB::select('war_msg', 'out_id', $msg_item['id']);
|
||
foreach($test_records as $test_record){
|
||
if($test_record['api_id'] == $this->war_id){
|
||
$msg_id = $test_record['id'];
|
||
}
|
||
}
|
||
$fields = array(
|
||
'id' => $msg_id,
|
||
'api_id' => $this->war_id,
|
||
'out_id' => $msg_item['id'],
|
||
'date' => strtotime($msg_item['date']),
|
||
'type' => 'CHAT_MESSAGE',
|
||
'orderId' => $id,
|
||
'fields' => base64_encode(serialize($fields_fields)),
|
||
);
|
||
$inner_id = WebAppRaiserDB::save('war_msg', $fields, $valid_fields);
|
||
if($inner_id){
|
||
//$return["msg"] = "Сообщение сохранено.";
|
||
//$return["status"] = 'success';
|
||
}
|
||
else{
|
||
$return["msg"] = "Возникла проблема при сохранении сообщения в базу данных.";
|
||
$return["status"] = 'error';
|
||
}
|
||
}
|
||
if($return["status"] == 'success'){
|
||
$return["msg"] = "Сообщение сохранено.";
|
||
}
|
||
}
|
||
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser при чтении одного сообщения. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
return $return;
|
||
}
|
||
|
||
// 4.7.Отправка текстового сообщения к заказу
|
||
public function sendChatMessage($id, $fields){
|
||
$entry_point = 'orders/'.$id.'/sendChatMessage';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
$res = $this->request($entry_point, $fields, 'POST');
|
||
//msg('API result', [$res]);
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
$return['body'] = $res['body'];
|
||
$return['fields'] = $fields;
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, сообщение отправлено
|
||
$return["msg"] = "Сообщение отправлено.";
|
||
//$return["status"] = 'success';
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
return $return;
|
||
}
|
||
|
||
//4.7.Принятие заказа в работу оценочной компанией (polling)
|
||
//4.8.Отклонение заказа оценочной компанией (polling)
|
||
//4.9.Получение информации об изменении статуса заказа (polling)
|
||
//4.10.Получение информации о готовности отчета (polling)
|
||
// 4.11.Получение информации о готовности расчета (polling)
|
||
//4.12.Получение текстового сообщения по заказу (polling)
|
||
|
||
//5. Получение списка банков
|
||
public function getBanks(){
|
||
$entry_point = 'banks';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
$res = $this->request($entry_point, [], 'GET');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
if ($return['info']['http_code'] == '200'){
|
||
// без ошибок, сохраняем заказ в свою базу
|
||
$return["msg"] = "Успех";
|
||
//$return["status"] = 'success';
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
return $return;
|
||
}
|
||
|
||
// Загрузка кэшированных данных по банкам и обновление кэша раз в сутки
|
||
public function loadBanks()
|
||
{
|
||
$banks = array();
|
||
$time = time();
|
||
$sql_res = mysql_query("SELECT * FROM war_banks");
|
||
while ($row = mysql_fetch_array($sql_res)) {
|
||
$banks_res[] = $row;
|
||
}
|
||
//$banks_res = mysql_fetch_assoc($sql_res);
|
||
$update_flag = (!empty($banks_res))?false:true;
|
||
foreach($banks_res as $bank_item){
|
||
$test_time = $time - (60*60*24);
|
||
if ($bank_item["updateDate"] < $test_time){
|
||
$update_flag = true;
|
||
}
|
||
$banks[$bank_item['id']] = $bank_item['name'];
|
||
}
|
||
if ($update_flag) {
|
||
// Обновляем кэш
|
||
$api_res = $this->getBanks();
|
||
if($api_res['status'] == 'success'){
|
||
foreach($api_res['result'] as $api_item){
|
||
if(isset($banks[$api_item['id']])){
|
||
$sql = sprintf("UPDATE `war_banks` SET `name`='%s', `updateDate`=%d WHERE `id`=%d", $api_item['name'], $time, $api_item['id']);
|
||
mysql_query($sql);
|
||
}
|
||
else{
|
||
$sql = sprintf("INSERT INTO `war_banks` (`id`, `name`, `updateDate`) VALUES ('%d', '%s', '%d')", $api_item['id'], $api_item['name'], $time);
|
||
mysql_query($sql);
|
||
$banks[$api_item['id']] = $api_item['name'];
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return $banks;
|
||
}
|
||
|
||
//6. Расчет стоимости объекта
|
||
//6.1.Проверка информации по адресу (устаревшее)
|
||
|
||
//6.2.Проверка наличия информации для проведения расчета // calculations/checkInformation
|
||
|
||
//6.3.Расчет стоимости объекта // calculations/calculate
|
||
public function getCalculate($fields)
|
||
{
|
||
$entry_point = 'calculations/calculate';
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => array(),
|
||
);
|
||
|
||
$valid_fields = array(
|
||
'objectType' => 'objectType',
|
||
'address'=> 'address',
|
||
'cadNum'=> 'cadNum',
|
||
'buildingStage'=> 'buildingStage',
|
||
'floor'=> 'floor',
|
||
'totalFloors'=> 'totalFloors',
|
||
'square' => 'square',
|
||
'decorationType'=> 'decorationType',
|
||
'buildYear'=> 'buildYear',
|
||
'wallMaterial'=> 'wallMaterial',
|
||
'latitude'=> 'latitude',
|
||
'longitude'=> 'longitude',
|
||
'estimateValue' => 'estimateValue',
|
||
'saveCalculation'=> 'saveCalculation',
|
||
);
|
||
|
||
$match = WebAppRaiserDB::matchFieldsToSave($fields, $valid_fields);
|
||
$res = $this->request($entry_point, $match['fields_to_save'], 'POST');
|
||
$return['info'] = $res['info'];
|
||
$return['result'] = $res['result'];
|
||
$return['body'] = $res['body'];
|
||
$return['match'] = $match;
|
||
$return['fields'] = $fields;
|
||
if ($return['info']['http_code'] == '200'){
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка обращения к API webappraiser. ";
|
||
$return["msg"] .= $return['result']['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
|
||
return $return;
|
||
}
|
||
|
||
private function request($path, $fields = [], $method = 'GET')
|
||
{
|
||
$body = json_encode($fields);
|
||
$url = $this->api_uri;
|
||
$token = $this->war_access_token;
|
||
$ch = curl_init($url.$path);
|
||
switch ($method){
|
||
case 'POST':
|
||
$header = array(
|
||
'Content-Type: application/json; charset=UTF-8',
|
||
'Content-Length: ' . strlen($body),
|
||
'Authorization: Bearer ' . $token
|
||
);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
|
||
curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break;
|
||
case 'GET':
|
||
curl_setopt($ch,CURLOPT_URL, $url.$path);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
||
'Content-Type: application/json; charset=UTF-8',
|
||
//'Content-Length: ' . strlen($body),
|
||
'Authorization: Bearer ' . $token
|
||
));
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break;
|
||
case 'PUT':
|
||
case 'DELETE':
|
||
curl_setopt($ch,CURLOPT_URL, $url.$path);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
||
'Content-Type: application/json; charset=UTF-8',
|
||
'Content-Length: ' . strlen($body),
|
||
'Authorization: Bearer ' . $token
|
||
));
|
||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break;
|
||
}
|
||
|
||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
|
||
|
||
// get stringified data/output. See CURLOPT_RETURNTRANSFER
|
||
$data = curl_exec($ch);
|
||
// get info about the request
|
||
$info = curl_getinfo($ch);
|
||
// close curl resource to free up system resources
|
||
curl_close($ch);
|
||
$result = json_decode($data, true);
|
||
|
||
return array('result' => $result,'info'=> $info, 'body'=> $body);
|
||
}
|
||
|
||
private function requestFile($path, $fields = [], $method = 'GET')
|
||
{
|
||
//$body = json_encode($fields);
|
||
$url = $this->api_uri;
|
||
$token = $this->war_access_token;
|
||
$ch = curl_init($url.$path);
|
||
switch ($method){
|
||
/*case 'POST':
|
||
$header = array(
|
||
'Content-Type: application/json; charset=UTF-8',
|
||
'Content-Length: ' . strlen($body),
|
||
'Authorization: Bearer ' . $token
|
||
);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
|
||
curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break; // */
|
||
case 'GET':
|
||
curl_setopt($ch,CURLOPT_URL, $url.$path);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
||
'Authorization: Bearer ' . $token
|
||
));
|
||
curl_setopt($ch, CURLOPT_HEADER, 1);
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break;
|
||
/*case 'PUT':
|
||
case 'DELETE':
|
||
curl_setopt($ch,CURLOPT_URL, $url.$path);
|
||
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
|
||
'Content-Type: application/json; charset=UTF-8',
|
||
'Content-Length: ' . strlen($body),
|
||
'Authorization: Bearer ' . $token
|
||
));
|
||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
break; // */
|
||
}
|
||
|
||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
|
||
|
||
// get stringified data/output. See CURLOPT_RETURNTRANSFER
|
||
$file = curl_exec($ch);
|
||
$info = curl_getinfo($ch);
|
||
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
|
||
$header = substr($file, 0, $header_size);
|
||
// Get the Body from response
|
||
$body = substr($file, $header_size);
|
||
// Explode Header rows into an array
|
||
$header_items = explode("\n", $header);
|
||
$disposition = '';
|
||
foreach ($header_items as $header_item){
|
||
if(strpos($header_item, 'filename')){
|
||
$disposition = $header_item;
|
||
}
|
||
}
|
||
|
||
// Close cURL handler
|
||
curl_close($ch);
|
||
|
||
// find the filname in the headers.
|
||
$file_name = 'Report-object-'.$fields['object_id'].'-order-'.$fields['order_id'].'.zip';
|
||
if(empty($disposition)){
|
||
$disposition = 'Content-Disposition: attachment; filename='.$file_name;
|
||
}
|
||
if($info['http_code'] == '200') {
|
||
header('Content-Description: File Transfer');
|
||
header('Content-Type: application/octet-stream');
|
||
header('Content-Transfer-Encoding: binary');
|
||
header('Expires: 0');
|
||
header('Cache-Control: must-revalidate');
|
||
header('Pragma: public');
|
||
header($disposition);
|
||
echo $body;
|
||
exit;
|
||
}
|
||
else {
|
||
$result = json_decode($body, true);
|
||
echo '<h1 style="margin: 60px auto;text-align: center;font-size: 3em;">'.$result['message'].'<h1>';
|
||
exit;
|
||
}
|
||
}
|
||
|
||
// $grant_type = 'password' | 'refresh_token'
|
||
public function auth_request($grant_type = 'password', $fields = array())
|
||
{
|
||
$return = array(
|
||
'status' => 'success',
|
||
'msg' => '',
|
||
'info' => array(),
|
||
'result' => array(),
|
||
'fields' => $fields,
|
||
);
|
||
$url = $this->auth_uri.'oauth/token';
|
||
|
||
if ($grant_type == 'password') {
|
||
$req_fields = array(
|
||
'username' => $fields['war_username'],
|
||
'client_id' => $fields['war_client_id'],
|
||
'client_secret' => $fields['war_client_secret'],
|
||
'grant_type' => $grant_type,
|
||
);
|
||
|
||
$ch = curl_init($url);
|
||
curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $req_fields); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
|
||
|
||
// get stringified data/output. See CURLOPT_RETURNTRANSFER
|
||
$data = curl_exec($ch);
|
||
// get info about the request
|
||
$info = curl_getinfo($ch);
|
||
// close curl resource to free up system resources
|
||
curl_close($ch);
|
||
$result = json_decode($data, true);
|
||
|
||
$return['info'] = $info;
|
||
$return['result'] = $result;
|
||
|
||
if ($info['http_code'] == '200'){
|
||
// без ошибок, обновляем и сохраняем почту и токен.
|
||
$db_fields = array (
|
||
'war_id' => $this->war_id,
|
||
'war_user_id' => $fields['war_user_id'],
|
||
'war_username' => $fields['war_username'],
|
||
'war_client_id' => $fields['war_client_id'],
|
||
'war_client_secret' => $fields['war_client_secret'],
|
||
'war_access_token' => $result['access_token'],
|
||
'war_refresh_token' => $result['refresh_token'],
|
||
'war_expires_in' => time() + $result['expires_in'],
|
||
'war_token_type' => $result['token_type'],
|
||
);
|
||
if(!empty($fields['war_pincode'])) {
|
||
$db_fields['war_pincode'] = $fields['war_pincode'];
|
||
}
|
||
|
||
if(self::save($db_fields)){
|
||
$return["msg"] = "Токен сохранен.";
|
||
//$return["status"] = 'success';
|
||
}
|
||
else {
|
||
$return["msg"] = "Ошибка сохранения токена в базу данных";
|
||
$return["status"] = 'error';
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
$return["msg"] = "Ошибка соединения с webappraiser. ";
|
||
$return["msg"] .= $info['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
return $return;
|
||
}
|
||
else {
|
||
// Обновляем токен данных через refresh_token
|
||
$fields = array(
|
||
'grant_type' => 'refresh_token',
|
||
'refresh_token' => $this->war_refresh_token,
|
||
);
|
||
$ch = curl_init($url);
|
||
curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
|
||
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // Set the posted fields
|
||
// Returns the data/output as a string instead of raw data
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
|
||
$data = curl_exec($ch);
|
||
$info = curl_getinfo($ch);
|
||
curl_close($ch);
|
||
$result = json_decode($data, true);
|
||
|
||
$return['info'] = $info;
|
||
$return['result'] = $result;
|
||
|
||
if ($info['http_code'] == '200'){
|
||
// без ошибок, обновляем и сохраняем токен.
|
||
$fields = array (
|
||
'war_id' => $this->war_id,
|
||
'war_access_token' => $result['access_token'],
|
||
'war_refresh_token' => $result['refresh_token'],
|
||
'war_expires_in' => time() + $result['expires_in'],
|
||
'war_token_type' => $result['token_type'],
|
||
);
|
||
self::save($fields);
|
||
$return["msg"] = "Токен сохранен.";
|
||
$return["status"] = 'success';
|
||
return $return;
|
||
}
|
||
else {
|
||
// Произошла ошибка
|
||
//TODO если просрочен refresh_token то делать запрос заново
|
||
$return["msg"] = "Ошибка соединения с webapprizer. ";
|
||
$return["msg"] .= $info['message'];
|
||
$return["status"] = 'error';
|
||
return $return;
|
||
}
|
||
|
||
}
|
||
return $return;
|
||
}
|
||
|
||
public static function getDict($dict_name, $item = '', $info = false)
|
||
{
|
||
if (isset(self::$dict_list[$dict_name])) {
|
||
$dict = self::$$dict_name;
|
||
if($info){
|
||
return self::$dict_list[$dict_name];
|
||
}
|
||
elseif(!empty($item) && isset($dict[$item])){
|
||
return $dict[$item];
|
||
}
|
||
elseif(!empty($item) && !isset($dict[$item])){
|
||
return false;
|
||
}
|
||
else {
|
||
return $dict;
|
||
}
|
||
}
|
||
else {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
|
||
public function get($name){
|
||
if(isset($this->$name)) {
|
||
return $this->$name;
|
||
}
|
||
else {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
}
|
||
|