+7(960) 250-82-68 spam@mirossa.ru


  MCU         C           1С         PHP       JAVA      разное 


Скрипты
 
 

ЕСИА - Единая система идентификации и аутентификации
Интеграция ИС с ЕСИА посредством подхода на базе REST (Аутентификация через OAuth2.0) (14.01.2018)

//*****************файл index.php*************************************************************

<?php
echo '<!DOCTYPE HTML>';
echo '<html>';
echo '<head>';
echo '<meta charset="utf-8">';
echo '<link type="text/css" rel="stylesheet" href="css/css.css" />';
echo '<title> Авторизация</title>';
echo '</head>';
echo '<body>';

echo '<form action="/firstR.php" method="GET" align="right">';
echo '<input type="submit" value="Войти через ЕСИА">';
echo '</form>';
echo '<Br/>';
echo '</body>';
echo '</html>';
?>
//*****************файл firstR.php (запрос на получение авторизационного кода)***************

<?php
require ("funcfunc20171012.php");

////////////////
//$scope = 'openid';
$scope = 'openid fullname usr_org email';
//$scope = 'fullname';
//$scope = 'usr_org';
$timestamp = date('Y.m.d H:i:s O');
$clientId = "ClientIdO01";
$state = generate_uuid();

$data = $scope.$timestamp.$clientId.$state;

$msgFile = "C:\\Apache22\\tempF\\".generateFileName();
$fp = fopen($msgFile, "w");
fwrite($fp, $data);
fclose($fp);

$pathPrive = "file://".realpath('../../cert/cert.key');
$pathOpen = "file://".realpath('../../cert/cert.crt');
$signFile = "C:\\Apache22\\tempF\\".generateFileName();

// encrypt it
$Zashifrovano = False;
/**/ if (openssl_pkcs7_sign($msgFile, $signFile, $pathOpen,

array($pathPrive, "ertdf"), //qwerty123!
array("To" => "sergey@mirossa.ru", // keyed syntax
"From: HQ <sergey@mirossa.ru>"// indexed syntax
"Subject" => "Theme"), PKCS7_BINARY | PKCS7_DETACHED
)) {

$Zashifrovano = True;
}
if ($Zashifrovano === false) {
return false;
}
$signed = file_get_contents($signFile);
unlink($signFile);
unlink($msgFile);
$signed = explode("\n\n", $signed);

$sign = str_replace("\n", "", $signed[3]);

///////////////

header("Location: https://esia-portal1.test.gosuslugi.ru/aas/oauth2/ac?timestamp=".urlencode($timestamp)."&client_id=$clientId&client_secret=".urlencode($sign)."&redirect_uri=".urlencode("https://myDomain.ru/redirectpage.php")."&scope=$scope&response_type=code&state=$state&access_type=online");

?>
//*****************файл funcfunc20171012.php (общие процедуры функции)***************

<?php
function generate_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
function generateFileName() {
return sprintf( '%04x%04x-%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff )
);
}

function urlsafe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}

function base64UrlSafeDecode($string) //encode наоборот
{
$base64 = strtr($string, '-', '+');
$base64 = strtr($base64, '_', '/');
//? есть ещё подстановка знаков "=" в конец
return base64_decode($base64);
}
?>
//*****************файл redirectpage.php (Получение всей нужной информации)***************

<?php
require ("funcfunc20171012.php");
$Domain = 'myDomain.ru';

$codeAuth = '';
if (isset($_GET['code'])) {
$codeAuth = $_GET['code'];
}
$state = ''; //нужно сравнивать отправленный state с полученным.
$stateOld = '';
if (isset($_GET['state'])) {
$stateOld = $_GET['state'];
}

if ($codeAuth === '' or $stateOld === '') {
header("Location: https://myDomain.ru/");
return;
}
/* получение Токена .(+сохранение ...)*/

//https://esia-portal1.test.gosuslugi.ru/aas/oauth2/te

/* $QUERY_STRING = $_SERVER['QUERY_STRING']; //получаем get параметры
$request_params = "";
parse_str($QUERY_STRING, $request_params); //получаем массив(ключ-знач) из параметров

$codeAuth = $request_params['code'];*/

//************************************************ЗАПРОС НА все нужные СКОУПы *****************************************

//Post-запрос

$serv_addr = 'esia-portal1.test.gosuslugi.ru';
$serv_port = 443;
$serv_page = 'aas/oauth2/te';
$timelimit = 20;
$errstr = '';
$errno = '';

