# Verify signatures

> Verify the X-Webhook-Signature header with HMAC-SHA256, compare signatures safely, enforce timestamp rules, and support secret rotation.

Every delivery is signed with HMAC-SHA256 using your Webhook Secret. Verify the signature before processing.

| Header | Description |
|--------|-------------|
| `X-Webhook-Signature` | Composite signature: `t={timestamp},v1={hmac_hex}` |
| `X-Webhook-Timestamp` | Unix seconds for this attempt — the same value the signature carries as `t` |
| `X-Webhook-Id` | The `evt_…` id of this delivery, for your logs. It is not signed, so [deduplicate](/docs/webhooks/payloads.md) on `event_id` from the body instead |

Only the first header takes part in verification. It contains the timestamp and one or more HMAC values:

```http
X-Webhook-Signature: t=1739281200,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
```

The HMAC is computed over `timestamp + "." + raw_body`:

```python
signature_payload = str(timestamp) + "." + raw_body
hmac_hex = HMAC-SHA256(webhook_secret, signature_payload)  # lowercase hex
```

The timestamp is part of the signed payload to prevent replay attacks. Reject deliveries where `|now - timestamp| > 300` seconds.

## Verification steps

1. Parse `X-Webhook-Signature`: extract `t` (timestamp) and every `v1` value
2. Reject if `|now - t| > 300` seconds
3. Build `signature_payload = str(t) + "." + raw_body`
4. Compute `HMAC-SHA256(webhook_secret, signature_payload)`
5. Convert the result to lowercase hex
6. Compare against every `v1` value using a timing-safe comparison — any match = valid
7. Reject with HTTP `401` if no signature matches

:::danger
Always compare signatures with a timing-safe function — `crypto.timingSafeEqual` (Node), `hmac.compare_digest` (Python), `hash_equals` (PHP), `MessageDigest.isEqual` (Java), `CryptographicOperations.FixedTimeEquals` (.NET). Plain `==` leaks the secret one byte at a time through timing analysis.
:::

## Secret rotation

During a Webhook Secret rotation, Paymos sends dual signatures for 24 hours so you can migrate without downtime. The header carries two `v1` values: `t={timestamp},v1={current_hmac},v1={previous_hmac}`. A signature that matches either the current or the previous secret is accepted, so your existing check (step 6) keeps passing throughout the rotation.

That overlap is the wrong thing to keep when the secret has leaked. While a rotation's 24 hours are running, the endpoint's menu in the dashboard offers **Rotate without grace period** instead: a new secret, and the current and previous ones stop signing at once. From then on the header carries a single `v1`, and your check fails every delivery until your server verifies with the new secret. Those deliveries are retried on the usual schedule, but update the secret right away. If no window is open, rotate as usual first — the option appears straight after.

## Verification code

```javascript
import { WebhookVerifier } from '@paymos/sdk';

const verifier = new WebhookVerifier(process.env.PAYMOS_WEBHOOK_SECRET);

// Keep the body as a Buffer until verification succeeds.
const event = verifier.constructEvent(signatureHeader, rawBody);
console.log(event.eventId, event.eventType, event.data);
```

```mcp
Setup once in terminal: `npx -y @paymos/mcp setup`

Prompt:
Read `paymos://docs/webhooks` and add a Paymos webhook endpoint to my
backend that verifies `X-Webhook-Signature` over the unparsed raw
request body using `WebhookVerifier` from the official SDK and
deduplicates deliveries by `event_id`. Use `@paymos/mcp` tool
`verify_webhook_signature` to test valid and tampered signatures.
```

```python
import os

from paymos import WebhookVerifier

verifier = WebhookVerifier(os.environ["PAYMOS_WEBHOOK_SECRET"])

# Keep raw_body as bytes until verification succeeds.
event = verifier.construct_event(signature_header, raw_body)
print(event["event_id"], event["event_type"], event["data"])
```

```php
<?php
use Paymos\Webhook\WebhookEvent;
use Paymos\Webhook\WebhookVerifier;

$verifier = new WebhookVerifier(getenv('PAYMOS_WEBHOOK_SECRET'));

// Keep $rawBody unchanged until verification succeeds.
$payload = $verifier->decodeVerifiedPayload($signatureHeader, $rawBody);
$event = new WebhookEvent($payload);
echo $event->id() . ' ' . $event->type();
```

```go
package main

import (
	"fmt"
	"os"
	"time"

	paymos "github.com/Paymos-labs/go-sdk/v2"
)

type invoiceEventData struct {
	InvoiceID string `json:"invoice_id"`
}

func handleWebhook(signatureHeader string, rawBody []byte) error {
	verifier, err := paymos.NewWebhookVerifier(os.Getenv("PAYMOS_WEBHOOK_SECRET"), 5*time.Minute)
	if err != nil {
		return err
	}
	var event paymos.WebhookEvent[invoiceEventData]
	if err := verifier.ConstructEvent(signatureHeader, rawBody, time.Now(), &event); err != nil {
		return err
	}
	fmt.Println(event.EventID, event.EventType, event.Data.InvoiceID)
	return nil
}
```

```csharp
using Paymos;

var verifier = new WebhookVerifier(
    Environment.GetEnvironmentVariable("PAYMOS_WEBHOOK_SECRET")!);

// Keep rawBody as ReadOnlySpan<byte> until verification succeeds.
var webhook = verifier.ConstructEvent<InvoiceEventData>(signatureHeader, rawBody);
Console.WriteLine($"{webhook.EventId} {webhook.EventType} {webhook.Data.InvoiceId}");

public sealed record InvoiceEventData(string InvoiceId);
```

```java
import com.fasterxml.jackson.databind.JsonNode;
import io.paymos.WebhookEvent;
import io.paymos.WebhookVerifier;
import java.time.Instant;

WebhookVerifier verifier = new WebhookVerifier(System.getenv("PAYMOS_WEBHOOK_SECRET"));

// Keep rawBody as byte[] until verification succeeds.
WebhookEvent<JsonNode> event =
    verifier.constructEvent(signatureHeader, rawBody, Instant.now());
System.out.println(event.eventId() + " " + event.eventType() + " " + event.data());
```

```ruby
require 'paymos'

verifier = Paymos::WebhookVerifier.new(ENV.fetch('PAYMOS_WEBHOOK_SECRET'))

# Keep raw_body as the original String until verification succeeds.
event = verifier.construct_event(signature_header, raw_body)
puts "#{event.event_id} #{event.event_type} #{event.data}"
```

```rust
use paymos::{Invoice, WebhookEvent, WebhookVerifier};

let verifier = WebhookVerifier::new(std::env::var("PAYMOS_WEBHOOK_SECRET")?)?;

// Keep raw_body as &[u8] until verification succeeds.
let event: WebhookEvent<Invoice> = verifier.construct_event(signature_header, raw_body)?;
println!("{} {} {}", event.event_id, event.event_type, event.data.invoice_id);
```
