#Allegro API Authorization
Authorizing with this lib is very easy. So far, lib is supporting only authorization_code grant flow.
- Prepare credentials object
- Create AllegroAuth object
- Redirect to obtain authorization code
- Fetch access token to start using API
- Check if token is expired
- Refresh expired token
- Get access to WebAPI (soap)
First, you should create object AppCredentials, or implement AppCredentialsInterface in your own class.
use Imper86\AllegroRestApiSdk\Model\Credentials\AppCredentials;
$credentials = new AppCredentials(
'clientId',
'clientSecret',
'http://your.redirect.uri',
true //isSandbox
);
AllegroAuth is the only service to handle auth operations.
use Imper86\AllegroRestApiSdk\AllegroAuth;
$authService = new AllegroAuth($credentials);
Optional arguments in AuthService constructor are:
- $logger (Psr\Log\LoggerInterface) - you can put your favourite log service there. If you leave this with null, lib won't log anything by itself
- $httpClient (Psr\Http\Client\ClientInterface) - you can put your favourite HTTP Client there. If you leave this with null, lib will use HTTPlug Guzzle6 Adapter
Use AllegroAuth to create proper URL and redirect.
$url = $authService->createAuthUrl();
header('Location: ' . $url);
After successful authorization, user will be redirected back to your app to your redirect uri with authorization code in query string. Use it to obtain access token.
$tokenBundle = $authService->fetchTokenFromCode($_GET['code']);
AllegroAuth will return object, which implements TokenBundleInterface. It contains your new access and refresh tokens, and allows to easily fetch some commonly used data, such as authorized user's id.
If you keep your $tokenBundle object, you'll be able to check if your access token is still active.
$tokenBundle->getAccessExpirationTime(); //DateTime
$tokenBundle->getAccessToken()->isExpired(); //bool
$tokenBundle->getRefreshExpirationTime(); //DateTime
$tokenBundle->getRefreshToken()->isExpired(); //bool
How to use refresh token to get new TokenBundle:
if ($tokenBundle->getAccessToken()->isExpired()) {
$tokenBundle = $allegroAuth->fetchTokenFromRefresh($tokenBundle->getRefreshToken());
}
Once you have your access token you can also fetch WebAPI session id:
$soapSession = $allegroAuth->fetchSoapSessionId($tokenBundle->getAccessToken())->getSessionHandlePart();