//$scope = 'openid';
$scope = 'openid fullname usr_org email';
//$scope = 'fullname';
//$scope = 'usr_org';
//$scope = 'snils';
$timestamp = date('Y.m.d H:i:s O');
$clientId = "ClientIdO01";
$state = generate_uuid();
$data = $scope.$timestamp.$clientId.$state;

$msgFile = "C:\\Apache22\\tempF\\".generateFileName();

$fp = fopen($msgFile, "w");
fwrite($fp, $data);
fclose($fp);


$pathPrive = "file://".realpath('../../cert/cert.key');
$pathOpen = "file://".realpath('../../cert/cert.crt');
$signFile = "C:\\Apache22\\tempF\\".generateFileName();

$Zashifrovano = False;
if (openssl_pkcs7_sign($msgFile, $signFile, $pathOpen,

array($pathPrive, "ertdf"), //qwerty123!
array("To" => "sergey@mirossa.ru", // keyed syntax
"From: HQ <sergey@mirossa.ru>", // indexed syntax
"Subject" => "Theme"), PKCS7_BINARY | PKCS7_DETACHED
)) {
$Zashifrovano = True;
}

if ($Zashifrovano === false) {
return false;
}
$signed = file_get_contents($signFile);
unlink($signFile);
unlink($msgFile);
$signed = explode("\n\n", $signed);

$sign = str_replace("\n", "", $signed[3]);

// Передаваемые POST переменные в формате: название переменной => значение
$post_data = array('client_id' => $clientId,
'code' => $codeAuth,
'grant_type' => 'authorization_code',
'client_secret' => $sign,
'state' => $state,
'redirect_uri' => "https://myDomain.ru/redirectpage.php",
'scope' => $scope,
'timestamp' => $timestamp,
'token_type' => 'Bearer');
// Генерируем строку с POST запросом
$post_data_text = '';
foreach ($post_data AS $key => $val)
$post_data_text .= $key.'='.urlencode($val).'&'; //может быть здесь не нужно URL-кодировать

// Убираем последний символ & из строки $post_data_text
$post_data_text = substr($post_data_text, 0, -1);


$headers = array('POST /'.$serv_page.' HTTP/1.1',
'Host: '.$serv_addr,
'Content-type: application/x-www-form-urlencoded',
'Content-length: '.strlen($post_data_text),
'Accept: */*',
//'Accept-Encoding: gzip, deflate',
'');

// Создание строки заголовков
$headers_txt = '';
foreach ($headers AS $val)
{
$headers_txt .= $val.chr(13).chr(10);
}

// Создание общего запроса (заголовки и тело запроса)
// chr(13).chr(10) равно "\r\n" - перевод каретки
$request_body = $headers_txt.$post_data_text.chr(13).chr(10).chr(13).chr(10);

// Открытие сокета
$sp = fsockopen('ssl://'.$serv_addr, $serv_port, $errno, $errstr, $timelimit);

if (!$sp)
exit('Error: '.$errstr.' #'.$errno);

fwrite($sp, $request_body);
$timelimit2 = 57; //есть настройка в php.ini max_execution_time

$server_answer = '';
$server_header = '';
$start = microtime(true);
$header_flag = 1;
while(!feof($sp) && (microtime(true) - $start) < $timelimit2)
{$chunksize = '';
if ($header_flag == 1)
{
$content = fgets($sp, 4096);

if ($content === chr(13).chr(10))
$header_flag = 0;
else
$server_header .= $content;
}
else
{
do {
$chunksize .= fread($sp, 1);
} while (strpos($chunksize, "\r\n") === false);
$chunksize = (int)base_convert($chunksize, 16, 10);

if ($chunksize === 0) {
fread($sp, 2); // read trailing "\r\n"
break;
} else {
$data = '';
$datalen = 0;
while ($datalen < $chunksize + 2) {
$data .= fread($sp, $chunksize - $datalen + 2);
$datalen = strlen($data);
}

$server_answer .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
}

}
}
fclose($sp);
// проверка полученного ответа
//..

