Receive webhooks
Verify and handle Voidhash webhook events in a PHP application.
Voidhash\Webhooks::constructEvent verifies a webhook request and parses its body.
It needs only the endpoint's signing secret (whsec_…), here VOIDHASH_WEBHOOK_SECRET; no client
or secret key.
Create an endpoint
In Studio, open Settings → Webhooks, select New webhook, and enter your endpoint's public
HTTPS URL, its environment and the events it receives. A Production endpoint receives
production purchases; a Test endpoint receives sandbox, simulated and test mode purchases.
Studio shows the signing secret (whsec_…) once; store it in your secret manager, here as
VOIDHASH_WEBHOOK_SECRET. See Endpoints for every field, or
create one from code.
Verify a request
Pass the raw body, never a decoded and re-encoded one, with the request headers.
use App\Jobs\HandleVoidhashEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Voidhash\Exception\WebhookVerificationException;
use Voidhash\Webhooks;
Route::post('/webhooks/voidhash', function (Request $request) {
try {
$event = Webhooks::constructEvent(
$request->getContent(),
$request->headers->all(),
config('services.voidhash.webhook_secret'),
);
} catch (WebhookVerificationException) {
return response()->noContent(400);
}
HandleVoidhashEvent::dispatch($event->type, $event->payload);
return response()->noContent(200);
});namespace App\Controller;
use App\Message\VoidhashEvent;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
use Voidhash\Exception\WebhookVerificationException;
use Voidhash\Webhooks;
final class VoidhashWebhookController
{
public function __construct(
private readonly MessageBusInterface $bus,
#[Autowire(env: 'VOIDHASH_WEBHOOK_SECRET')] private readonly string $secret,
) {
}
#[Route('/webhooks/voidhash', methods: ['POST'])]
public function __invoke(Request $request): Response
{
try {
$event = Webhooks::constructEvent($request->getContent(), $request->headers->all(), $this->secret);
} catch (WebhookVerificationException) {
return new Response(null, 400);
}
$this->bus->dispatch(new VoidhashEvent($event->type, $event->payload));
return new Response(null, 200);
}
}use Voidhash\Exception\WebhookVerificationException;
use Voidhash\Webhooks;
require __DIR__ . '/../../vendor/autoload.php';
try {
$event = Webhooks::constructEvent(
file_get_contents('php://input'),
getallheaders(),
getenv('VOIDHASH_WEBHOOK_SECRET'),
);
} catch (WebhookVerificationException) {
http_response_code(400);
exit;
}
enqueueVoidhashEvent($event->type, $event->payload); // your queue or table
http_response_code(200);Each example queues the event and answers 200 before it
processes it. Keep the route out of CSRF protection: Laravel's
routes/api.php already is.
Handle events
constructEvent returns a Voidhash\WebhookEvent with three read-only properties:
| Property | Type | Description |
|---|---|---|
type | string | The X-Webhook-Event header, such as purchase.refunded. |
payload | array | The JSON body, decoded to an associative array. |
timestamp | DateTimeImmutable | When the attempt was signed. |
In your queue worker, switch on the type and skip duplicates:
function handleVoidhashEvent(PDO $db, string $type, array $payload): void
{
$subject = $payload['subscriptionId'] ?? $payload['purchaseId'] ?? $payload['personId'] ?? '';
$key = "{$type}:{$subject}:" . ($payload['occurredAt'] ?? $payload['erasedAt'] ?? '');
// Deliveries are at least once: skip one you have already processed.
$claim = $db->prepare('INSERT INTO processed_webhooks (key) VALUES (?) ON CONFLICT DO NOTHING');
$claim->execute([$key]);
if ($claim->rowCount() === 0) {
return;
}
match ($type) {
'subscription.renewed', 'subscription.expired', 'purchase.refunded' => $db
->prepare('DELETE FROM access_cache WHERE distinct_id = ?')
->execute([$payload['distinctId']]),
'person.deleted' => $db
->prepare('DELETE FROM users WHERE voidhash_person_id = ?')
->execute([$payload['personId']]),
default => null, // Includes test.ping and event types added after this code.
};
}Verification errors
constructEvent throws Voidhash\Exception\WebhookVerificationException. Its reason property
says why:
reason | Cause |
|---|---|
missing_header | A signing header is missing, empty or sent more than once. |
invalid_signature | The signature doesn't match, or the timestamp is malformed or outside the tolerance. |
invalid_payload | The signature matches but the body isn't valid JSON. |
Answer 400 for each. A clock that drifts beyond the tolerance shows up as invalid_signature;
see Troubleshooting.
Options
constructEvent takes two optional arguments after the secret:
| Argument | Default | Description |
|---|---|---|
$toleranceSeconds | 300 | Accepted clock difference, in seconds, in either direction. |
$now | Current time | A DateTimeImmutable to verify against. Use it in tests. |
Webhooks::verifySignature($payload, $signature, $timestamp, $secret) takes the same options and
returns a boolean, for when you read the headers yourself.
Respond and retries
Answer any 2xx within 30 seconds. A redirect, a 4xx or 5xx, a timeout or a connection
error is a failed attempt. Voidhash retries it 5 minutes, 30 minutes, 2 hours and 24 hours after
the attempt before, signing each retry again with a new timestamp, then marks the delivery
exhausted. After 20 consecutive failed attempts it sets the endpoint to Failed and stops
sending to it until you enable it again. See Retries and the
delivery log.
Duplicates and ordering
Delivery is at least once: a timeout after you processed an event, or a manual retry, sends it
again. Payloads carry no event ID, so the handler above builds a key from the type, the subject's
ID and occurredAt (erasedAt for person.deleted). Events can also arrive out of order; compare
occurredAt before you overwrite newer state, or check access for
the current answer.
Rotate the secret
Rotate a secret that may have leaked with Rotate secret in the endpoint's actions menu,
voidhash webhook rotate, or $voidhash->webhooks->endpoints->rotateSecret. The old secret stops working at once, including for
retries of earlier events, so deploy the new one right away.
Test locally
Voidhash can't reach localhost, so expose your local server through a tunnel such as
ngrok http 8000 or cloudflared tunnel --url http://localhost:8000, and create a
Test endpoint with the tunnel's HTTPS URL. Then:
- Select Send test in the endpoint's actions menu, or run
voidhash webhook test <webhook>, which waits for your server's answer and prints it. A test only goes to an endpoint that is Active. Itstest.pingpayload has notypefield. - Make a sandbox or simulated purchase to receive real lifecycle events. See Test purchases (Help center).
Troubleshooting
- Every signature fails. You passed a decoded and re-encoded body, such as
json_encode($request->all()), instead of$request->getContent()orphp://input. Or you are using another endpoint's secret: each endpoint has its own, and rotating replaces it at once. - Signatures fail only sometimes. Check your server's clock. Drift beyond 300 seconds rejects valid requests; keep clocks synced with NTP.
- A proxy rewrites the body. Some proxies re-encode JSON or change line endings. Verify against the bytes your application receives, and turn off body rewriting on the webhook route.
Manage endpoints from code
$voidhash->webhooks->endpoints manages endpoints with a secret key. Only create and
rotateSecret return the signing secret:
use Voidhash\Generated\Core\Model\CreateWebhookBodyJsonEncoding;
use Voidhash\VoidhashClient;
$voidhash = VoidhashClient::create(getenv('VOIDHASH_SECRET_KEY'));
$webhook = $voidhash->webhooks->endpoints->create(
(new CreateWebhookBodyJsonEncoding())
->setName('Orders backend')
->setUrl('https://api.example.com/webhooks/voidhash')
->setEvents(['subscription.created', 'subscription.renewed', 'purchase.completed'])
->setEnvironment('production'),
);
echo $webhook->getId(), ' ', $webhook->getSecret(); // wh_ep_… whsec_…Other endpoint methods: list, get, update, delete, rotateSecret and test.
$voidhash->webhooks->deliveries has list($webhookId), get($deliveryId) and
retry($deliveryId).
Next steps
- Webhook events: every event type and its payload.
- Check access
- Persons and events
Something wrong or missing on this page? Tell us by email or on Discord.