How FamGateway™ Webhooks Work: Pure-PHP Architecture, HMAC Security & Official PHP SDK
In mission-critical fintech applications, payment verification cannot rely on fragile browser redirects. Customers frequently close browser tabs immediately after seeing a UPI success tick, drop network connectivity on mobile 4G/5G, or experience app crashes. Here is the complete architectural and engineering blueprint of the FamGateway™ Webhook Delivery Engine — built on a lightweight, high-performance Pure PHP and MySQL stack, and how to integrate it using our official open-source FamGateway PHP SDK.
- Architecture Stack: Pure PHP 8.x + MySQL (PDO), zero external dependencies, native IMAP SSL (port 993).
- Signature Algorithm: Cryptographic HMAC-SHA256 generated via
hash_hmac('sha256', $rawBody, $apiKey). - Delivery Latency: Sub-150ms asynchronous execution decoupled via non-blocking cURL to
api/cron.php. - Idempotency & Anti-Fraud: Row-level atomic database UTR locking prevents 100% of double-spending attempts.
- Retry Policy: 4-attempt exponential backoff schedule (Immediate, +5 min, +10 min, +15 min).
1. Official Open-Source PHP SDK on GitHub
To make payment creation and webhook verification seamless for developers, we maintain an official zero-dependency PHP SDK on GitHub:
aryanispe / famgateway-php-sdk
A pure, zero-dependency drop-in PHP module for instant FamPay UPI payment order creation and cryptographic HMAC-SHA256 webhook verification.
View on GitHub →2. Quantitative Performance & Architecture Benchmarks
Here is an empirical comparison of how FamGateway's webhook architecture compares with traditional custodial payment aggregators and manual UTR verification:
| Evaluation Metric | FamGateway Engine | Traditional Gateways | Manual Verification |
|---|---|---|---|
| Verification Latency | 1.5 – 3.5 seconds | 2.0 – 5.0 seconds | 5 – 30 minutes |
| Fund Settlement | Instant (0s, Direct UPI) | T+2 Business Days | Instant (Manual) |
| Transaction Commission | 0% (Free Forever) | 2.0% – 3.0% + GST | 0% |
| Cryptographic Auth | HMAC-SHA256 Signed | HMAC / Basic Secret | None (Screenshot fake risk) |
| Double-Spending Lock | Atomic DB UTR Unique | Aggregator Controlled | High Human Error Risk |
| Automated Retries | 4 Retries (0, 5m, 10m, 15m) | Variable (3-5 Retries) | No Retry Capability |
3. The Problem: Why Client-Side Redirects Fail
Traditional payment setups often redirect the customer's browser from the payment page back to a merchant URL (such as https://yoursite.com/success.php?order_id=123). In high-volume production environments, between 8% and 14% of successful payments are lost or abandoned at this stage due to:
- Immediate App Switching: Users tap 'Done' or swipe away the mobile browser immediately after viewing their UPI app confirmation screen.
- Mobile Network Handover Failures: Network latency spikes or mobile data disconnects during the bank-to-merchant browser redirect.
- Aggressive OS Tab Discarding: Mobile browsers (such as Chrome and Safari on iOS/Android) frequently suspend background tabs to save battery when a user opens PhonePe, Google Pay, or FamApp.
FamGateway eliminates this vulnerability through Server-to-Server Webhooks (Instant Payment Notifications) that communicate directly between our backend and your server within milliseconds of payment clearance.
3. Pure-PHP & MySQL Webhook Pipeline Architecture
Unlike complex systems that require heavy Node.js or Python daemons, FamGateway is engineered entirely in Pure PHP and MySQL for maximum speed, security, and low server resource consumption. Learn how this fits into our broader Non-Custodial Architecture:
The 5-Stage Webhook Delivery Lifecycle:
- Pure-PHP IMAP Ingestion (
api/imap-processor.php): When an order check is requested, our pure-PHP IMAP engine decrypts the merchant's Google App Password using AES-256-GCM, connects over SSL port 993 ({imap.gmail.com:993/imap/ssl}), and scans incoming bank receipt emails within an atomic 5-second lockfile window. - Atomic Order & UTR Locking: The 12-digit bank UTR and embedded transaction reference note are matched against the pending order database record using an atomic row-level lock, instantly preventing fake UPI payments and double-spending.
- HMAC-SHA256 Payload Construction: The
fireWebhook()subsystem compiles the standardized JSON payload and computes a cryptographic signature using the merchant's private API key as the shared secret:hash_hmac('sha256', $payload, $apiKey). - Decoupled Queue Storage (
webhook_jobs): The webhook task is stored in a dedicated MySQL job queue table with statuspending. - Non-Blocking Asynchronous Wakeup: An ultra-fast 100ms non-blocking cURL signal wakes up the background queue processor (
api/cron.php), triggering immediate delivery without delaying the checkout UI. Follow our API Integration Guide for full backend configuration.
4. Preventing Double Payments & Replay Attacks
One of the hardest challenges in peer-to-peer UPI automation is preventing bad actors from submitting the same UTR multiple times or replaying old webhook notifications to receive duplicate product deliveries.
FamGateway defends against these exploits at three distinct engineering layers:
A. Unique Order Reference Embedding in UPI QR
Every dynamic QR code generated by FamGateway encodes a unique, deterministic transaction reference note (such as FamGateway-ORD68F921B). When the customer pays, this note is permanently attached to the bank receipt, allowing our matching engine to bind the incoming payment to exactly one order.
B. Atomic Database Locks (UTR Deduplication)
The database enforces strict uniqueness on transaction UTRs. Once a UTR is recorded for an order, any subsequent attempt by a user or script to submit that same UTR for another invoice is rejected instantly with an HTTP 409 Conflict status.
C. Webhook Payload Timestamps
Every webhook payload includes a Unix timestamp field representing the exact second the event was generated. Merchant servers can verify that the timestamp is within a 5-minute tolerance window to discard stale replay attacks.
5. Standardized JSON Payload Specification
FamGateway delivers a standardized, strongly typed JSON payload across all webhook events:
{
"event": "payment.success",
"order_id": "ORD-68F921B",
"amount": "499.00",
"payable_amount": "499.00",
"status": "success",
"transaction_id": "TXN_881920394",
"utr": "423189021345",
"sender_name": "Rahul Kumar",
"payment_time": "30-08-2026 19:20:15",
"timestamp": 1788098415
}
| Field Name | Type | Description |
|---|---|---|
| event | String | Event type identifier (e.g., payment.success). |
| order_id | String | The unique merchant order ID provided during creation. |
| amount | String | Original order amount requested in INR. |
| payable_amount | String | Actual amount verified and paid by the sender. |
| status | String | Payment state (success). |
| utr | String | 12-digit official bank UPI Reference Number. |
| sender_name | String | Name of the customer who completed the UPI transfer. |
| timestamp | Integer | Unix epoch timestamp when the webhook was generated. |
6. Integration via Official FamGateway PHP SDK
Integrating webhook verification takes just a few lines of code with FamGateway.php from the official GitHub SDK:
Handling Webhooks in PHP (webhook.php)
<?php
// Include the official FamGateway PHP SDK
require_once 'FamGateway.php';
// 1. Initialize SDK with your Secret API Key
$fam = new FamGateway("sk_live_YOUR_API_KEY_HERE");
// 2. Read raw POST data and incoming signature header
$rawPostData = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_FAMGATEWAY_SIGNATURE'] ?? '';
// 3. Verify the signature securely
$data = $fam->verifyWebhook($rawPostData, $signature);
if ($data !== false) {
// Signature verified and authentic!
$event = $data['event'];
if ($event === 'payment.success') {
$orderId = $data['order_id'];
$amount = $data['amount'];
$utr = $data['utr'];
$transactionId = $data['transaction_id'];
// Execute your database fulfillment logic idempotently
// markOrderPaidInDatabase($orderId, $utr, $amount);
http_response_code(200);
echo "Webhook processed successfully.";
} else {
http_response_code(200);
echo "Event ignored.";
}
} else {
// Forged or invalid signature
http_response_code(403);
echo "Invalid signature.";
}
?>
Creating a Payment Order with Custom Webhook URL
<?php
require_once 'FamGateway.php';
$fam = new FamGateway("sk_live_YOUR_API_KEY_HERE");
// Automatically creates the order and redirects to secure checkout
$amount = 299.00;
$redirectUrl = "https://yourwebsite.com/success.php";
$customWebhookUrl = "https://yourwebsite.com/api/payment-callback.php";
$fam->createPayment($amount, $redirectUrl, $customWebhookUrl);
?>
7. Pure PHP Manual Verification (Without SDK)
If you prefer writing native PHP code without including the SDK file, here is the exact verification algorithm:
<?php
$apiKey = "YOUR_FAMGATEWAY_API_KEY";
// 1. Read raw body and signature header
$rawBody = file_get_contents("php://input");
$receivedSignature = $_SERVER['HTTP_X_FAMGATEWAY_SIGNATURE'] ?? '';
if (empty($rawBody) || empty($receivedSignature)) {
http_response_code(400);
echo json_encode(["status" => "error", "message" => "Missing payload or signature"]);
exit;
}
// 2. Compute expected HMAC-SHA256 signature
$expectedSignature = hash_hmac('sha256', $rawBody, $apiKey);
// 3. Constant-time comparison to prevent timing attacks
if (!hash_equals($expectedSignature, $receivedSignature)) {
http_response_code(401);
echo json_encode(["status" => "error", "message" => "Invalid signature"]);
exit;
}
// 4. Decode payload and fulfill order
$data = json_decode($rawBody, true);
if (($data['event'] ?? '') === 'payment.success') {
$orderId = $data['order_id'];
$utr = $data['utr'];
$amount = $data['amount'];
// Fulfill order
http_response_code(200);
echo json_encode(["status" => "success"]);
}
?>
8. Automated Exponential Retry Schedule
If your destination server is temporarily unresponsive or returns a 5xx/4xx error code, FamGateway does not discard the transaction event. The background engine manages an automated retry schedule:
| Delivery Attempt | Timing Delay | Condition | Status Outcome |
|---|---|---|---|
| Attempt 1 (Immediate) | 0 seconds | Bank email matched and verified | Completed on 2xx response |
| Attempt 2 (Retry 1) | +5 minutes | Attempt 1 timeout or non-2xx | Re-queued in scheduler |
| Attempt 3 (Retry 2) | +10 minutes | Attempt 2 timeout or non-2xx | Re-queued in scheduler |
| Attempt 4 (Final Retry) | +15 minutes | Attempt 3 timeout or non-2xx | Permanently marked Failed |
9. Developer Observability & Sandbox Testing
Inside the FamGateway Dashboard → Webhooks section, developers have access to complete testing and monitoring tools:
- Test & Verify Button: Fires a simulated sandbox payload with the signature to test server connectivity before going live.
- Live Audit Logs: Displays recent webhook history, including timestamps, raw payloads, HTTP response codes, latency, and cURL error diagnostics.
- SSRF Network Defense: Outbound deliveries to loopback (127.0.0.1) and private subnets (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) are strictly blocked.
Frequently Asked Questions
What technology stack powers the FamGateway webhook engine?
FamGateway is built on a pure PHP and MySQL architecture. It utilizes PHP's native IMAP SSL extension (port 993) to securely inspect payment receipts, AES-256-GCM for credential encryption, and an asynchronous MySQL queue (webhook_jobs) for instant event dispatch without heavy external runtimes.
Where can I find the official FamGateway PHP SDK?
The official FamGateway PHP SDK is an open-source, zero-dependency PHP library hosted on GitHub at github.com/aryanispe/famgateway-php-sdk. It allows you to create payments and verify incoming webhook signatures in a single function call.
How does FamGateway prevent double-spending and duplicate webhook executions?
FamGateway enforces double-spending prevention at two levels: First, a 5-second per-merchant atomic lockfile prevents concurrent IMAP spam. Second, incoming 12-digit bank UTRs and unique transaction reference notes are validated atomically in the MySQL database, ensuring that an already-processed UTR can never trigger a second webhook.
How do I verify incoming webhooks using the official FamGateway PHP SDK?
Using the official SDK, initialize the FamGateway class with your secret API key and call (, ). The SDK computes the HMAC-SHA256 signature, compares it using constant-time hash_equals to eliminate timing attacks, and returns the decoded JSON payload if authentic or false if forged.
What is the automated retry schedule if my server goes down?
If your endpoint times out (>10 seconds) or returns an HTTP status code outside the 200-299 range, FamGateway's queue scheduler automatically retries the delivery using an exponential backoff schedule: Attempt 1 is immediate (0s), Attempt 2 after 5 minutes, Attempt 3 after 10 minutes, and Attempt 4 after 15 minutes before marking the job permanently failed.
Ready to Automate Your Payment Workflows?
Get instant zero-fee FamPay UPI webhooks, complete REST API documentation, and direct bank settlements today.
Related Developer Guides & Resources
What is FamPay? Complete Guide to FamApp by Trio, UPI & Payments (2026)
Everything you need to know about FamPay (FamApp by Trio) in 2026: What is FamPay, how it works, under 18 a...
How to Contact FamGateway™: Official Customer Support, WhatsApp & Telegram Desk
Get instant official support for FamGateway™. Connect directly with founder Aryan Gupta (@aryanispe) on Wha...
FamGateway™ Video Tutorials: Complete YouTube Setup & Integration Guide
Watch official step-by-step video tutorials and coding guides on integrating FamGateway API, FamPay UPI aut...