Skip to content

Commit

Permalink
add refresh access token callback
Browse files Browse the repository at this point in the history
  • Loading branch information
egrigorev committed Apr 25, 2024
1 parent ea4bc87 commit 9c8e482
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
26 changes: 25 additions & 1 deletion src/AmoCRM/Client/AmoCRMApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ class AmoCRMApiClient
*/
private $userAgent;

/**
* @var callable|null
*/
private $refreshAccessTokenCallback;

/**
* AmoCRMApiClient constructor.
*
Expand Down Expand Up @@ -181,6 +186,19 @@ public function onAccessTokenRefresh(callable $callback): self
return $this;
}

/**
* Устанавливаем callback, который будет вызван для обновления AccessToken`a библиотеки
*
* @param callable $callable
* @return $this
*/
public function onRefreshAccessTokenCallback(callable $callable): self
{
$this->refreshAccessTokenCallback = $callable;

return $this;
}

/**
* Метод строит объект для совершения запросов для сервисов сущностей
*
Expand All @@ -206,12 +224,18 @@ function (AccessToken $accessToken, string $baseAccountDomain) use ($oAuthClient
}
);

return new AmoCRMApiRequest(
$request = new AmoCRMApiRequest(
$this->getAccessToken(),
$oAuthClient,
$this->getContextUserId(),
$this->getUserAgent()
);

if ($this->refreshAccessTokenCallback !== null) {
$request->setRefreshAccessTokenCallback($this->refreshAccessTokenCallback);
}

return $request;
}

/**
Expand Down
20 changes: 19 additions & 1 deletion src/AmoCRM/Client/AmoCRMApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ class AmoCRMApiRequest
/** @var string|null */
private $userAgent = null;

/**
* @var callable
*/
private $refreshAccessTokenCallback;

/**
* AmoCRMApiRequest constructor.
*
Expand All @@ -126,6 +131,19 @@ public function __construct(
$this->httpClient = $oAuthClient->getHttpClient();
$this->contextUserId = $contextUserId;
$this->userAgent = $userAgent;
$this->refreshAccessTokenCallback = function () {
return $this->oAuthClient->getAccessTokenByRefreshToken($this->accessToken);
};
}

public function getRefreshAccessTokenCallback(): callable
{
return $this->refreshAccessTokenCallback;
}

public function setRefreshAccessTokenCallback(callable $callback): void
{
$this->refreshAccessTokenCallback = $callback;
}

/**
Expand All @@ -138,7 +156,7 @@ private function refreshAccessToken(): void
throw new AmoCRMoAuthApiException('Can not update LongLivedAccessToken');
}

$newAccessToken = $this->oAuthClient->getAccessTokenByRefreshToken($this->accessToken);
$newAccessToken = $this->getRefreshAccessTokenCallback();
$this->accessToken = $newAccessToken;
}

Expand Down

0 comments on commit 9c8e482

Please sign in to comment.