PHP library

A server-side client for the Voidhash API for PHP 8.2 and later.

voidhash/voidhash-php is a client for PHP backends, with Laravel and Symfony setup below. It needs a secret key, so run it on your server only.

Install

voidhash/voidhash-php installs from a clone of the Voidhash repository, as a Composer path repository:

git clone https://github.com/voidhashcom/voidhash.git third_party/voidhash
composer config repositories.voidhash path third_party/voidhash/libraries/php
composer require voidhash/voidhash-php:@dev

To pin a build, check out a commit in the clone (git -C third_party/voidhash checkout <commit>), or add the repository as a Git submodule so your repository records the commit.

Requirements: PHP 8.2, 8.3 or 8.4 with the json extension. The library sends requests with Symfony HTTP Client 7, which Composer installs with it.

Create a client

Create one client with your secret key and share it across your application:

bootstrap/voidhash.php
use Voidhash\VoidhashClient;

$voidhash = VoidhashClient::create(getenv('VOIDHASH_SECRET_KEY'), [
    // Event capture is served from the API host for now.
    'ingestUrl' => 'https://api.voidhash.com',
]);

create takes the secret key and an array of options:

OptionDefaultDescription
projectIdThe key's projectSkips the project lookup.
baseUrlhttps://api.voidhash.comThe API origin.
ingestUrlhttps://ingest.voidhash.comThe event capture origin. Use https://api.voidhash.com; the default host doesn't answer yet.
publishableKey—Sent as the body token on event capture. Optional.
httpClientSymfony Psr18ClientAny PSR-18 client, for timeouts, proxies or tracing.
headers[]Extra headers for every request.

create makes no request. It throws Voidhash\Exception\ApiException with the code configuration_error when the secret key is blank or headers sets Authorization or x-secret-key.

Call the API

Each resource is a property of the client. Methods take IDs as strings and request bodies as generated model objects built with setters. They return generated models with a getter for each field of the API reference. List methods follow every page and return an array.

use Voidhash\Generated\Core\Model\CreatePersonBodyJsonEncoding;

foreach ($voidhash->perks->list() as $perk) {
    echo $perk->getSlug(), PHP_EOL;
}

$person = $voidhash->persons->create(
    (new CreatePersonBodyJsonEncoding())->setDistinctId('user_123')->setEmail('ada@example.com'),
);
PropertyCovers
personsPersons, attributes and access checks.
perks, productsThe catalog, and the perks each product grants.
paywallsPaywall locations.
webhooksWebhook endpoints and deliveries.
eventCaptureEvents.
notificationsPush notifications.
paymentSourcesPayment sources.
apiKeys, schemaThe project's API keys and runtime schema.

For an endpoint without a method here, call the REST API directly.

Handle errors

Every failed call throws Voidhash\Exception\ApiException, holding the API error. Branch on getType() and getErrorCode():

use Voidhash\Exception\ApiException;

try {
    $person = $voidhash->persons->get('person_k2v9x4m8q1r3');
} catch (ApiException $error) {
    match ($error->getType()) {
        'not_found' => $person = null,
        'unauthenticated', 'permission_denied' => throw new RuntimeException(
            'The Voidhash secret key is invalid or lacks access.', previous: $error,
        ),
        default => throw $error,
    };
}

getParam(), getStatus() and getRequestId() return the rest. A failure that never reached the API has status 0: a client misconfiguration has the code configuration_error. Network failures throw the HTTP client's PSR-18 Psr\Http\Client\ClientExceptionInterface instead. The library doesn't retry or cache.

Use with Laravel or Symfony

Register the client once as a shared service, then type-hint VoidhashClient where you need it.

app/Providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Voidhash\VoidhashClient;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(
            VoidhashClient::class,
            fn () => VoidhashClient::create(config('services.voidhash.secret_key'), [
                'ingestUrl' => 'https://api.voidhash.com',
            ]),
        );
    }
}

Add the keys to config/services.php:

config/services.php
'voidhash' => [
    'secret_key' => env('VOIDHASH_SECRET_KEY'),
    'webhook_secret' => env('VOIDHASH_WEBHOOK_SECRET'),
],
config/services.yaml
services:
  Voidhash\VoidhashClient:
    factory: ['Voidhash\VoidhashClient', "create"]
    arguments:
      - "%env(VOIDHASH_SECRET_KEY)%"
      - { ingestUrl: "https://api.voidhash.com" }

Next steps

Something wrong or missing on this page? Tell us by email or on Discord.