//пример заголовков ответа $server_header
/*
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Dec 2017 13:22:16 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
com.coradiant.appvis: nulltid=1514467336504;4696328222695907644
X-XSS-Protection: 1; mode=block;
X-Content-Type-Options: nosniff
*/
//echo $server_answer;
// {"state":"cdaeec62-a717-43f7-95ce-f34916644762","token_type":"Bearer","expires_in":3600,
"refresh_token":"18e55fac-69b6-474c-a613-d0aac20a79e0","id_token":"eyJhbGciOiJSUzI1NiIsInN
idCI6ImlkIiwidHlwIjoiSldUIiwidmVyIjowfQ.eyJhdXRoX3RpbWUiOjE1MTQ0NjczMzU5MjksImV4cCI6MTUxN
DQ3ODEzNiwic3ViIjoxMDAwMjk5Njg2LCJhdWQiOiJDbGllbnRJZE8wMSIsImlzcyI6Imh0dHA6XC9cL2VzaWEuZ2
9zdXNsdWdpLnJ1XC8iLCJuYmYiOjE1MTQ0NjczMzYsInVybjplc2lhOnNpZCI6ImQxNGQzY2ExOGFlNTVkYWUzODR
jOTljYTQ3MmZhODkyZjNmMmVjODEyNWRlZGE2ZjdlNzNkOWZkZjRlMTVjMWEiLCJ1cm46ZXNpYTpzYmoiOnsidXJu
OmVzaWE6c2JqOm5hbSI6Ik9JRC4xMDAwMjk5Njg2IiwidXJuOmVzaWE6c2JqOm9pZCI6MTAwMDI5OTY4NiwidXJu
OmVzaWE6c2JqOnR5cCI6IlAiLCJ1cm46ZXNpYTpzYmo6aXNfdHJ1Ijp0cnVlfSwidXJuOmVzaWE6YW1kIjoiUFd
EIiwiaWF0IjoxNTE0NDY3MzM2LCJhbXIiOiJQV0QifQ.cE8GFbwjrbEn6xEwDngL5b5pJ_Rw3hDAA7LqShYAL6
TG18ps_35xfFhPizpRt8aauMx7C4OsrrnqdQFnyhOTBt-JwqwimJcfqRFWz0Fv4VCmjIvGksgde7LOE18PfkaOq
MQgMzM-AFpJ1AKSA51Srk6_5BD3YEh9cvsTb5ZfxCtTdtQeIV3OmBy9ymclFd_0AM9KBHm6A6YYG748hEAH1Sv-
Eb2WyG-kIuY-V8eFNk_eMwj9e2prn2LX8Lq6DiUcAwRWPe-AZE4As1hp-HlfJMO_AFz2FHW6MbIGCIdfhR0zMp9_
nVUcVOK94fqddY4xB_peGh9GJI1Eg89pKS1Ygg","access_token":"eyJhbGciOiJSUzI1NiIsInNidCI6ImFj
Y2VzcyIsInR5cCI6IkpXVCIsInZlciI6MX0.eyJleHAiOjE1MTQ0NzA5MzYsInNjb3BlIjoidXNyX29yZz9vaWQ9M
TAwMDI5OTY4NiBvcGVuaWQgZnVsbG5hbWU_b2lkPTEwMDAyOTk2ODYiLCJpc3MiOiJodHRwOlwvXC9lc2lhLmdvc3
VzbHVnaS5ydVwvIiwibmJmIjoxNTE0NDY3MzM2LCJ1cm46ZXNpYTpzaWQiOiJkMTRkM2NhMThhZTU1ZGFlMzg0Yz
k5Y2E0NzJmYTg5MmYzZjJlYzgxMjVkZWRhNmY3ZTczZDlmZGY0ZTE1YzFhIiwidXJuOmVzaWE6c2JqX2lkIjoxMD
AwMjk5Njg2LCJjbGllbnRfaWQiOiJGSVRPMDEiLCJpYXQiOjE1MTQ0NjczMzZ9.KvDuV7MqF9p-JXvPud98_jU0Y
EMaLGdNoE_r0sNr-vzO2SFDrrlq6YCoJRwEmkmajnAjD8jBx_uSLdPGc1ryS_FuO-0csL-Nr-UYIotap_JsNooAy
_7V5Z1iji6JbLHCX5xUvop62pgEtDXs_yTcex7T5Y4cHbtY4M7QVsJfA_DB5Ark3q2L6mVuH3FAYPN7MRWviR8IJ
SXR8dAG4i9CB6BxaWj_XEaUVGNvKzWVoUyKMLhboVXHqUIhORBnRN_-ix1oL8Uv7UvCDXZEZZwdM7G70gDdT3tkS
GbQtHic7q5qoF6jVI716gMjkT721ykV46Wn9DCKT0wuHyqz5eteKw"}

$answerJson = json_decode($server_answer);

$access_token = $answerJson->{"access_token"};

//**********закомментировать н ******************
$PartsOfAnswer = explode('.', $access_token);

$header = base64UrlSafeDecode($PartsOfAnswer[0]);
$payload = base64UrlSafeDecode($PartsOfAnswer[1]);
$signature = $PartsOfAnswer[2];

$payloadJson = json_decode($payload);
$oid = $payloadJson->{"urn:esia:sbj_id"};
$exp = $payloadJson->{"exp"}; //время прекращения действия маркера в секундах с 1 января 1970 г. 00:00:00 GMT
//date("Y-m-d H:i:s O", $exp) вернет 2017-12-28 17:52:14 +0400
$nbf = $payloadJson->{"nbf"}; //время начала действия маркера в секундах с 1 января 1970 г. 00:00:00 GMT

//**********закомментировать кон ******************

//****************************************получение полного имени пользователя ********************************

$serv_addr = 'esia-portal1.test.gosuslugi.ru';
$serv_port = 443;
$serv_page = 'aas/oauth2/te';
$timelimit = 20;
$errstr = '';
$errno = '';

$fp = fsockopen('ssl://'.$serv_addr, $serv_port, $errno, $errstr, $timelimit);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
}
else {
$out = "GET /rs/prns/".$oid." HTTP/1.1\r\n";
$out .= "Host: esia-portal1.test.gosuslugi.ru\r\n";
$out .= "Authorization: Bearer ".$access_token."\r\n";
$out .= "Accept: */*\r\n\r\n";
//$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-3\"\r\n\r\n";
//$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/orgs/Organizations-1\"\r\n\r\n";
fwrite($fp, $out);

$server_answer = '';
$server_header = '';
$start = microtime(true);
$header_flag = 1;

while(!feof($fp) && (microtime(true) - $start) < $timelimit2)
{$chunksize = '';
if ($header_flag == 1)
{
$content = fgets($fp, 4096);

if ($content === chr(13).chr(10))
{$header_flag = 0;
}
else
$server_header .= $content;

}
else
{
do {
$chunksize .= fread($fp, 1);
} while (strpos($chunksize, "\r\n") === false);
$chunksize = (int)base_convert($chunksize, 16, 10);

if ($chunksize === 0) {
fread($fp, 2); // read trailing "\r\n"
break;
} else {
$data = '';
$datalen = 0;
while ($datalen < $chunksize + 2) {
$data .= fread($fp, $chunksize - $datalen + 2);
$datalen = strlen($data);
}

$server_answer .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
}

}
}

fclose($fp);
// проверка полученного ответа

//пример заголовков ответа:
/*
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Dec 2017 13:02:14 GMT
Content-Type: application/json; schema="https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-3"
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/>;rel=parent;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/prns/Persons-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/prmns>;rel=permissions;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/prmns/PersonPermissions-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctx>;rel=context;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/ctx/RegContext-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/events>;rel=events;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/events/AuditEvents-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/reqs>;rel=requests;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/reqs/Requests-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/sec>;rel=sec;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/sec/SecuritySettings-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/addrs>;rel=addresses;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/addrs/Addresses-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/roles>;rel=roles;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/roles/Roles-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts>;rel=contacts;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/ctts/Contacts-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/docs>;rel=documents;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/docs/Documents-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/vhls>;rel=vehicles;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/vhls/Vehicles-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/kids>;rel=kids;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/kids/Kids-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/trmnls>;rel=terminals;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/trmnls/Terminals-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/orgs>;rel=organizations;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/orgs/Organizations-1"
com.coradiant.appvis: nulltid=1514466134701;-810712349028523703
ETag: B2139609D990C4F140CBF352217DB15CF3BFE79C
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
*/
// пример тела ответа:
// {"stateFacts":["EntityRoot"],"eTag":"B2139609D990C4F140CBF352217DB15CF3BFE79C","firstName":"Сергей","lastName":"Иванов",
"middleName":"Петрович","trusted":true,"updatedOn":1511162767,"status":"REGISTERED","verifying":false,"rIdDoc":42587,"containsUpCfmCode":false}


$obj = json_decode($server_answer);
$fn = $obj->{"firstName"};
$ln = $obj->{"lastName"};
$mn = $obj->{"middleName"};
$trust = $obj->{"trusted"};

} //end while

//****************************************получение email пользователя (1. доступ к перечню контактов "ctts" 2. получение контактов)********************************

$serv_addr = 'esia-portal1.test.gosuslugi.ru';
$serv_port = 443;
$serv_page = 'aas/oauth2/te';
$timelimit = 20;
$errstr = '';
$errno = '';
$fp = fsockopen('ssl://'.$serv_addr, $serv_port, $errno, $errstr, $timelimit);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
}
else {
$out = "GET /rs/prns/$oid/ctts HTTP/1.1\r\n";
$out .= "Host: esia-portal1.test.gosuslugi.ru\r\n";
$out .= "Authorization: Bearer ".$access_token."\r\n";
$out .= "Accept: */*\r\n\r\n";
//$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-3\"\r\n\r\n";
//$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/orgs/Organizations-1\"\r\n\r\n";
fwrite($fp, $out);

$server_answer = '';
$server_header = '';
$start = microtime(true);
$header_flag = 1;

while(!feof($fp) && (microtime(true) - $start) < $timelimit2)
{$chunksize = '';
if ($header_flag == 1)
{
$content = fgets($fp, 4096);

if ($content === chr(13).chr(10))
{$header_flag = 0;

}
else
$server_header .= $content;

}
else
{
do {
$chunksize .= fread($fp, 1);
} while (strpos($chunksize, "\r\n") === false);
$chunksize = (int)base_convert($chunksize, 16, 10);

if ($chunksize === 0) {
fread($fp, 2); // read trailing "\r\n"
break;
} else {
$data = '';
$datalen = 0;
while ($datalen < $chunksize + 2) {
$data .= fread($fp, $chunksize - $datalen + 2);
$datalen = strlen($data);
}

$server_answer .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
}


}
}

// проверка полученного ответа
//..

//Пример ответа:
/*
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Dec 2017 15:21:04 GMT
Content-Type: application/json; schema="https://esia-portal1.test.gosuslugi.ru/rs/model/ctts/Contacts-1"
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/>;rel=parent;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/>;rel=create
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/confirm>;rel=confirmCtt
com.coradiant.appvis: nulltid=1514474464330;-8913419786195199503
ETag: 4A75519B5B4A1D3532C5AB387F673141347B9569
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
//тело ответа
{"stateFacts":["hasSize"],"size":1,"eTag":"4A75519B5B4A1D3532C5AB387F673141347B9569","elements":["https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788"]}
*/

$struct = json_decode($server_answer, true);
$elements = $struct["elements"]; //контакты

$Contact = '';
$path = '';
if (count($elements) > 0):
//пока беру только первый контакт
$Contact = $elements[0]; // https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788
$n = strpos($Contact, '/', 8);
if($n !== false):
$path = substr($Contact, $n); // /rs/prns/1000299686/ctts/14216788
endif;
endif;


if ($path !== ''):
$out = "GET $path HTTP/1.1\r\n";
$out .= "Host: esia-portal1.test.gosuslugi.ru\r\n";
$out .= "Authorization: Bearer ".$access_token."\r\n";
$out .= "Accept: */*\r\n\r\n";
fwrite($fp, $out);
$server_answer = '';
$server_header = '';
$start = microtime(true);
$header_flag = 1;

while(!feof($fp) && (microtime(true) - $start) < $timelimit2)
{$chunksize = '';
if ($header_flag == 1)
{
$content = fgets($fp, 4096);

if ($content === chr(13).chr(10))
{$header_flag = 0;
}
else
$server_header .= $content;

}
else
{
do {
$chunksize .= fread($fp, 1);
} while (strpos($chunksize, "\r\n") === false);
$chunksize = (int)base_convert($chunksize, 16, 10);

if ($chunksize === 0) {
fread($fp, 2); // read trailing "\r\n"
break;
} else {
$data = '';
$datalen = 0;
while ($datalen < $chunksize + 2) {
$data .= fread($fp, $chunksize - $datalen + 2);
$datalen = strlen($data);
}
$server_answer .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
}
}
}

endif;


fclose($fp);
//Примет ответа:
/*
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Dec 2017 15:58:34 GMT
Content-Type: application/json; schema="https://esia-portal1.test.gosuslugi.ru/rs/model/ctt/Contact-1"
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/>;rel=parent;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/ctts/Contacts-1"
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/>;rel=alt
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/>;rel=del
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/>;rel=alt
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/cfm>;rel=confirm
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/rfrCode>;rel=refreshCode
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/ctts/14216788/alt-cancel>;rel=alt-cancel
com.coradiant.appvis: nulltid=1514476714046;1454622467803226386
ETag: 0DEC08F5FC5B4BA17097FCC47EB07E91FC14A8EE
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
//тело ответа
{"stateFacts":["Identifiable"],"eTag":"0DEC08F5FC5B4BA17097FCC47EB07E91FC14A8EE","id":14216788,"type":"EML","vrfStu":"VERIFIED","value":"EsiaTest008@yandex.ru"}
*/
} //end while

