Last active
October 20, 2023 08:34
-
-
Save XOlegator/9f67fa057f39d1c685e9ccf83ed74457 to your computer and use it in GitHub Desktop.
Bitrix24 example API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
/** | |
* client_id приложения | |
*/ | |
define('CLIENT_ID', 'local.somecode1.somecode2'); | |
/** | |
* client_secret приложения | |
*/ | |
define('CLIENT_SECRET', 'somebigcode'); | |
/** | |
* относительный путь приложения на сервере | |
*/ | |
define('PATH', '/integration/index.php'); | |
/** | |
* полный адрес к приложению | |
*/ | |
define('REDIRECT_URI', 'http://sitename' . PATH); | |
/** | |
* scope приложения | |
*/ | |
//define('SCOPE', 'crm,log,user'); | |
define('SCOPE', 'crm,user'); | |
/** | |
* протокол, по которому работаем. должен быть https | |
*/ | |
define('PROTOCOL', "https"); | |
/** | |
* Производит перенаправление пользователя на заданный адрес | |
* | |
* @param string $url адрес | |
*/ | |
function redirect($url) | |
{ | |
Header("HTTP 302 Found"); | |
Header("Location: ".$url); | |
die(); | |
} | |
/** | |
* Совершает запрос с заданными данными по заданному адресу. В ответ ожидается JSON | |
* | |
* @param string $method GET|POST | |
* @param string $url адрес | |
* @param array|null $data POST-данные | |
* | |
* @return array | |
*/ | |
function query($method, $url, $data = null) | |
{ | |
$query_data = ""; | |
$curlOptions = array( | |
CURLOPT_RETURNTRANSFER => true | |
); | |
if($method == "POST") | |
{ | |
$curlOptions[CURLOPT_POST] = true; | |
$curlOptions[CURLOPT_POSTFIELDS] = http_build_query($data); | |
} | |
elseif(!empty($data)) | |
{ | |
$url .= strpos($url, "?") > 0 ? "&" : "?"; | |
$url .= http_build_query($data); | |
} | |
$curl = curl_init($url); | |
curl_setopt_array($curl, $curlOptions); | |
$result = curl_exec($curl); | |
return json_decode($result, 1); | |
} | |
/** | |
* Вызов метода REST. | |
* | |
* @param string $domain портал | |
* @param string $method вызываемый метод | |
* @param array $params параметры вызова метода | |
* | |
* @return array | |
*/ | |
function call($domain, $method, $params) | |
{ | |
return query("POST", PROTOCOL."://".$domain."/rest/".$method, $params); | |
} | |
function logger($message, $type, $errors = null) | |
{ | |
$format = "[" . date('Y-m-d H:i:s') . "]"; | |
if (!is_null($errors) && is_array($errors)) { | |
$message .= ":\n"; | |
foreach ($errors as $error) { | |
$message .= "\t" . $error . "\n"; | |
} | |
} else { | |
$message .= "\n"; | |
} | |
$logDir = 'log/'; | |
switch ($type) { | |
case 'common': | |
$path = $logDir. "common.log"; | |
error_log($format . " " . $message, 3, $path); | |
break; | |
case 'history-log': | |
$path = $logDir . "history.log"; | |
file_put_contents($path, $message); | |
break; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
</head> | |
<body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$path_parts = pathinfo($_SERVER['SCRIPT_FILENAME']); // определяем директорию скрипта (полезно для запуска из cron'а) | |
chdir($path_parts['dirname']); // задаем директорию выполнение скрипта | |
require($path_parts['dirname'] . "/include/config.php"); | |
$error = ""; | |
// clear auth session | |
if(isset($_REQUEST["clear"]) || $_SERVER["REQUEST_METHOD"] == "POST") | |
{ | |
logger('Очищаем сессию' . "\n", 'common'); | |
unset($_SESSION["query_data"]); | |
} | |
if($_SERVER["REQUEST_METHOD"] == "POST") | |
{ | |
logger('Определили, что метод POST' . "\n", 'common'); | |
/******************* get code *************************************/ | |
if(!empty($_POST["portal"])) | |
{ | |
logger('Передан $_POST["portal"]' . "\n", 'common'); | |
$domain = $_POST["portal"]; | |
$params = array( | |
"response_type" => "code", | |
"client_id" => CLIENT_ID, | |
"redirect_uri" => REDIRECT_URI, | |
); | |
$path = "/oauth/authorize/"; | |
redirect(PROTOCOL."://".$domain.$path."?".http_build_query($params)); | |
} | |
/******************** /get code ***********************************/ | |
} | |
if(isset($_REQUEST["code"])) | |
{ | |
logger('Передан $_REQUEST["code"]' . "\n", 'common'); | |
/****************** get access_token ******************************/ | |
$code = $_REQUEST["code"]; | |
$domain = $_REQUEST["domain"]; | |
$member_id = $_REQUEST["member_id"]; | |
$params = array( | |
"grant_type" => "authorization_code", | |
"client_id" => CLIENT_ID, | |
"client_secret" => CLIENT_SECRET, | |
"redirect_uri" => REDIRECT_URI, | |
"scope" => SCOPE, | |
"code" => $code, | |
); | |
$path = "/oauth/token/"; | |
$query_data = query("GET", PROTOCOL."://".$domain.$path, $params); | |
if(isset($query_data["access_token"])) | |
{ | |
logger('Передан $query_data["access_token"]' . "\n", 'common'); | |
$_SESSION["query_data"] = $query_data; | |
$_SESSION["query_data"]["ts"] = time(); | |
redirect(PATH); | |
die(); | |
} | |
else | |
{ | |
$error = "Произошла ошибка авторизации! ".print_r($query_data, 1); | |
} | |
/********************** /get access_token *************************/ | |
} | |
elseif(isset($_REQUEST["refresh"])) | |
{ | |
logger('Передан $_REQUEST["refresh"]' . "\n", 'common'); | |
/******************** refresh auth ********************************/ | |
$params = array( | |
"grant_type" => "refresh_token", | |
"client_id" => CLIENT_ID, | |
"client_secret" => CLIENT_SECRET, | |
"redirect_uri" => REDIRECT_URI, | |
"scope" => SCOPE, | |
"refresh_token" => $_SESSION["query_data"]["refresh_token"], | |
); | |
$path = "/oauth/token/"; | |
$query_data = query("GET", PROTOCOL."://".$_SESSION["query_data"]["domain"].$path, $params); | |
if(isset($query_data["access_token"])) | |
{ | |
logger('Передан $query_data["access_token"]' . "\n", 'common'); | |
$_SESSION["query_data"] = $query_data; | |
$_SESSION["query_data"]["ts"] = time(); | |
redirect(PATH); | |
die(); | |
} | |
else | |
{ | |
$error = "Произошла ошибка авторизации! ".print_r($query_data); | |
} | |
/********************* /refresh auth ******************************/ | |
} | |
require_once(dirname(__FILE__)."/include/header.php"); | |
if(!isset($_SESSION["query_data"])) | |
{ | |
logger('НЕ установлен $_SESSION["query_data"]' . "\n", 'common'); | |
/******************************************************************/ | |
if($error) | |
{ | |
echo '<b>'.$error.'</b>'; | |
} | |
?> | |
<form action="" method="post"> | |
<input type="text" name="portal" placeholder="Адрес портала"> | |
<input type="submit" value="Авторизоваться"> | |
</form> | |
<?php | |
/******************************************************************/ | |
} | |
else | |
{ | |
logger('Передан $_SESSION["query_data"]' . "\n", 'common'); | |
/******************************************************************/ | |
if(time() > $_SESSION["query_data"]["ts"] + $_SESSION["query_data"]["expires_in"]) | |
{ | |
echo "<b>Авторизационные данные истекли</b>"; | |
} | |
else | |
{ | |
echo "Авторизационные данные истекут через ".($_SESSION["query_data"]["ts"] + $_SESSION["query_data"]["expires_in"] - time())." секунд"; | |
} | |
?> | |
<ul> | |
<li><a href="<?=PATH?>?test=user.current">Информация о пользователе</a> | |
<li><a href="<?=PATH?>?test=user.update">Загрузить новую аватарку пользователя</a> | |
<li><a href="<?=PATH?>?test=log.blogpost.add">Опубликовать запись в Живой Ленте</a> | |
<li><a href="<?=PATH?>?test=event.bind.lead">Установить обработчик события "Добавление лида"</a> | |
<li><a href="<?=PATH?>?test=event.bind.deal">Установить обработчик события "Обновление сделки"</a> | |
<li><a href="<?=PATH?>?test=event.get">Просмотр установленных обработчиков событий</a> | |
<li><a href="<?=PATH?>?test=event.unbind">Удаление установленного обработчика события</a> | |
<li><a href="<?=PATH?>?test=event.list">Просмотр всех доступных событий</a> | |
<li><a href="<?=PATH?>?test=deal.list">Просмотр всех сделок</a> | |
</ul> | |
<a href="<?=PATH?>?refresh=1">Обновить данные авторизации</a><br /> | |
<a href="<?=PATH?>?clear=1">Очистить данные авторизации</a><br /> | |
<?php | |
$test = isset($_REQUEST["test"]) ? $_REQUEST["test"] : ""; | |
switch($test) | |
{ | |
case 'user.current': // test: user info | |
$data = call($_SESSION["query_data"]["domain"], "user.current", array( | |
"auth" => $_SESSION["query_data"]["access_token"]) | |
); | |
break; | |
/*****************/ | |
case 'event.list': | |
$data = call($_SESSION["query_data"]["domain"], "events", array( | |
"auth" => $_SESSION["query_data"]["access_token"]) | |
); | |
break; | |
/******************/ | |
/*****************/ | |
case 'event.get': | |
$data = call($_SESSION["query_data"]["domain"], "event.get", array( | |
"auth" => $_SESSION["query_data"]["access_token"]) | |
); | |
break; | |
/******************/ | |
/*****************/ | |
case 'event.unbind': | |
$data = call($_SESSION["query_data"]["domain"], "event.unbind", array( | |
"auth" => $_SESSION["query_data"]["access_token"], | |
'EVENT' => 'ONCRMLEADADD', | |
'HANDLER' => REDIRECT_URI . "event.php" | |
)); | |
break; | |
/******************/ | |
/*****************/ | |
case 'event.bind.deal': // bind event handler | |
$data = call($_SESSION["query_data"]["domain"], "event.bind", array( | |
"auth" => $_SESSION["query_data"]["access_token"], | |
"EVENT" => "ONCRMDEALUPDATE", | |
"HANDLER" => "http://sitename/integration/reg-deal.php" | |
)); | |
break; | |
/******************/ | |
case 'user.update': // test batch&files | |
$fileContent = file_get_contents(dirname(__FILE__)."/images/MM35_PG189a.jpg"); | |
$batch = array( | |
'user' => 'user.current', | |
'user_update' => 'user.update?' | |
.http_build_query(array( | |
'ID' => '$result[user][ID]', | |
'PERSONAL_PHOTO' => array( | |
'avatar.jpg', | |
base64_encode($fileContent) | |
) | |
)) | |
); | |
$data = call($_SESSION["query_data"]["domain"], "batch", array( | |
"auth" => $_SESSION["query_data"]["access_token"], | |
"cmd" => $batch, | |
)); | |
break; | |
case 'event.bind.lead': // bind event handler | |
$data = call($_SESSION["query_data"]["domain"], "event.bind", array( | |
"auth" => $_SESSION["query_data"]["access_token"], | |
"EVENT" => "ONCRMLEADADD", | |
//"HANDLER" => REDIRECT_URI."event.php", | |
"HANDLER" => "http://sitename/integration/event.php" | |
)); | |
break; | |
case 'log.blogpost.add': // add livefeed entry | |
$fileContent = file_get_contents(dirname(__FILE__)."/images/MM35_PG189a.jpg"); | |
$data = call($_SESSION["query_data"]["domain"], "log.blogpost.add", array( | |
"auth" => $_SESSION["query_data"]["access_token"], | |
"POST_TITLE" => "Hello world!", | |
"POST_MESSAGE" => "Goodbye, cruel world :-(", | |
"FILES" => array( | |
array( | |
'minotaur.jpg', | |
base64_encode($fileContent) | |
) | |
), | |
)); | |
break; | |
default: | |
$data = $_SESSION["query_data"]; | |
break; | |
} | |
echo '<pre>'; var_export($data); echo '</pre>'; | |
/******************************************************************/ | |
} | |
require_once(dirname(__FILE__)."/include/footer.php"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment