Skip to content

Commit

Permalink
context user support
Browse files Browse the repository at this point in the history
  • Loading branch information
bessudnov committed Nov 19, 2023
1 parent e6c81c3 commit 016c0c8
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 5 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,17 @@ $accessToken = $apiClient->getOAuthClient()->getAccessTokenByCode($_GET['code'])

Пример авторизации можно посмотреть в файле examples/get_token.php

### Авторизация с правами конкретного пользователя аккаунта
Начиная с версии 1.4.0 появилась возможность авторизоваться с правами конкретного пользователя, если токен был выпущен администратором аккаунта.

Для авторизации под пользователем аккаунта - необходимо задать ID пользователя у объекта типа ```\AmoCRM\Client\AmoCRMApiClient```.

```php
$apiClient = new \AmoCRM\Client\AmoCRMApiClient($clientId, $clientSecret, $redirectUri);
$apiClient->setContextUserId(123);
```


## Подход к работе с библиотекой

В библиотеке используется сервисный подход. Для каждой сущности имеется сервис.
Expand Down
35 changes: 35 additions & 0 deletions examples/user_context_actions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

use AmoCRM\Exceptions\AmoCRMApiException;
use League\OAuth2\Client\Token\AccessTokenInterface;

include_once __DIR__ . '/bootstrap.php';

$accessToken = getToken();

$apiClient->setAccessToken($accessToken)
->setAccountBaseDomain($accessToken->getValues()['baseDomain'])
->onAccessTokenRefresh(
function (AccessTokenInterface $accessToken, string $baseDomain) {
saveToken(
[
'accessToken' => $accessToken->getToken(),
'refreshToken' => $accessToken->getRefreshToken(),
'expires' => $accessToken->getExpires(),
'baseDomain' => $baseDomain,
]
);
}
);

$contextUserId = 123;
$apiClient->setContextUserId($contextUserId);

//Получим свойства аккаунта и сравним юезра
try {
$account = $apiClient->account()->getCurrent();

echo 'Текущий юзер, тот кого вы передали? - ' . ($account->getCurrentUserId() === $contextUserId ? 'да' : 'нет');
} catch (AmoCRMApiException $e) {
printError($e);
}
25 changes: 24 additions & 1 deletion src/AmoCRM/Client/AmoCRMApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ class AmoCRMApiClient
*/
private $accessTokenRefreshCallback;

/**
* @var null|int
*/
private $contextUserId;

/**
* AmoCRMApiClient constructor.
* @param string $clientId
Expand Down Expand Up @@ -103,6 +108,24 @@ public function getAccessToken(): ?AccessToken
return $this->accessToken;
}

public function getContextUserId(): ?int
{
return $this->contextUserId;
}

/**
* Для админских токеном можно задать пользователя аккаунта, в контексте которого будет сделан запрос
* @param int|null $contextUserId
*
* @return $this
*/
public function setContextUserId(?int $contextUserId): AmoCRMApiClient
{
$this->contextUserId = $contextUserId;

return $this;
}

/**
* Устанавливаем базовый домен аккаунта в amoCRM, который будет использован при запросах
* @param string $domain
Expand Down Expand Up @@ -162,7 +185,7 @@ function (AccessToken $accessToken, string $baseAccountDomain) use ($oAuthClient
}
);

return new AmoCRMApiRequest($this->accessToken, $oAuthClient);
return new AmoCRMApiRequest($this->getAccessToken(), $oAuthClient, $this->getContextUserId());
}

/**
Expand Down
26 changes: 22 additions & 4 deletions src/AmoCRM/Client/AmoCRMApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class AmoCRMApiRequest
public const CONNECT_TIMEOUT = 5;
public const REQUEST_TIMEOUT = 20;
//TODO Do not forget to change this on each release
public const LIBRARY_VERSION = '1.1.0';
public const LIBRARY_VERSION = '1.4.0';
public const USER_AGENT = 'amoCRM-API-Library/' . self::LIBRARY_VERSION;

public const SUCCESS_STATUSES = [
Expand Down Expand Up @@ -101,16 +101,25 @@ class AmoCRMApiRequest
/** @var string|null */
private $requestDomain = null;

/** @var int|null */
private $contextUserId = null;

/**
* AmoCRMApiRequest constructor.
*
* @param AccessTokenInterface $accessToken
* @param AmoCRMOAuth $oAuthClient
* @param int|null $contextUserId
*/
public function __construct(AccessTokenInterface $accessToken, AmoCRMOAuth $oAuthClient)
{
public function __construct(
AccessTokenInterface $accessToken,
AmoCRMOAuth $oAuthClient,
?int $contextUserId
) {
$this->accessToken = $accessToken;
$this->oAuthClient = $oAuthClient;
$this->httpClient = $oAuthClient->getHttpClient();
$this->contextUserId = $contextUserId;
}

/**
Expand All @@ -129,11 +138,15 @@ private function refreshAccessToken()
* @param array $queryParams
* @param array $headers
* @param bool $needToRefresh
* @param bool $isFullPath
*
* @return array
* @throws AmoCRMApiConnectExceptionException
* @throws AmoCRMApiException
* @throws AmoCRMoAuthApiException
* @throws AmoCRMApiHttpClientException
* @throws AmoCRMApiNoContentException
* @throws AmoCRMApiTooManyRedirectsException
* @throws AmoCRMoAuthApiException
*/
public function post(
string $method,
Expand Down Expand Up @@ -626,6 +639,10 @@ private function getBaseHeaders()
$headers['X-Library-Version'] = self::LIBRARY_VERSION;
$headers['X-Client-UUID'] = $this->oAuthClient->getOAuthProvider()->getClientId();

if (!is_null($this->contextUserId)) {
$headers['X-Context-User-ID'] = $this->contextUserId;
}

return $headers;
}

Expand All @@ -635,6 +652,7 @@ private function getBaseHeaders()
public function getLastRequestInfo(): array
{
return [
'context_user_id' => $this->contextUserId,
'last_http_method' => $this->lastHttpMethod,
'last_method' => $this->lastMethod,
'last_body' => $this->lastBody,
Expand Down

0 comments on commit 016c0c8

Please sign in to comment.