P
P
Pan Propan2015-06-04 10:33:58
PHP
Pan Propan, 2015-06-04 10:33:58

How to log in REST API Authorization & Authentication??

We have
POST API/2.0/AUTHENTICATION 7629547bd64248d981e0c300dd0c5788.png5846c7381c29434e96ba1c3b88d6885c.png
Help to log in and get a token for further work with the API.
Did so

<?php
#Массив с параметрами, которые нужно передать методом POST к API системы
$user=array(
  'userName'=>'**********@mail.ru', #Ваш логин (электронная почта)
  'password'=>'**********' #Хэш для доступа к API (смотрите в профиле пользователя)
);
 
 
#Формируем ссылку для запроса
$link='http://192.168.1.221/api/2.0/authentication';

$curl=curl_init(); #Сохраняем дескриптор сеанса cURL
#Устанавливаем необходимые опции для сеанса cURL
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_USERAGENT,'amoCRM-API-client/1.0');
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($user));
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($curl,CURLOPT_HEADER,false);

$out=curl_exec($curl); #Инициируем запрос к API и сохраняем ответ в переменную
$code=curl_getinfo($curl,CURLINFO_HTTP_CODE); #Получим HTTP-код ответа сервера
curl_close($curl); #Завершаем сеанс cURL


$code=(int)$code;
$errors=array(
  301=>'Moved permanently',
  400=>'Bad request',
  401=>'Unauthorized',
  403=>'Forbidden',
  404=>'Not found',
  500=>'Internal server error',
  502=>'Bad gateway',
  503=>'Service unavailable'
);
try
{
  #Если код ответа не равен 200 или 204 - возвращаем сообщение об ошибке
  if($code>=400)
    throw new Exception(isset($errors[$code]) ? $errors[$code] : 'Undescribed error',$code);
}
catch(Exception $E)
{
  die('Ошибка: '.$E->getMessage().PHP_EOL.'Код ошибки: '.$E->getCode());
}
 
/**
 * Данные получаем в формате JSON, поэтому, для получения читаемых данных,
 * нам придётся перевести ответ в формат, понятный PHP
 */
$Response=json_decode($out,true);
print_r($Response);
?>

get
Array ([count] => 1 [status] => 0 [statusCode] => 201 [response] => Array ([token] => 4mWmJ5td7eXICAjj6fpXNj0m2U + RdC8EO8Zwh4ojHFTjHQYKjfaPN7Kidq6qclpqMSYRFBYc8 / muXqq + CKdHvboMebFL + VB64YN4qvqTa9J7bKx3a2uIT + 6 / srpwhYCC [expires] => 2016-06-04T10:33:18.2412940+03:00 [sms] => [phoneNoise] => ) )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pan Propan, 2015-06-05
@mgis

Ready option.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$url = ' https://-------.onlyoffice.eu/api/2.0/authentication ';
$params = array(
'userName' => '[email protected]', // in localhost/post.php this would be $_POST['param1'] == '123'
'password' => '---------', // in localhost/post.php this would be $_POST['param2'] == 'abc'
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array( 'content' => http_build_query($params) ) ))); $obj=json_decode($result, true); $token = $obj['response']['token'];
'method' => 'POST',
'header' => array('Accept:
print_r($token);
#Add user
$urlAdd = ' https://-------.onlyoffice.eu/api/2.0/people ';
#We form the request parameters, describe the parameters of the user we want to add
$userdAdd = array('isVisitor' =>'false',
'email' => '[email protected]',
'firstname' => 'Mahmood',
'lastname' => 'Abbas',
'title'=> 'Tiger', 'birthday' => '1989-05-13T06:30:00.0000000-07:00', 'worksfrom' => '2014-09-13T06:30: 00.0000000-07:00', '
$addMember = file_get_contents($urlAdd, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => array('Accept: application/json', 'Content-type: application/x-www-form-urlencoded', 'Authorization: 9na7+RVlKU1at0aZm38UCRHE8Rp7W5Tqr9M4+OgFvQkVAUJiFRaWuFLrmQ1nqOvlZ0kTOYfcJGrNPvFs50Z2YfYiLHI1CAnizaNtJ8Wy6RJcYidhdv63GNJLbe5')
,
http_build_query($userdAdd) )
)));
var_dump($addMember);
?>

P
Pavel Tetyuev, 2015-06-04
@jetexe

After all, you have a token in the array and lies ... or have I misunderstood something?
$token = $Response['response']['token'];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question