10 min read
|
Published
|
Updated

Polygon Webhooks: Real-Time On-Chain Events

How Polygon webhooks work, what to watch for on PoS (reorgs, confirmations, duplicates), and how to build a safe, idempotent deposit handler for USDC and POL.

Chapters
C
Chaingateway Team
Blockchain Experts

Reviewed by Maurice Sobiera

Geometric event path from ledger to webhook

A Polygon webhook is an HTTP callback that a service sends to your server when something happens on the Polygon chain, such as a USDC deposit reaching one of your addresses. You register a URL, the provider watches the chain, and your backend receives a signed POST instead of polling an RPC node. This guide covers handler design and Polygon edge cases.

TL;DR

  • A webhook replaces polling: the provider watches Polygon and pushes events (deposits, transfers, token movements) to your endpoint.
  • Polygon finalizes transactions within seconds, but you still need a confirmation policy before crediting funds.
  • Treat every delivery as possibly duplicated, late or out of order: verify the signature, store the event ID, and process idempotently.
  • Acknowledge fast, do the work in a queue, and reconcile against the chain on a schedule. Chaingateway does not retry failed notifications automatically.
  • Chaingateway Webhooks deliver HMAC-signed Polygon events with the sender, recipient, token contract and amount already decoded, so you skip running nodes and parsing logs.

What is a Polygon webhook?

Polygon PoS is an EVM chain. Every ERC-20 transfer, whether USDC, USDT or a token you issued yourself, emits a Transfer log. Native POL moves as a value transfer, not as an ERC-20 Transfer log. Raw RPC gives you both in different shapes: logs for tokens, transaction data for native coins. If you want to know that a customer paid, you have to assemble that picture yourself.

A webhook service does the assembly. You subscribe to an address (or a set of them), and when a matching event occurs the service sends a JSON payload to your URL. A useful payload tells you the transaction hash, sender, recipient, token contract, amount, block number and a unique event identifier. That is the difference between “here is a log with hex topics” and “customer 4812 paid 250 USDC”.

Three things people search for under this keyword are really three different tools:

  • Address and payment webhooks: notify me when funds hit these addresses. This is what payment flows need.
  • Contract event webhooks: notify me when a given smart contract emits a given event. This is what dApp backends and analytics need.
  • Protocol-level webhooks: notifications from a Polygon product itself about its own operations. Those belong to that product’s documentation, not to a general chain listener.

This article is about the first kind, with notes on the second.

Why do webhooks beat polling on Polygon?

If you poll an RPC endpoint for new blocks and filter logs yourself, you face a trade-off with no good answer:

  • Poll every few seconds and you burn through rate limits and pay for mostly empty responses.
  • Poll every minute and your customer stares at a spinner for a minute after paying.
  • Miss a range after a restart and you have a silent gap in your ledger.

Webhooks flip this. The provider carries the watching and the block bookkeeping. Your job shrinks to running one endpoint that handles events correctly. We go deeper on the architecture trade-offs in our post on webhooks vs WebSockets, including the ingest, queue and fan-out pattern we recommend.

How many confirmations do I need on Polygon?

Wait for finality, which Polygon reaches within seconds. A webhook that fires on first sight of a transaction is fast, but it is not final. Before you release goods or credit a balance, decide what you wait for.

The Polygon finality documentation says that deterministic finality is achieved in 2 to 5 seconds since the Heimdall v2 upgrade. Milestones provide this finality without waiting for a checkpoint on Ethereum. A finalized block is irreversible, so there is no reorganization risk after that point. You can query the most recent finalized block with the standard eth_getBlockByNumber method and the "finalized" block tag.

A practical way to choose is to tie the policy to the value at risk:

Payment sizeSuggested handlingReasoning
Small (digital goods, tips)Credit on first event, mark as “pending”Fast UX, low loss if a rare reorg happens
Medium (subscriptions, top-ups)Credit after a modest block depthBalanced
Large (invoices, withdrawals)Credit only when the block is finalizedReorg risk matters more than speed

This table is our suggested policy, not a Polygon rule. Pick numbers that match your own risk tolerance and write them down.

In your data model, give each incoming payment a status such as detected, confirming and final. Show the customer the first state immediately and move funds only on the last. Store the block number from the first event. On a timer, compare it with the number of the latest finalized block, and move the payment to final when the finalized block has passed it.

What does a safe Polygon webhook handler look like?

The Polygon developer docs include a guide on receiving webhooks for one of Polygon’s own products. Its principles apply to every webhook integration: verify the delivery, and apply it without double-processing or applying stale state. The OWASP Webhook Security Cheat Sheet lists the same points. Here is the same discipline for chain events.

1. Verify the signature before anything else

Anyone who finds your URL can POST to it. Without verification, an attacker can send a fake “250 USDC received” and walk away with your product. Reject unsigned or badly signed requests with a 401 and do not parse the body further.

Chaingateway signs webhooks with HMAC-SHA256. The X-Signature header holds the Base64-encoded HMAC of the transaction ID (txid) from the payload, computed with your personal secret as the key. Recompute it and compare the two values with a constant-time comparison. The signature documentation has code for several languages, and our post on a new feature to enhance webhook security explains the setup.

2. Make processing idempotent

Assume that a notification can arrive more than once, for example when you resend a failed one. Store a unique key per event, ideally the transaction hash, or the event ID the provider supplies. Put a unique constraint on it in your database:

INSERT INTO processed_events (event_key, received_at)
VALUES ($1, now())
ON CONFLICT (event_key) DO NOTHING;

If the insert affects zero rows, you have seen this event. Return 200 and stop. Do the insert and the balance update in the same database transaction so a crash cannot leave one without the other.

3. Acknowledge fast, work later

Return a 2xx as soon as the event is verified and safely stored. Do the slow work, such as emailing the customer, updating ledgers and calling other services, from a queue. If your handler is slow, the sender can time out, and you will be debugging failed notifications.

4. Do not trust order

Two events about the same payment can arrive in either order, for example a confirmation update before the original detection. Compare block numbers or sequence fields and ignore anything older than the state you already hold. Never let a late “detected” event overwrite a “final” record.

5. Validate what the payload claims

Check that the recipient is an address you issued, that the token contract is one you accept, and that the amount matches the invoice. This matters on Polygon more than people expect, because anyone can deploy a token named “USDC” and send it to your address. Compare contract addresses, never symbols.

6. Plan for failure

Your server will be down at some point. Decide in advance how you recover:

  • Check the list of failed notifications. Chaingateway does not retry them automatically. It lists them at GET /api/v2/polygon/webhooks/notifications/failed, and you resend each one with POST /api/v2/polygon/webhooks/notifications/{id}/retry.
  • Run a reconciliation job, for example every few minutes, that checks balances or recent transfers for your addresses and flags anything your webhook log never saw.
  • Alert when no events arrive for an unusually long time. On a busy system, silence is a signal.

Webhooks are your fast path. Reconciliation is your safety net. Run both.

Which tokens and edge cases matter on Polygon?

USDC and USDT. Stablecoin payments are the main reason developers set up Polygon webhooks, because fees are low and settlement is quick. Make sure you know which contract each stablecoin uses on Polygon and allow only those addresses, as described above.

Native POL. POL is the native token of Polygon Chain, according to the Polygon documentation. Native transfers are not ERC-20 Transfer events, so a listener built only on those events will miss them. In the Chaingateway Polygon webhook API, the type filter accepts MATIC, ERC20 and ERC721. The MATIC value is the native coin type, so test it before you rely on it for POL payments.

Contract-to-address payments. A payment may come from a smart contract wallet or a multisig, not a plain account. Do not assume the sender is the customer. Link payments to customers by the receiving address you generated for them, not by the sender.

Failed and reverted transactions. A reverted transaction consumes gas but moves nothing. Only act on events that represent successful transfers.

Dust and spam tokens. Unsolicited tokens regularly show up in addresses. Ignore contracts you did not whitelist.

Do and avoid list for Polygon tokens: whitelist stablecoin contracts, confirm native POL is reported, link customers by receiving address and act only on successful transfers; do not assume the sender is the customer, listen only for token events, accept unlisted contracts or act on reverted transactions

Should I build it myself or use a unified API?

There are three realistic routes to Polygon event notifications:

  1. Run your own node and listener. Maximum control, but you own node upgrades, storage growth, log decoding, reorg handling and uptime. Sensible when chain infrastructure is your product.
  2. Use a general-purpose node or data provider and write the filtering yourself. Less operational burden, but you still build subscriptions, retries, decoding and the signature layer.
  3. Use a payments-focused API that delivers decoded, signed events. You write the endpoint and the business logic, nothing else.

