Technical
ERPNext Payment Gateway Integration: UPI, Webhooks, Reconciliation
How a UPI-first payment gateway connects to ERPNext through Payment Gateway Account, Payment Request and Payment Entry, why the webhook must be the source of truth, and how to reconcile net settlements against gross invoices.
Kalvyai Engineering · · Updated · 8 min read

On this page
Connecting a payment gateway to ERPNext takes more than showing a pay button. The payment has to land on the right invoice, exactly once, and the money that reaches your bank days later has to match what you booked. This post covers how those pieces fit together in ERPNext, using UPI-first gateways common in India as the example.
The code samples target recent Frappe/ERPNext versions. Method names and fields can shift between versions, so check them against the version you run.
The four moving parts
A gateway integration in ERPNext touches four things. Knowing what each one does makes debugging much easier.
1. Payment Gateway Account
This record links a gateway (Cashfree, PayU and so on) to a ledger account and a currency. When a payment succeeds, the resulting Payment Entry debits the account you set here. You can find it by searching "Payment Gateway Account" in the awesome bar.
The account you choose matters for reconciliation (covered below). We recommend a dedicated clearing account per gateway, not your main bank account.
2. Payment Request
A Payment Request is ERPNext's "please pay this" document. It references a Sales Order or Sales Invoice, holds the amount and currency, and produces a payment URL for the customer. You can create one from the Sales Order or Sales Invoice, and the Webshop checkout creates one automatically.
The Payment Request is the anchor for the whole flow. The gateway order you create should carry the Payment Request name so that every later event can be traced back to it.
3. Payment Entry
When the payment is confirmed, ERPNext creates a Payment Entry of type Receive. It allocates the amount against the referenced invoice or order and posts the accounting: debit the gateway account, credit the customer's receivable.
Payment Entry has Reference No and Reference Date fields. For UPI payments, store the gateway transaction ID or the bank UTR there. You will need it during reconciliation.
4. Bank Reconciliation
Days later, the gateway settles money into your bank. That settlement is one bank line covering many customer payments, minus fees and GST on those fees. ERPNext's Bank Transaction records and Bank Reconciliation Tool are where you match that line to what you booked.
How a UPI payment flows end to end
Here is the typical sequence for a customer paying an invoice by UPI.
- A Payment Request is created for Sales Invoice
SINV-0042. - Your integration calls the gateway's create-order API, passing the Payment Request name as the order reference and the exact amount and currency.
- The customer opens the checkout page and pays with a UPI app, a QR code or a UPI ID.
- The customer is redirected back to your site. This redirect may or may not happen.
- The gateway sends a server-to-server webhook to your ERPNext site with the final status.
- Your webhook handler verifies the request, checks the amount, and marks the Payment Request as paid. ERPNext creates the Payment Entry against
SINV-0042. - On settlement day, the gateway pays the net amount into your bank, and you reconcile it.
Steps 4 and 5 are where most production bugs live.
Why the webhook must be the source of truth
It is tempting to mark the invoice paid when the customer lands back on your "thank you" page. With UPI this is unreliable for several reasons.
- The customer approves the payment in another app. They often switch to their UPI app, approve, and never come back to the browser tab. No redirect, no confirmation.
- Payments can stay pending. The bank may take time to confirm. The redirect can arrive while the status is still pending.
- A "failed" payment can later succeed. The gateway may report a late success after an initial failure or timeout.
- Webhooks are retried. If your server is slow or returns an error, the gateway sends the same event again. You will receive duplicates.
- The redirect URL can be tampered with. Anything that comes through the customer's browser is untrusted.
So treat the redirect as a UI hint only ("we are confirming your payment") and let the signed webhook decide. Back it up with a status poll for anything the webhook misses.
Writing a safe webhook handler
In Frappe, a webhook endpoint is a whitelisted method that allows guest access, because the gateway does not log in. That makes signature verification mandatory.
The example below shows the shape of a handler. The header names and signature scheme are an example of the common HMAC-SHA256 pattern.
import base64
import hashlib
import hmac
import json
import frappe
from frappe.utils import flt
@frappe.whitelist(allow_guest=True, methods=["POST"])
def gateway_webhook():
raw = frappe.request.get_data()
signature = frappe.get_request_header("x-webhook-signature") or ""
timestamp = frappe.get_request_header("x-webhook-timestamp") or ""
secret = frappe.conf.get("gateway_webhook_secret")
signed = timestamp.encode() + raw
expected = base64.b64encode(
hmac.new(secret.encode(), signed, hashlib.sha256).digest()
).decode()
if not signature or not hmac.compare_digest(expected, signature):
frappe.local.response.http_status_code = 401
return {"ok": False}
event = parse_event(json.loads(raw)) # map your gateway's payload
if event["status"] != "SUCCESS":
return {"ok": True}
pr_name = event["order_reference"]
status = frappe.db.get_value(
"Payment Request", pr_name, "status", for_update=True
)
if status == "Paid":
return {"ok": True, "duplicate": True}
pr = frappe.get_doc("Payment Request", pr_name)
if flt(event["amount"]) != flt(pr.grand_total) or event["currency"] != pr.currency:
frappe.log_error(f"Amount mismatch for {pr_name}", "Gateway webhook")
return {"ok": True}
frappe.set_user(frappe.conf.get("gateway_integration_user"))
pr.run_method("on_payment_authorized", "Completed")
return {"ok": True}What each part protects against:
- Raw body for the signature. Verify against the exact bytes received, not a re-serialised JSON object. Re-serialising changes whitespace and key order and breaks the HMAC.
- Constant-time comparison.
hmac.compare_digestavoids timing leaks. - Row lock plus status check.
for_update=Truelocks the Payment Request row for the transaction, so two simultaneous deliveries of the same event cannot both create a Payment Entry. - Amount and currency check. Never trust that the paid amount equals what you asked for. A mismatch should go to a human, not be booked silently.
- A dedicated integration user. Run the posting as a limited user rather than Administrator, so the audit trail shows clearly that the integration created the entry.
- Return 200 for events you deliberately ignore. Otherwise the gateway keeps retrying them.
on_payment_authorized on the Payment Request is the hook ERPNext's own gateway integrations use to mark the request paid and create the Payment Entry.
Two more practices worth adopting:
- Log every webhook payload before processing, for example in Frappe's Integration Request doctype or a custom log. When a customer says "I paid", this is the first place you look.
- Keep the handler fast. If posting is slow, verify and log the event, push the rest into a background job with
frappe.enqueue, and return quickly so the gateway does not time out and retry.
Add a status poll as a safety net
Webhooks get lost: a deploy restarts the server, a firewall rule changes, or the gateway has an incident. A scheduled job that checks pending Payment Requests against the gateway's order-status API closes that gap.
# hooks.py
scheduler_events = {
"cron": {
"*/15 * * * *": ["my_app.payments.poll.check_pending_requests"]
}
}The job should select Payment Requests that are still waiting for payment and were created within a recent window, call the gateway's status API for each, and run them through the same function the webhook uses. One code path for both means one set of rules for idempotency and amount checks.
Reconciling settlements: gross in, net out
This is where accounts teams feel the pain. Customers pay the gross amount. The gateway settles the net amount after deducting its fee and the GST on that fee, and it batches many payments into one bank credit.
A clearing account handles this cleanly. Using illustrative figures:
- 50 customers pay a total of ₹2,00,000 on Monday.
- The gateway deducts fee F and GST on the fee G.
- On settlement day your bank receives ₹2,00,000 − F − G as one credit.
The postings look like this:
- At payment time (automatic). Each Payment Entry debits Gateway Clearing and credits the customer. Clearing now holds ₹2,00,000.
- At settlement (from the settlement report). One Journal Entry debits Bank for the net amount, debits Payment Gateway Charges for F, debits Input GST for G, and credits Gateway Clearing for ₹2,00,000.
- Bank reconciliation. Import the bank statement as Bank Transactions and match the settlement credit to that Journal Entry in the Bank Reconciliation Tool.
If everything is settled, the clearing account balance equals payments received but not yet settled. A balance that keeps growing points to a missed settlement, a refund booked in the wrong place, or a payment booked twice.
Confirm the GST treatment of gateway fees with your accountant.
The gateway's settlement report is the key input here. Each line usually carries the order reference you sent, which is your Payment Request name, so you can match settlement lines to Payment Entries automatically rather than by eye.
Refunds
Refunds run in the opposite direction and need the same care.
- Raise the refund from ERPNext against the original payment, so there is a record of who approved it and why.
- Call the gateway's refund API with a unique refund ID you generate, so a retried call cannot refund twice.
- Wait for the refund webhook or poll the refund status. UPI refunds are not always instant.
- Book the accounting: typically a Credit Note against the invoice and a Payment Entry of type Pay to the customer through the clearing account. The gateway then deducts the refund from a later settlement.
Go-live checklist
- Webhook URL configured in the gateway dashboard and reachable over HTTPS.
- Webhook secret stored in site config, not in code or a doctype field visible to every user.
- Signature verification tested with a tampered payload. It must be rejected.
- The same webhook sent twice in a row creates exactly one Payment Entry.
- Amount mismatch is logged and alerted, not booked.
- Status poll running and using the same processing function as the webhook.
- Separate clearing account per gateway, set on the Payment Gateway Account.
- One full cycle tested in the gateway's sandbox: pay, settle, refund, reconcile.
Ready-made apps
If you would rather not build this from scratch, our ERPNext apps cover common Indian gateways:
- Cashfree Payments for ERPNext lets you take UPI, card, net banking and wallet payments in ERPNext with Cashfree.
- PayU Payments for ERPNext lets you collect and refund PayU India payments without leaving ERPNext.
- Multi Payment Gateway for ERPNext lets Webshop customers choose how to pay, using any payment gateway installed on your site.
All our apps are listed at store.kalvyai.com.
How Kalvyai can help
We build and connect ERPNext systems, including payment gateway integrations, webhook handling, settlement imports and reconciliation setups that your accounts team can trust. If you have a gateway that is not yet connected, payments that do not match your bank, or a clearing account nobody can explain, get in touch and we will look at it with you.
Last updated 28 Nov 2026
- ERPNext
- Payment Gateway
- UPI
- Webhooks
- Reconciliation
- Frappe
- India
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment