массовая регистрация graphisoft id

Встал вопрос получить сотрудникам Graphisoft id, но никакого функционала у производителя нет, чтобы сделать это массово. Печаль.

Итак, проанализировав механизм регистрации и добавления пользователя в состав компании получаем следующий алгоритм:

  1. регистрация пользователя на сайте graphisoft.com
  2. подтверждение регистрации в посте пользователя
  3. авторизация на сайте graphisoft.com под административной учетной записью
  4. отправка приглашения пользователю
  5. авторизация на сайте graphisoft.com под пользовательской учетной записью
  6. подтверждение приглашения

как родилось решение описано тут:
1 часть, «как нельзя относиться к корпоративным клиентам»
2 часть, «анализ, получение исходных данных»
3 часть, «кропотливая работа и долгожданный успех»

получилось неплохо, полностью автоматизированная система, работает следующим образом:
при появлении нового сотрудника создается для него graphisoft id, добавляется в состав компании и на почту высылаются данные с логином и паролем, а так же инструкция по использованию последних;
после увольнения сотрудника или ухода в декрет — graphisoft id исключается из списка сотрудников компании.

ниже сам код регистрации одно пользователя, как сделать это массово — я думаю разберетесь

<?php

// данные регистрируемого сотрудника
$fname = 'Иван';
$sname = 'Петров';
$email = 'user@domain.ru';
$pasword = 'koo0ovo5Kamu';

// данные администратора компании
$admin_login = 'admin@domain.ru';
$admin_password = 'P@5$w0rD';

$header = '';

function get_url($url, $method, $ctype, $referer, $data) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
	if ($data!=='') {
		if ($ctype == 1) {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		} else if ($ctype == 2) {
			curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
		} else if ($ctype == 3) {
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
			curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
		}
	}
	curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
	$headers = array();
	$headers[] = 'Connection: keep-alive';
	$headers[] = 'Sec-Ch-Ua: \" Not;A Brand\";v=\"99\", \"Opera\";v=\"79\", \"Chromium\";v=\"93\"';
	$headers[] = 'Dnt: 1';
	$headers[] = 'Sec-Ch-Ua-Mobile: ?0';
	$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 OPR/79.0.4143.22';
	if ($ctype == 1) {
		$headers[] = 'Content-Type: application/json; charset=UTF-8';
	} else {
		$headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
	}
	$headers[] = 'Accept: application/json, text/javascript, */*; q=0.01';
	$headers[] = 'X-Requested-With: XMLHttpRequest';
	$headers[] = 'Sec-Ch-Ua-Platform: \"Windows\"';
	$headers[] = 'Sec-Fetch-Site: same-origin';
	$headers[] = 'Sec-Fetch-Mode: cors';
	$headers[] = 'Sec-Fetch-Dest: empty';
	$headers[] = 'Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7';
	$headers[] = 'Origin: '.$referer;
	$headers[] = 'Referer: '.$referer;
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
	curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
	$response = curl_exec($ch);
	global $header;
	$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
	$header = substr($response, 0, $header_size);
	return $response;
	if (curl_errno($ch)) {
		echo 'Error:' . curl_error($ch);
	}
	curl_close($ch);
}

// удаляем старые куки
if (file_exists(dirname(__FILE__).'/cookie.txt')) {
   unlink(dirname(__FILE__).'/cookie.txt');
}		
// заходим на главную
get_url('https://graphisoft.com/ru','GET',1,'','');
// переходим на форму пользователя
get_url('https://graphisoftid.graphisoft.com/Account/ServiceLogin?Application=GRAPHISOFT&ReturnUrl=https://graphisoft.com/ru','GET',1,'https://graphisoftid.graphisoft.com/','');
// переходим на форму регистрации
get_url('https://graphisoftid.graphisoft.com/#/register/3/https%3a%2f%2fgraphisoft.com%2fru','GET',1,'https://graphisoftid.graphisoft.com/','');

//проверяем e-mail
$check_mail = get_url('https://graphisoftid.graphisoft.com/api/user/CheckEmail/','PUT',2,'https://graphisoftid.graphisoft.com/',array("EmailAddress" => $email));
if ($check_mail == 'true') {
	$data = array('applicationName' => null,
				  'customDataObject' => null,
				  'redirectUrl' => null,
				  'emailHintLocalizationKey' => null,
				  'firstName' => $fname,
				  'lastName' => $sname,
				  'isValidated' => true,
				  'email' => $email,
				  'password' => $pasword,
				  'confirmPassword' => $pasword,
				  'isPrivacyPolicyAccepted' => true,
				  'companyName' => 'ООО "Рога и Копыта"',
				  'countryId' => 186,
				  'federated' => false,
				  'callbackUrl' => 'https://graphisoft.com/ru',
				  'isDirty' => true,
				  'errors' => array());

	//echo json_encode($data)."\n";

	$ecoded_json = get_url('https://graphisoftid.graphisoft.com/api/user/CreateUser','POST',1,'https://graphisoftid.graphisoft.com/',$data);

	$jsonObj = json_decode($ecoded_json);

	if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
	   echo "у меня не получилось отправить регистрационную форму с данными...  извините\n";
	} else {
		// удаляем старые куки
		unlink(dirname(__FILE__).'/cookie.txt');
		get_url($jsonObj->{'VerificationURL'}.$jsonObj->{'VerificationCode'},'GET',1,'','');
		$gsid_url = get_url('https://graphisoftid.graphisoft.com/api/user/VerifyUser','PUT',2,'https://graphisoftid.graphisoft.com/',array("code" => $jsonObj->{'VerificationCode'}));
		$parts = parse_url($gsid_url);
		parse_str($parts['query'], $query);
		$user_gsid = $query['gsid'];
		if ($user_gsid !== '') {
			echo "пользователь ".$email." успешно зарегистрирован (Graphisoft sid: ".$user_gsid.")\n";
			// удаляем старые куки
			unlink(dirname(__FILE__).'/cookie.txt');
			// заходим на главную
			get_url('https://graphisoft.com/ru','GET',1,'','');
			get_url('https://graphisoftid.graphisoft.com/','GET',1,'','');
			// авторизуемся под пользователем
			$data = array('email' => $admin_login,
						  'errors' => array(),
						  'isDirty' => true,
						  'isNullo' => false,
						  'password' => $admin_password);			
			$json_response = get_url('https://graphisoftid.graphisoft.com/api/Authenticate/Login','POST',1,'https://graphisoftid.graphisoft.com/',$data);
			$obj = json_decode($json_response);
			$companyGsId = $obj->{'Company'}->{'GsId'};
			// Загружаем список подключенных пользователей
			foreach ($obj->{'Company'}->{'CompanyUsers'} as $user) {
				$users_list[] = array("FirstName" => $user->{'FirstName'},"LastName" => $user->{'LastName'},"EmailAddress" => $user->{'EmailAddress'},"GsId" => $user->{'GsId'});
			}


			$data = array('companyGsId' => $companyGsId,
						  'email' => $email,
						  'errors' => array(),
						  'isDirty' => true,
						  'requestedGraphisoftUserId' => $user_gsid);
			get_url('https://graphisoftid.graphisoft.com/api/user/SendInvitation','PUT',2,'https://graphisoftid.graphisoft.com/',$data);
			echo "выслано приглашение присоединиться к компании\n";
			// удаляем старые куки
			unlink(dirname(__FILE__).'/cookie.txt');
			// переходим на форму пользователя
			get_url('https://graphisoftid.graphisoft.com/','GET',1,'','');
			// авторизуемся под пользователем
			$data = array('email' => $email,
						  'errors' => array(),
						  'isDirty' => true,
						  'isNullo' => false,
						  'password' => $pasword);			
			$json_response = get_url('https://graphisoftid.graphisoft.com/api/Authenticate/Login','POST',1,'https://graphisoftid.graphisoft.com/',$data);
			$obj = json_decode($json_response);
			$user_gsid = $obj->{'GraphisoftUser'}->{'GsId'};
			if ($user_gsid == '') {
				echo "не смог зайти под пользователем в личный кабинет\n";
			} else {
				$data = array('actionId' => 2,
							  'companyGsId' => $companyGsId,
							  'graphisoftUserGsId' => $user_gsid,
							  'reactionId' => 1);
				get_url('https://graphisoftid.graphisoft.com/api/user/ProcessingPendingRequest','PUT',1,'https://graphisoftid.graphisoft.com/',$data);
				echo "сотрудник подтвердил приглашение\n";
			}
		} else {
			echo "у меня не получилось подтвердить регистрацию...  извините\n";
		}
	}
} else {
	echo "$email уже зарегистрирован в системе\n";
}
// удаляем старые куки
unlink(dirname(__FILE__).'/cookie.txt');
?>
Поделиться
Отправить
Запинить
 932   2021   argicad   graphisoft   php   автоматизация