For a team that wants to accept or send crypto in its product, the third route usually reaches production fastest. We compare the options in more depth in Blockchain APIs compared: 6 types and when to use each.

Our perspective: webhooks are a ledger problem, not a notification problem

Most integration bugs we see are not about receiving the HTTP request. They are about what happens after. Teams treat a webhook as a trigger (“payment arrived, ship it”) when it is really one input to a ledger that has to stay correct under retries, reorgs and restarts.

Three cards titled Ledger, Replay test and HMAC: retries, reorgs and restarts threaten correctness, replay one event ten times and shuffle three, and sign every request to reject forgeries

That shapes how we build Chaingateway. We deliver decoded events, so your code reads an amount and a token contract, not hex-encoded log topics. We sign every webhook with HMAC so your endpoint can reject forgeries. And we cover Polygon next to Ethereum, Tron, Bitcoin, Solana, BNB Chain and Arbitrum through one REST API, so your handler logic stays the same when you add a second chain.

Our advice: write your idempotency and reconciliation code first, before the happy path. If you can replay the same event ten times and shuffle three events and end up with the right balance, the rest is easy. Our write-up on processing deposits automatically with webhooks walks through that flow end to end.

— Bitblade

How do I get Polygon webhooks with Chaingateway?

With Chaingateway Webhooks you create wallets or register addresses through the API, subscribe to payment events and receive signed notifications at your endpoint. The Polygon API page covers sending and receiving USDC and USDT on Polygon, and the Blockchain API covers wallets, transfers, decoded transactions and gas prices across supported chains.

Create a webhook with POST /api/v2/polygon/webhooks. It needs a url and at least one of from or to. You can filter by type and contractaddress, and set a reference of up to 255 characters, such as your order number. Add the header X-Network: testnet to try it on the test network.

Terminal window
curl -X POST https://app.chaingateway.io/api/v2/polygon/webhooks \
-H "Authorization: Bearer $CHAINGATEWAY_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
"url": "https://example.com/hooks/polygon",
"type": "ERC20",
"contractaddress": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
"reference": "order-1042"
}'

The contract address in this example is the native USDC contract on Polygon PoS, as listed in Circle’s contract address documentation.

Plans are published on the pricing page:

PlanMonthlyYearly
Plus€49 per month€490 per year
Pro€99 per month€990 per year
Premium€249 per month€2,490 per year
Enterprise€499 per month€4,990 per year

Paid access starts after a free trial, so you can test the full flow, including signature checks and duplicate handling, before you commit.

A launch checklist

Before you point production traffic at your endpoint, run through this:

  • HTTPS only, with a valid certificate.
  • X-Signature verified against the txid, with a constant-time comparison.
  • Unique constraint on the event key.
  • 2xx returned within a couple of seconds, work moved to a queue.
  • Contract addresses allowed by a list, amounts and recipients validated.
  • Status model with pending and final states, and a documented confirmation threshold.
  • Reconciliation job and an alert for missing events.
  • Secrets stored outside the repo and rotatable without downtime.
  • A replay test: send the same event several times, and out of order, in staging.

Sources

Frequently asked questions

It depends on the provider. Token transfers emit logs that are easy to track, while native transfers need transaction-level monitoring. In the Chaingateway Polygon webhook API the type filter accepts MATIC, ERC20 and ERC721, so test the native coin type with a small transfer before you rely on it for POL payments.

There is no single rule, but Polygon finalizes quickly. The Polygon finality documentation says milestones typically finalize a transaction within 2 to 5 seconds, and the finalized block tag returns the latest irreversible block. Small payments are often credited earlier as pending. Match the threshold to the amount at risk.

The notification is not sent again automatically. Chaingateway lists failed notifications, and you resend each one through the retry endpoint. Run your own reconciliation job as well, which compares your records with the chain, so that gaps do not stay unnoticed.

Assume it can, for example when you resend a failed notification. Store a unique event key with a database constraint and return 200 for events you have already processed.

How we write these articles

Ready to build this yourself? Get your API key — 7-day trial, no card required — or see the Polygon API for the full endpoint reference.

C
Chaingateway Team
Blockchain Experts

The Chaingateway team is dedicated to simplifying blockchain integration for developers worldwide.