Last active
January 12, 2022 09:52
-
-
Save BekNaji/98e616f60291590013c985b156b4b48e to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Send rest query to Bitrix24. | |
* | |
* @param $method - Rest method, ex: methods | |
* @param array $params - Method params, ex: Array() | |
* @param array $auth - Authorize data, received from event | |
* @param boolean $authRefresh - If authorize is expired, refresh token | |
* @return mixed | |
*/ | |
function restCommand($method, array $params = [], array $auth = [], $authRefresh = true) | |
{ | |
$queryUrl = $auth["client_endpoint"].$method; | |
$queryData = http_build_query(array_merge($params, ["auth" => $auth["access_token"]])); | |
$curl = curl_init(); | |
curl_setopt_array($curl, [ | |
CURLOPT_POST => 1, | |
CURLOPT_HEADER => 0, | |
CURLOPT_RETURNTRANSFER => 1, | |
CURLOPT_SSL_VERIFYPEER => 1, | |
CURLOPT_URL => $queryUrl, | |
CURLOPT_POSTFIELDS => $queryData, | |
]); | |
$result = curl_exec($curl); | |
curl_close($curl); | |
$result = json_decode($result, 1); | |
if ($authRefresh && isset($result['error']) && in_array($result['error'], ['expired_token', 'invalid_token'])) | |
{ | |
$auth = restAuth($auth); | |
if ($auth) | |
{ | |
$result = restCommand($method, $params, $auth, false); | |
} | |
} | |
return $result; | |
} | |
/** | |
* Get new authorize data if you authorize is expire. | |
* | |
* @param array $auth - Authorize data, received from event | |
* @return bool|mixed | |
*/ | |
function restAuth($auth) | |
{ | |
if (!CLIENT_ID || !CLIENT_SECRET) | |
return false; | |
if(!isset($auth['refresh_token'])) | |
return false; | |
$queryUrl = 'https://oauth.bitrix.info/oauth/token/'; | |
$queryData = http_build_query($queryParams = array( | |
'grant_type' => 'refresh_token', | |
'client_id' => CLIENT_ID, | |
'client_secret' => CLIENT_SECRET, | |
'refresh_token' => $auth['refresh_token'], | |
)); | |
$curl = curl_init(); | |
curl_setopt_array($curl, array( | |
CURLOPT_HEADER => 0, | |
CURLOPT_RETURNTRANSFER => 1, | |
CURLOPT_URL => $queryUrl.'?'.$queryData, | |
)); | |
$result = curl_exec($curl); | |
curl_close($curl); | |
$result = json_decode($result, 1); | |
if (!isset($result['error'])) | |
{ | |
$appsConfig = []; | |
} | |
else | |
{ | |
$result = false; | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment