Receive webhooks
Verify and handle Voidhash webhook events in a Rust server.
voidhash::webhooks::construct_event 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
construct_event takes the raw body bytes, the values of the three signing headers, and the
secret. This axum handler needs no crate feature; any framework that gives you the body bytes and
headers works the same way.
use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use voidhash::webhooks::{self, EVENT_HEADER, SIGNATURE_HEADER, TIMESTAMP_HEADER};
use crate::AppState;
pub async fn voidhash_webhook(State(app): State<AppState>, headers: HeaderMap, body: Bytes) -> StatusCode {
let (Some(event_type), Some(signature), Some(timestamp)) = (
single_header(&headers, EVENT_HEADER),
single_header(&headers, SIGNATURE_HEADER),
single_header(&headers, TIMESTAMP_HEADER),
) else {
return StatusCode::BAD_REQUEST;
};
let Ok(event) = webhooks::construct_event(&body, event_type, signature, timestamp, &app.webhook_secret) else {
return StatusCode::BAD_REQUEST;
};
tokio::spawn(async move {
if let Err(error) = crate::handle_event::handle_event(&app.db, event).await {
eprintln!("handling a Voidhash webhook failed: {error}");
}
});
StatusCode::OK
}
/// The header's value when it is sent exactly once.
fn single_header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
let mut values = headers.get_all(name).iter();
match (values.next(), values.next()) {
(Some(value), None) => value.to_str().ok().filter(|value| !value.is_empty()),
_ => None,
}
}Mount it with .route("/webhooks/voidhash", axum::routing::post(voidhash_webhook)). The handler
answers 200 before it processes the event. In production, store
the event first, so a crash after answering doesn't lose it.
Handle events
construct_event returns a voidhash::webhooks::WebhookEvent:
| Field | Type | Description |
|---|---|---|
event_type | String | The X-Webhook-Event header, such as purchase.refunded. |
payload | serde_json::Value | The parsed JSON body. |
timestamp | i64 | When the attempt was signed, in Unix seconds. |
Match on event_type and skip duplicates. This example uses
sqlx:
use sqlx::PgPool;
use voidhash::webhooks::WebhookEvent;
pub async fn handle_event(db: &PgPool, event: WebhookEvent) -> Result<(), sqlx::Error> {
let field = |name: &str| event.payload[name].as_str().unwrap_or_default().to_owned();
let subject = [field("subscriptionId"), field("purchaseId"), field("personId")]
.into_iter()
.find(|id| !id.is_empty())
.unwrap_or_default();
let key = format!("{}:{subject}:{}{}", event.event_type, field("occurredAt"), field("erasedAt"));
// Deliveries are at least once: skip one you have already processed.
let claimed = sqlx::query("INSERT INTO processed_webhooks (key) VALUES ($1) ON CONFLICT DO NOTHING")
.bind(&key)
.execute(db)
.await?;
if claimed.rows_affected() == 0 {
return Ok(());
}
match event.event_type.as_str() {
"subscription.renewed" | "subscription.expired" | "purchase.refunded" => {
sqlx::query("DELETE FROM access_cache WHERE distinct_id = $1")
.bind(field("distinctId"))
.execute(db)
.await?;
}
"person.deleted" => {
sqlx::query("DELETE FROM users WHERE voidhash_person_id = $1")
.bind(field("personId"))
.execute(db)
.await?;
}
_ => {} // Includes test.ping and event types added after this code.
}
Ok(())
}Verification errors
construct_event returns a voidhash::webhooks::WebhookVerificationError:
| Variant | Cause |
|---|---|
InvalidSignature | The signature doesn't match, or the timestamp is malformed or outside the tolerance. |
InvalidPayload | The signature matches but the body isn't valid JSON. |
Your code checks the headers, as single_header does above. Answer 400 when one is missing,
empty or repeated, and for both variants. A clock that drifts beyond the tolerance shows up as
InvalidSignature; see Troubleshooting.
Options
construct_event always accepts a clock difference of 300 seconds.
voidhash::webhooks::verify_signature(payload, signature, timestamp, secret, tolerance_seconds)
takes the tolerance as an argument and returns a boolean, for when you parse the body 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().rotate_secret. 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 3000 or cloudflared tunnel --url http://localhost:3000, 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. An extractor such as
Jsonconsumed the body: take it asBytesand pass those bytes. 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
rotate_secret return the signing secret:
use voidhash::generated::types::{
CreateWebhookBodyJsonEncoding, CreateWebhookBodyJsonEncodingEventsItem as Event, IntegrationEnvironment,
};
use voidhash::VoidhashClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let voidhash = VoidhashClient::new(std::env::var("VOIDHASH_SECRET_KEY")?)?;
let webhook = voidhash
.webhooks()
.endpoints()
.create(&CreateWebhookBodyJsonEncoding {
name: "Orders backend".into(),
url: "https://api.example.com/webhooks/voidhash".into(),
events: vec![Event::SubscriptionCreated, Event::SubscriptionRenewed, Event::PurchaseCompleted],
environment: Some(IntegrationEnvironment::Production),
description: None,
})
.await?;
println!("{} {}", webhook.id, webhook.secret); // wh_ep_… whsec_…
Ok(())
}Other endpoint methods: list, get, update, delete, rotate_secret and test.
voidhash.webhooks().deliveries() has list(endpoint_id), get(delivery_id) and
retry(delivery_id).
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.