lustmored / oauth2-lockme
LockMe OAuth2 provider
Requires
- php: >=8.2.0
- ext-json: *
- guzzlehttp/guzzle: ^7.8 || ^8.0
- league/oauth2-client: ^2.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.70
- phpstan/phpstan: ^2.1
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This package provides LockMe OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
Recommendation: For a more comprehensive integration with LockMe, we recommend using the lustmored/lockme-sdk package, which provides a full-featured SDK for the LockMe API.
Installation
To install, use Composer:
composer require lustmored/oauth2-lockme
Requirements
PHP 8.2 or newer is required.
This package depends on:
- league/oauth2-client (^2.2)
- guzzlehttp/guzzle (^7.8 || ^8.0)
- PHP ext-json
Usage
Authorization Code Flow
use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use Lockme\OAuth2\Client\Provider\Lockme; // Initialize the provider $provider = new Lockme([ 'clientId' => '{lockme-client-id}', 'clientSecret' => '{lockme-client-secret}', 'redirectUri' => 'https://example.com/callback-url', ]); // If we don't have an authorization code then get one if (!isset($_GET['code'])) { // Get authorization URL $authorizationUrl = $provider->getAuthorizationUrl([ 'scope' => 'rooms_manage' // Optional: specify scopes ]); // Get state and store it to the session $_SESSION['oauth2state'] = $provider->getState(); // Redirect user to authorization URL header('Location: ' . $authorizationUrl); exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state'); } else { try { // Try to get an access token using the authorization code grant $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // We have an access token, which we may use in authenticated // requests against the service provider's API. echo 'Access Token: ' . $accessToken->getToken() . "<br>"; echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>"; echo 'Expires: ' . $accessToken->getExpires() . "<br>"; echo 'Already expired? ' . ($accessToken->hasExpired() ? 'Yes' : 'No') . "<br>"; // Using the access token, get the user's details $resourceOwner = $provider->getResourceOwner($accessToken); // Show user ID var_dump($resourceOwner->getId()); // Show all user data var_dump($resourceOwner->toArray()); } catch (IdentityProviderException $e) { // Failed to get the access token or user details. exit($e->getMessage()); } }
Refreshing a Token
$refreshToken = $accessToken->getRefreshToken(); // Verify token has expired if ($accessToken->hasExpired()) { $accessToken = $provider->getAccessToken('refresh_token', [ 'refresh_token' => $refreshToken ]); }
Making Authenticated API Requests
This package includes a helper method executeRequest() to easily make authenticated API requests:
use Lockme\OAuth2\Client\Provider\Exception\ConflictException; use Lockme\OAuth2\Client\Provider\Exception\LockmeIdentityProviderException; use Lockme\OAuth2\Client\Provider\Exception\NotFoundException; try { // Make an authenticated API request $response = $provider->executeRequest( 'GET', // HTTP method '/endpoint', // API endpoint $accessToken, // Access token ['param' => 'value'] // Optional request body (will be JSON encoded) ); // Process the response var_dump($response); } catch (NotFoundException $e) { // The room, booking, ... does not exist } catch (ConflictException $e) { // The request clashes with the current state, e.g. the hour was booked meanwhile } catch (LockmeIdentityProviderException $e) { // Any other refusal; getCode() is the HTTP status, getResponseBody() the raw body echo $e->getMessage(); }
Exceptions
Every refusal is thrown as a subclass of Lockme\OAuth2\Client\Provider\Exception\LockmeIdentityProviderException
(itself a League\OAuth2\Client\Provider\Exception\IdentityProviderException), chosen by the HTTP status
of the response. The message carries the API's description of the error and the code the HTTP status.
| Status | Exception |
|---|---|
| 400 | BadRequestException |
| 401 | UnauthorizedException |
| 403 | ForbiddenException |
| 404 | NotFoundException |
| 409 | ConflictException |
| 422 | UnprocessableEntityException |
| other 4xx | ClientErrorException (base of all the above) |
| 5xx | ServerErrorException |
2xx with an error field |
OAuthErrorException |
Up to API version 2.6 the API reports every refusal with status 500, so ServerErrorException is all you get
there. Since version 2.7 (the default) the status tells what went wrong, see the
API documentation.
LockMe SDK and API Documentation
LockMe SDK
For more advanced integration with LockMe, we recommend using the lustmored/lockme-sdk package. This SDK provides a more comprehensive set of features and utilities specifically designed for the LockMe API.
To install the LockMe SDK, use Composer:
composer require lustmored/lockme-sdk
For detailed documentation and usage examples, please refer to the SDK repository.
API Documentation
For complete API specifications and endpoint documentation, please refer to the official LockMe API Documentation.
Configuring the Provider
The provider constructor accepts the following options:
$provider = new Lockme([ 'clientId' => '{lockme-client-id}', // Required 'clientSecret' => '{lockme-client-secret}', // Required 'redirectUri' => 'https://example.com/', // Required 'apiDomain' => 'https://api.lock.me', // Optional: custom API domain 'version' => 'v2.7', // Optional: API version, defaults to v2.7 'ignoreSslErrors' => false // Optional: ignore SSL errors ]);
The second constructor argument takes the collaborators of League\OAuth2\Client\Provider\AbstractProvider,
e.g. ['httpClient' => $client] to supply your own HTTP client.
Development
composer check # php-cs-fixer (dry run) and phpstan
composer cs:fix # apply the code style
License
This package is released under the GPL-3.0-or-later License. See the bundled LICENSE file for details.