Search by

airsoft-defense / connector

Blackhawkso

PHP SDK for the Airsoft Defence API

v0.2.0 2026-12-03 22:24 UTC

This package is auto-updated.

Last update: 2026-12-03 22:25:14 UTC


README

Use this Composer package to connect a PHP application to the Airsoft Defence API. It supports OAuth client registration, server-to-server access, user-authorised access, and named methods for the full API.

Install

Use PHP 8.2 or later in the PHP 8 series, the PHP cURL extension, and Composer. Run this in your application's folder.

composer require airsoft-defense/connector

Save this as check-airsoft.php beside your application's vendor folder and run php check-airsoft.php.

<?php

declare(strict_types=1);

use AirsoftDefense\Connector\Client;

require __DIR__ . '/vendor/autoload.php';

$sdk = new Client(environment: 'demo');
echo $sdk->ping()['message'] . PHP_EOL;

The public ping returns pong without credentials. For production, set the environment to production.

Choose how to connect

What you are building Which flow to use What you need
A server job or an integration operating as the OAuth client owner Client credentials A client ID, client secret, and the scopes for the API calls
A “Connect to Airsoft Defence” button that acts for each consenting user Authorization code with PKCE A registered client, an exact callback URL, browser sign-in and consent, and server-side token storage
An integration setup screen that creates the OAuth client programmatically Authenticated client registration An API login token for the account that will own the client and permission to create it
A retailer installing a new store integration Hosted store connection A stable installation UUID, HTTPS callback, and a retailer with access to an approved store
A first-party app that signs in its users Sanctum The user's account and their two-factor code when required
A tool that already has a valid API bearer token Direct bearer token The token and permission for the API calls

Client registration and user consent happen at different times. Register the app once and reuse its client ID for user connections. Users sign in and approve access on the Airsoft Defence page.

Choose production or demo

The client defaults to production at https://airsoft-defence.co.uk/api. Set the environment to demo for https://demo.airsoft-defence.co.uk/api. Keep each environment's credentials and tokens separate.

Select the environment in your application config and pass it with new Client(environment: $settings['environment']). You can also set the AIRSOFT_DEFENCE_ENV environment variable. In PowerShell, use $env:AIRSOFT_DEFENCE_ENV = 'demo'. In a POSIX shell, use export AIRSOFT_DEFENCE_ENV=demo.

In a Git checkout, edit the environment setting in config.php to set the default for the SDK and its examples. For a Composer install, keep this setting in your own application so it survives package updates.

The client checks these settings in order.

  1. An explicit baseUrl.
  2. The constructor's environment argument.
  3. The AIRSOFT_DEFENCE_ENV environment variable.
  4. The default in the SDK's config.php.

Run the included examples

Use an OAuth client that allows the client credentials grant. Enable store:list for the connection and store examples. The player status example defaults to user:limited and requires permission to check the requested player.

Clone or download the SDK source, run composer install in its root, then set the credentials and run the scripts. The commands below use PowerShell.

$env:AIRSOFT_DEFENCE_CLIENT_ID = '<your client ID>'
$env:AIRSOFT_DEFENCE_CLIENT_SECRET = '<your client secret>'

php examples/oauth.php
php examples/list-stores.php
php examples/player-defence-status.php 123

In a POSIX shell, use export AIRSOFT_DEFENCE_CLIENT_ID='...' and export AIRSOFT_DEFENCE_CLIENT_SECRET='...'. Replace 123 with the player record ID or UUID accepted by the status endpoint.

Script Output
oauth.php Confirms an access token was issued. The token stays in memory.
list-stores.php The store directory as JSON, limited to the account's access.
player-defence-status.php Checks a player record by ID and prints the API's validity result as JSON.
connect-with-oauth.php Builds a consent URL and exchanges a returned code using the original PKCE verifier.
sanctum.php Shows direct user sign-in and two-factor verification.

Set AIRSOFT_DEFENCE_SCOPE to override the script's default scope. For example, if the client uses user:restricted for its own record, set that scope before running the player example. Unset the override before running a script that needs a different scope. AIRSOFT_DEFENCE_API_BASE_URL optionally points the examples at another environment. The scripts send errors to stderr and use exit code 1 for a failed request or setup. The player script also uses exit code 2 for an invalid ID.

Sign in a user with Sanctum

Use Sanctum for first-party mobile and web sign-in when the person needs an API token for their own account. No OAuth client ID or secret is needed.

$result = $sdk->sanctumLogin($email, $password);

if ($result['status'] === 'two_factor_required') {
    // Keep tempToken in memory while your UI asks the user for their code.
    $result = $sdk->sanctumVerifyTwoFactor($result['tempToken'], $authenticatorCode);
    // For a recovery code, call sanctumRecoverTwoFactor($tempToken, $recoveryCode).
}

$api = $result['client'];
$session = $api->sessionCheck();

When the wrapper returns authenticated, use its client for API calls. It also returns token for storage and user when the server supplies account details. To reconnect with a saved token, call $sdk->withToken($savedToken). In a mobile app, store the final token in the platform's secure credential store. Pass authenticator codes as strings so leading zeroes survive.

Run the CLI example with php examples/sanctum.php. Set AIRSOFT_DEFENCE_EMAIL and AIRSOFT_DEFENCE_PASSWORD in a trusted test environment. For a 2FA account, also set either AIRSOFT_DEFENCE_TOTP (a current code) or AIRSOFT_DEFENCE_RECOVERY_CODE (an unused code).

A temporary challenge token is single-use on success and expires if the user waits too long. Never attach it as a bearer token. If verification returns 422, prompt for another code using the current challenge. For 401 during verification, restart sign-in. On 429, wait and use the API's Retry-After value when available. A 423 indicates an account hold.

The session check reports server-side activity information, including sanctum_token_refreshed and inactive_expiry_at when available. It does not return a new bearer token or an OAuth refresh token. If your saved bearer token is rejected, ask the user to sign in again.

Access the API from a server job

The application supplies the configured credentials and the API scope. Keep the secret on the server. After the access token expires, repeat clientCredentials() to obtain a new one.

<?php

use AirsoftDefense\Connector\Client;

require __DIR__ . '/vendor/autoload.php';

$clientId = getenv('AIRSOFT_DEFENCE_CLIENT_ID');
$clientSecret = getenv('AIRSOFT_DEFENCE_CLIENT_SECRET');
if (!$clientId || !$clientSecret) {
    throw new RuntimeException('Configure the Airsoft Defence OAuth credentials.');
}

$sdk = new Client();
$tokens = $sdk->clientCredentials($clientId, $clientSecret, 'store:list');
$api = $sdk->withToken($tokens['access_token']);

$stores = $api->listStores();

Use expires_in from the token response when deciding when to obtain another token. A pre-issued access or API login token can be attached using new Client($token) or withToken($token). withToken() returns a new client with the same base URL and timeout.

Register your app through the API

For automated setup, call registerOAuthClient() using the intended owner account's API login token. Registration requires an eligible Airsoft Defence account. If your setup obtains an API login token with login(), check requires_2fa and complete the challenge using verifyTwoFactor($result['temp_token'], $code) or recoverTwoFactor($result['temp_token'], $recoveryCode). The final login response contains token. Use this account setup flow in a trusted environment. Direct users to Airsoft Defence's sign-in page for the OAuth consent flow described below.

$redirectUri = 'https://app.example.com/airsoft/callback';
$registration = $sdk->withToken($ownerLoginToken)->registerOAuthClient(
    'Example integration',
    $redirectUri,
    'Connect the application to Airsoft Defence',
);

$clientId = $registration['data']['client_id'];
$clientSecret = $registration['data']['client_secret'];
$grantedScopes = $registration['data']['scopes'];

Store the returned secret in server-side secret storage when registering. Use the exact callback URL in both the authorisation request and the code exchange. When the installation already has a client ID and secret, use the stored pair.

Connect a user with browser consent

The following snippets belong in two handlers in your web application. Load the SDK and registered client settings in both handlers. Start the PHP session before accessing $_SESSION. Configure the first handler as your Connect button target and the second at the registered callback URL.

Connect handler. Generate state and a PKCE verifier for this attempt. Pick the smallest granted scope needed for your integration. The SDK builds an S256 challenge from the verifier.

session_start();

$state = bin2hex(random_bytes(32));
$codeVerifier = bin2hex(random_bytes(32));
$_SESSION['airsoft_oauth'] = [
    'state' => $state,
    'code_verifier' => $codeVerifier,
    'expires_at' => time() + 600,
];

$url = $sdk->authorizationUrl($clientId, $redirectUri, $state, $scope, $codeVerifier);
header('Location: ' . $url, true, 302);
exit;

Callback handler. Check that the attempt belongs to the current session and consume it once. Replace the example exit responses with your application's error pages as needed.

session_start();

$pending = $_SESSION['airsoft_oauth'] ?? null;
$state = $_GET['state'] ?? null;
if (
    !is_array($pending)
    || $pending['expires_at'] <= time()
    || !is_string($state)
    || !hash_equals($pending['state'], $state)
) {
    http_response_code(400);
    exit('The Airsoft Defence connection attempt is invalid or expired.');
}

unset($_SESSION['airsoft_oauth']);

$code = $_GET['code'] ?? null;
if (isset($_GET['error']) || !is_string($code) || $code === '') {
    http_response_code(400);
    exit('Airsoft Defence access was not authorised.');
}

$tokens = $sdk->exchangeAuthorizationCode(
    $clientId,
    $clientSecret,
    $redirectUri,
    $code,
    $pending['code_verifier'],
);

$api = $sdk->withToken($tokens['access_token']);
$account = $api->currentUser();

Persist the access token, its expiry, and any refresh token in server-side storage associated with the signing-in application user. Keep client secrets and tokens out of responses and application logs.

Refresh. When the access token is close to expiry, call refreshOAuthToken() with the same registered client. Save the new access token and expiry, and replace the stored refresh token when the response includes one. If multiple workers use the same connection, serialise refreshes for that connection so two workers cannot consume the same refresh token. If Airsoft Defence reports that the refresh token is no longer valid, have the user reconnect.

$tokens = $sdk->refreshOAuthToken($clientId, $clientSecret, $storedRefreshToken);
$api = $sdk->withToken($tokens['access_token']);

Connect a new retailer installation

Use the hosted store connection for a retailer installing an integration with no existing OAuth client. The retailer signs in on Airsoft Defence, completes any two-factor challenge and selects an eligible store.

In your server-side connect handler, use a stable installation UUID and the public HTTPS callback URL. Generate a new PKCE verifier for each attempt.

$codeVerifier = bin2hex(random_bytes(32));
$challenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');

$attempt = $sdk->startStoreConnection($installationId, $redirectUri, $challenge);

Save attempt_id, expires_at and the verifier server-side against the installation and the administrator who started setup. Direct their browser to approval_url. Verify the redirect uses the Airsoft Defence host for the selected environment.

The callback receives attempt_id and the one-time approval_proof as POST fields. Match the attempt to the pending installation. A cross-site POST may arrive without your session cookie. If needed, hold the proof briefly on the server and redirect the browser to resume setup in the initiating administrator's authenticated session. Require that session before redeeming. Check expiry and guard the redemption against duplicate submissions. Use the verifier from your saved attempt.

$connection = $sdk->redeemStoreConnection($attemptId, $savedVerifier, $approvalProof);

$tokens = $sdk->exchangeAuthorizationCode(
    $connection['client_id'],
    $connection['client_secret'],
    $connection['redirect_uri'],
    $connection['authorization_code'],
    $savedVerifier,
);

Store the returned store, client credentials and token set together on the server. On reconnect, replace the installation's credentials and tokens with the new values. Use the refresh flow above and keep the verifier, proof, secrets and tokens out of logs.

API methods

Pass the printed hexadecimal member ID as a string to $api->playerStatusByMemberId('00ab12cd34ef5'). The helper resolves the member ID before checking defence status. An empty search returns null. This flow requires permission to search the player list.

For every named wrapper, see the complete endpoint reference. Use $api->searchPlayers(['member_id' => $memberId]) to look up a membership reference and $api->playerStatus($playerId) to check the returned record ID. Photo methods accept a local path. Record IDs can be UUIDs or positive numeric IDs on compatible routes.

Area Methods
Connectivity and account ping(), sessionCheck(), currentUser(), userDetails()
Sign-in and two-factor login(), verifyTwoFactor(), recoverTwoFactor()
OAuth registerOAuthClient(), clientCredentials(), authorizationUrl(), exchangeAuthorizationCode(), refreshOAuthToken()
Sites and stores listSites(), getSite(), listStores(), getStore()
Games and attendance listGames($page, $perPage), getGame(), checkInPlayer($siteId, $userId, $data), selfCheckIn($siteId, $data)
Players playerStatus($playerId)
Custom JSON requests request($method, $path, $query, $json)

The client returns decoded API arrays, with null for an empty body on resource methods and request(). List and pagination formats follow the endpoint's response. Pass filters and pagination as query arguments where documented.

$stores = $api->listStores(['search' => 'Example']);
$games = $api->listGames(page: 2, perPage: 25);
$versions = $api->legalVersions();
$players = $api->listPlayers(['page' => 1, 'size' => 20]);

Use API-relative paths beginning with /. For JSON writes, pass an associative array as the json argument. The generic request method handles JSON routes. See the official API docs for payload fields, filters, pagination, scopes, and routes that require a different format.

Game check-ins

Both methods accept an optional API-shaped body:

$api->checkInPlayer($siteId, $userId, ['play_date' => '2025-11-08']);
$api->selfCheckIn($siteId, [
    'play_date' => '2025-11-08',
    'location' => ['latitude' => 51.5, 'longitude' => -0.12, 'accuracy' => 18],
]);

Omit play_date to use the server receipt date in Europe/London. Invalid or future London dates return 422. Self check-ins may also include location with latitude and longitude in decimal degrees and accuracy in metres, or ['status' => 'permission_denied'] / ['status' => 'unavailable'] when appropriate. Omit location entirely if GPS is unsupported; null or an empty object is assessed differently. To send an empty JSON object for location, use new \stdClass(), not []. For self check-ins, location and historical dates are advisory and can add risk points. A 201 acknowledges processing, not a saved record; duplicates may return 409.

Handle errors and configure the client

Catch AirsoftDefense\Connector\Exception\ApiException for an HTTP error. It exposes statusCode, any decoded response, and the retryAfter value if supplied. Catch AirsoftDefense\Connector\Exception\TransportException for a connection failure or invalid successful response. An invalid method, path, or client option raises InvalidArgumentException. Invalid locally supplied JSON data can raise JsonException.

HTTP status What to check
401 The bearer token is missing, expired, or rejected. For a token request, check the credentials or authorisation code.
403 Check the account's permissions, OAuth scopes, and whether the account can access the requested record.
404 Check the resource ID and the API route.
409 For attendance, the check-in may already exist. Check the API response before retrying.
422 Inspect the structured validation details on the API exception.
429 Use Retry-After when supplied and pace subsequent requests.

The SDK sends each request once. Choose a retry policy suited to the operation. For a timed-out write, verify the resulting server state before repeating it.

The default API base URL is https://airsoft-defence.co.uk/api and the request timeout is 30 seconds. You can override either via named constructor arguments.

$sdk = new Client(
    baseUrl: 'http://127.0.0.1:8080/api',
    timeoutSeconds: 10,
);

The client accepts HTTPS for remote endpoints and permits HTTP for loopback development. For browser consent it uses the configured address with a trailing /api removed. Keep a remote base URL in trusted application configuration and use the official Airsoft Defence environment unless you have a specific test environment.

Run the tests

Install the development dependencies with composer install, then run composer test. The PHPUnit suite covers request construction, OAuth and PKCE, Sanctum and 2FA, environment selection, and response and transport failures. It uses synthetic responses and never calls a live service.

To measure executable line coverage, enable Xdebug coverage mode before running the coverage script.

XDEBUG_MODE=coverage composer test:coverage
$env:XDEBUG_MODE = 'coverage'
composer test:coverage

The console reports coverage for src/ and the script writes a Clover report to build/coverage.xml.

Licence

Copyright © 2026 Airsoft Defence Ltd. The MIT License permits commercial use, modification, and redistribution, including in proprietary mobile apps and e-commerce integrations. Include the copyright and licence notices whenever you distribute the SDK or substantial portions of it. MIT License