//*************************scope openid fullname usr_org email****************************************************************************************
//ПОЛУЧЕНИЕ ИНФОРМАЦИИ ПО ОРГАНИЗАЦИЯМ , В КОТОРЫХ СОСТОИТ ПОЛЬЗОВАТЕЛЬ

$serv_addr = 'esia-portal1.test.gosuslugi.ru';
$serv_port = 443;
$serv_page = 'aas/oauth2/te';
$timelimit = 20;
$errstr = '';
$errno = '';

$fp = fsockopen('ssl://'.$serv_addr, $serv_port, $errno, $errstr, $timelimit);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
}
else {
$out = "GET /rs/prns/".$oid."/roles HTTP/1.1\r\n";
$out .= "Host: esia-portal1.test.gosuslugi.ru\r\n";
$out .= "Authorization: Bearer ".$access_token."\r\n";
$out .= "Accept: */*\r\n";
$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-3\"\r\n\r\n";
//$out .= "Accept: application/json; schema=\"https://esia-portal1.test.gosuslugi.ru/rs/model/orgs/Organizations-1\"\r\n\r\n";
fwrite($fp, $out);
$server_answer = '';
$server_header = '';
$start = microtime(true);
$header_flag = 1;
while(!feof($fp) && (microtime(true) - $start) < $timelimit2)
{$chunksize = '';
if ($header_flag == 1)
{
$content = fgets($fp, 4096);

if ($content === chr(13).chr(10))
{$header_flag = 0;

}
else
$server_header .= $content;

}
else
{
do {
$chunksize .= fread($fp, 1);
} while (strpos($chunksize, "\r\n") === false);
$chunksize = (int)base_convert($chunksize, 16, 10);

if ($chunksize === 0) {
fread($fp, 2); // read trailing "\r\n"
break;
} else {
$data = '';
$datalen = 0;
while ($datalen < $chunksize + 2) {
$data .= fread($fp, $chunksize - $datalen + 2);
$datalen = strlen($data);
}
$server_answer .= substr($data, 0, -2); // -2 to remove the "\r\n" before the next chunk
}
}
}
fclose($fp);
// проверка полученного ответа
//..

//пример заголовка ответа $server_header
/*
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 28 Dec 2017 13:11:49 GMT
Content-Type: application/json; schema="https://esia-portal1.test.gosuslugi.ru/rs/model/roles/Roles-1"
Transfer-Encoding: chunked
Connection: keep-alive
Location: https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/roles
Link: <https://esia-portal1.test.gosuslugi.ru:443/rs/prns/1000299686/>;rel=parent;schema="https://esia-portal1.test.gosuslugi.ru/rs/model/prn/Person-1"
com.coradiant.appvis: nulltid=1514466709687;-2980672566055308293
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0
*/
//пример тела ответа $server_answer
/*
//{"stateFacts":["hasSize"],"size":2,"elements":[{"stateFacts":["Identifiable"],"oid":1000299543,"fullName":"Название организации","ogrn":"1234567890123","chief":false},{"stateFacts":["Identifiable"],"oid":1000346115,"fullName":"Название организации 2","ogrn":"0001230000051","chief":false}]}
*/

$struct = json_decode($server_answer, true);
$elements = $struct["elements"]; //организации ,в которые входит пользователь

$FullNameOrg = '';
$OgrnOrg = '';
if (count($elements) > 0):
//пока беру только первую организацию
$element = $elements[0];
$FullNameOrg = $element['fullName'];
$OgrnOrg = $element['ogrn'];
endif;
//проверка на = '' наверное не нужны
}
//********дальше после проверки полученных данных что-нибудь делаем*******************************************
//...
?>