← All posts

SaaS: payment webhook received twice, and how to prevent it

A customer charged or credited twice because of a replayed webhook? Payment providers resend events: your handler must be idempotent.

SaaS: payment webhook received twice, and how to prevent it

Key points

  • Payment providers guarantee “at least once” delivery, not “exactly once”.
  • Store each event ID before processing it to stop duplicates.
  • Reply fast (200) and do heavy work in the background.

In a SaaS app, the “payment succeeded” webhook activates a plan or adds credits. One day a customer gets their credits twice. The provider made no mistake: it resent the event because your server took too long to answer.

Why webhooks arrive twice

Stripe, PayPal and most services resend an event until they get a 2xx response in time. A slow server, a restart or a network glitch is enough. Your code must assume the same event can arrive several times, and out of order.

Make processing idempotent

Record the event’s unique ID in a table with a uniqueness constraint before doing anything:

CREATE TABLE webhook_events (
  event_id VARCHAR(255) PRIMARY KEY,
  received_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
try {
    $pdo->prepare('INSERT INTO webhook_events (event_id) VALUES (?)')->execute([$event->id]);
} catch (PDOException $e) {
    http_response_code(200); // already handled
    exit;
}
// … one-time processing here

The database is the referee: even if two requests land in the same millisecond, only one gets through.

Other rules we follow

  • Verify the signature first, to reject forged events.
  • Answer within seconds: store the event, return 200, then process from a queue.
  • Do not trust ordering: re-read the subscription’s current state from the API instead of applying events in sequence.
  • Log every event received so you can replay it after a bug.

FAQ

Isn’t checking “plan already active” enough?

No: two simultaneous requests can both pass the check before either saves. Only a uniqueness constraint is reliable.

How long should IDs be kept?

Providers usually retry for a few days; 30 days of retention leaves a comfortable margin.

Facing this on your site or app? We diagnose and fix it.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →