PHP code example of smart-dato / gls-authenticator

1. Go to this page and download the library: Download smart-dato/gls-authenticator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

smart-dato / gls-authenticator example snippets


return [
    // Default environment: 'sandbox' or 'production'
    'environment' => env('GLS_ENVIRONMENT', 'sandbox'),

    // OAuth2 client credentials
    'client_id' => env('GLS_CLIENT_ID'),
    'client_secret' => env('GLS_CLIENT_SECRET'),

    // API endpoints
    'endpoints' => [
        'sandbox' => 'https://api-sandbox.gls-group.net/oauth2/v2',
        'production' => 'https://api.gls-group.net/oauth2/v2',
    ],

    // Default scopes (space-separated)
    'scopes' => env('GLS_SCOPES', ''),

    // Cache configuration
    'cache' => [
        'store' => env('GLS_CACHE_STORE'),
        'prefix' => env('GLS_CACHE_PREFIX', 'gls_auth'),
        'expiration_buffer' => env('GLS_CACHE_EXPIRATION_BUFFER', 300), // 5 minutes
    ],

    // HTTP client settings
    'http' => [
        'timeout' => env('GLS_HTTP_TIMEOUT', 30),
        'retry' => [
            'times' => env('GLS_HTTP_RETRY_TIMES', 3),
            'sleep' => env('GLS_HTTP_RETRY_SLEEP', 100), // milliseconds
        ],
    ],

    // Authentication method: 'basic_auth' or 'body'
    'auth_method' => env('GLS_AUTH_METHOD', 'basic_auth'),
];

use SmartDato\GlsAuthenticator\Facades\GlsAuthenticator;

$token = GlsAuthenticator::getToken();

// Use the token
$authHeader = $token->toAuthorizationHeader(); // "Bearer eyJ..."

$token = GlsAuthenticator::getToken();

echo $token->token;          // The JWT access token
echo $token->tokenType;      // "Bearer"
echo $token->expiresIn;      // 14400 (4 hours in seconds)
echo $token->expiresAt();    // DateTimeInterface
echo $token->isExpired();    // false
echo $token->secondsUntilExpiration(); // 14399

// Each tenant has their own credentials
$tenant = Tenant::current();

$token = GlsAuthenticator::withCredentials(
    $tenant->gls_client_id,
    $tenant->gls_client_secret
)->getToken();

// Use sandbox
$token = GlsAuthenticator::environment('sandbox')->getToken();

// Use production
$token = GlsAuthenticator::environment('production')->getToken();

// Array of scopes
$token = GlsAuthenticator::scopes(['parcel.create', 'parcel.read'])->getToken();

// Space-separated string
$token = GlsAuthenticator::scopes('parcel.create parcel.read')->getToken();

$token = GlsAuthenticator::withCredentials($clientId, $clientSecret)
    ->environment('production')
    ->scopes(['parcel.create', 'parcel.read'])
    ->getToken();

$token = GlsAuthenticator::fresh()->getToken();

// Clear token for current credentials
GlsAuthenticator::clearCache();

// Clear all cached tokens
GlsAuthenticator::clearAllTokens();

if (GlsAuthenticator::isConfigured()) {
    $token = GlsAuthenticator::getToken();
} else {
    // Prompt user to configure credentials
}

use SmartDato\GlsAuthenticator\Exceptions\MissingCredentialsException;
use SmartDato\GlsAuthenticator\Exceptions\InvalidCredentialsException;
use SmartDato\GlsAuthenticator\Exceptions\TokenRequestException;

try {
    $token = GlsAuthenticator::getToken();
} catch (MissingCredentialsException $e) {
    // No credentials configured
    logger()->error('GLS credentials not configured');
} catch (InvalidCredentialsException $e) {
    // Invalid client_id or client_secret
    logger()->error('Invalid GLS credentials', ['errors' => $e->errors]);
} catch (TokenRequestException $e) {
    // API request failed (network error, server error, etc.)
    logger()->error('GLS API request failed', ['message' => $e->getMessage()]);
}

use Illuminate\Support\Facades\Http;

$token = GlsAuthenticator::getToken();

$response = Http::withToken($token->token)
    ->post('https://api.gls-group.net/parcel/v1/shipments', [
        // Your shipment data
    ]);

namespace App\Http\Middleware;

use Closure;
use SmartDato\GlsAuthenticator\Facades\GlsAuthenticator;

class SetGlsCredentials
{
    public function handle($request, Closure $next)
    {
        $tenant = $request->user()->tenant;

        // Store token for later use
        $request->attributes->set('gls_token',
            GlsAuthenticator::withCredentials(
                $tenant->gls_client_id,
                $tenant->gls_client_secret
            )->getToken()
        );

        return $next($request);
    }
}

namespace App\Services;

use SmartDato\GlsAuthenticator\Facades\GlsAuthenticator;
use Illuminate\Support\Facades\Http;

class GlsParcelService
{
    protected $token;

    public function __construct()
    {
        $this->token = GlsAuthenticator::getToken();
    }

    public function createShipment(array $data)
    {
        return Http::withToken($this->token->token)
            ->post('https://api.gls-group.net/parcel/v1/shipments', $data)
            ->json();
    }

    public function trackParcel(string $parcelNumber)
    {
        return Http::withToken($this->token->token)
            ->get("https://api.gls-group.net/parcel/v1/tracking/{$parcelNumber}")
            ->json();
    }
}

use Illuminate\Support\Facades\Http;
use SmartDato\GlsAuthenticator\Facades\GlsAuthenticator;

test('can authenticate with GLS API', function () {
    Http::fake([
        'api-sandbox.gls-group.net/*' => Http::response([
            'token_type' => 'Bearer',
            'access_token' => 'test_token_123',
            'expires_in' => 14400,
        ]),
    ]);

    $token = GlsAuthenticator::getToken();

    expect($token->token)->toBe('test_token_123');
    expect($token->tokenType)->toBe('Bearer');
});
bash
php artisan vendor:publish --tag="gls-authenticator-config"
bash
composer analyse