Build Your Own Razorpay Subscriptions Clone in Plain Python
The problem
Seven parts in, you know the words. Plan, mandate, pre-debit notification, dunning, webhook. You can draw the state machine from memory.
But knowing the words is not the same as knowing where the bugs hide. The fastest way to find them is to build the thing yourself and watch it break.
So we did. This part is a small clone of the subscription side of Razorpay, called mini-pay. It is written in plain Python with no framework, plus one small JavaScript checkout widget. It runs on a laptop, and there is a live copy you can click through right now.
- Live demo shop: mini-pay-blogllm.vercel.app
- Live dashboard: mini-pay-blogllm.vercel.app/dashboard
- Code, MIT licence: github.com/NafiGit/mini-pay
It is test mode only. No real money, no real cards, no call to any payment provider. It only accepts its own test card numbers and test UPI ids. A real looking card number is refused before it is even sent.
What we actually ran
Being clear about this matters more than any feature list.
| What | Where | How |
|---|---|---|
| 37 unit tests | this VM | python3 -m unittest, all pass |
| Six scenarios (trial, failed renewal, webhook replay, upgrade, coupon, refund) | this VM | scripts/scenarios.py, output pasted below |
| Click through in a real browser (14 steps) | this VM, local server | headless Chromium via Playwright, 14 of 14 passed |
| Full API walk with curl (19 steps) | the live Vercel deploy | scripts/demo_curl.sh, all steps returned what they should |
| Forged webhook against the live deploy | the live Vercel deploy | curl, rejected with HTTP 400 |
One thing we could not do: drive the live Vercel site with a headless browser. The browser on our VM cannot reach outside sites. So the widget was clicked through in a real browser locally, and the live site was tested with curl, which hits the same code. If you open the live demo yourself, you are the first real browser to try it.
The shape of it
flowchart LR Shop[Merchant page with checkout.js] ==>|POST /checkout/api/pay| API[api.py router] Backend[Merchant backend] ==>|/v1/... with key id and secret| API API ==> E[engine.py] E ==> B[billing.py: subscriptions, invoices, dunning] E ==> P[payments.py: orders, refunds, settlements] E ==> W[webhooks.py: signed events, retries] B ==> N[network.py: test cards and UPI ids] P ==> N E ==> C[clock.py: simulated time] E ==> S[(store.py: SQLite)] W ==>|signed POST| R[Receiver: examples/receiver.py]
Three ideas carry the whole design.
A fake clock. Nothing in mini-pay reads the real time. The clock starts at 1 January 2027 and only moves when you tell it to. That is how a seven day trial converts in under a second, and why the run logs below are dated 2027. Billing bugs are almost always time bugs, so owning the clock is the single most useful choice in the project.
A fake network. network.py is the pretend bank. Card 4111 1111 1111 1111 works. 4000 0000 0000 0002 is declined. 4000 0000 0000 9995 approves the mandate but fails every renewal. The UPI id low_balance@mini has Rs 600 in it, enough for one Rs 499 charge and not two. Every failure in this post is one of those on purpose.
One config file. Every number lives in minipay/config.py with a comment saying where it came from. The ones that mirror real rules point at the rule: the Rs 15,000 per debit limit without extra authentication is from RBI's E-mandate Framework, 2026, para 8(a). The 24 hour pre-debit notice is para 6(a). The ones that are just teaching values say so: the 2% fee and T+2 settlement are placeholders, not Razorpay's pricing.
Run one: a free trial that converts
This is the flow from part 1. A Rs 499 monthly plan, a 7 day trial made by setting start_at seven days ahead, approved with UPI AutoPay.
text=== scenario a: trial_converts (simulated clock, UTC) === 2027-01-01 00:00 >> create subscription: Pro Monthly Rs 499, 12 cycles, start_at = now + 7 days (free trial) 2027-01-01 00:00 >> sub_BsEYRVrv10O3bl status=created; customer opens /checkout/sub_BsEYRVrv10O3bl and approves UPI AutoPay on success@mini 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 refund Rs 5.00 on pay_t9YS70jMWk6OJt (full) 2027-01-01 00:00 webhook refund.processed -> 200 accepted 2027-01-01 00:00 mandate approved (upi); free until 2027-01-08 00:00 2027-01-01 00:00 webhook subscription.authenticated -> 200 accepted 2027-01-01 00:00 >> authorisation payment pay_t9YS70jMWk6OJt: Rs 5.00, status refunded 2027-01-01 00:00 >> advance the clock 7 days 2027-01-03 00:00 settlement setl_00OYWvGVaGlS3W on 2027-01-03 00:00: gross Rs 5.00 - fee Rs 0.10 - GST on fee Rs 0.02 - refunds Rs 5.00 = Rs 0.00 (Rs 0.12 carried to the next one) 2027-01-03 00:00 webhook settlement.processed -> 200 accepted 2027-01-07 00:00 pre-debit notice: Rs 499.00 will be debited on 2027-01-08 00:00 2027-01-08 00:00 webhook payment.captured -> 200 accepted 2027-01-08 00:00 cycle 1/12 paid Rs 499.00 (Pro Monthly); next charge 2027-02-08 00:00 2027-01-08 00:00 webhook invoice.paid -> 200 accepted 2027-01-08 00:00 webhook subscription.activated -> 200 accepted 2027-01-08 00:00 webhook subscription.charged -> 200 accepted 2027-01-08 00:00 >> advance the clock 31 days 2027-01-10 00:00 settlement setl_29cneUlsvFlOLF on 2027-01-10 00:00: gross Rs 499.00 - fee Rs 9.98 - GST on fee Rs 1.80 - refunds Rs 0.00 - carried Rs 0.12 = Rs 487.10 2027-01-10 00:00 webhook settlement.processed -> 200 accepted 2027-02-07 00:00 pre-debit notice: Rs 499.00 will be debited on 2027-02-08 00:00 2027-02-08 00:00 webhook payment.captured -> 200 accepted 2027-02-08 00:00 cycle 2/12 paid Rs 499.00 (Pro Monthly); next charge 2027-03-08 00:00 2027-02-08 00:00 webhook invoice.paid -> 200 accepted 2027-02-08 00:00 webhook subscription.charged -> 200 accepted 2027-02-08 00:00 >> status=active paid_count=2 remaining_count=10 Invoices invoice | status | period | amount | of which GST | discount inv_X78WOwNHmawadN | paid | 2027-01-08 to 2027-02-08 | Rs 499.00 | Rs 76.12 | Rs 0.00 inv_nL5siESfyc6uUi | paid | 2027-02-08 to 2027-03-08 | Rs 499.00 | Rs 76.12 | Rs 0.00
Read it top to bottom and the whole series is in there. The Rs 5 authorisation transaction is captured and refunded at once, as Razorpay's workflow page describes for future start subscriptions. The subscription sits in authenticated for the trial. A day before the first debit, the pre-debit notice goes out. On day 7 the first real Rs 499 is captured and the status flips to active.
Two details we only noticed by running it:
- The Rs 5 still costs the merchant. The settlement on 3 January shows a fee and GST on fee for the Rs 5, and then the refund wipes out the gross. The 12 paise of fees is carried into the next payout. With our placeholder fee that is tiny, but it is real money on every trial, at any scale.
- The invoice includes GST. Rs 499 is GST inclusive here, so Rs 76.12 of it is tax at a flat 18%. Real GST has place of supply rules this clone does not model. Ask a chartered accountant, not a blog.

Run two: a renewal fails, retries, then halts
Now the case from part 5. The customer pays the first month from low_balance@mini, which then cannot cover the second.
text=== scenario b: renewal_fails_halted (simulated clock, UTC) === 2027-01-01 00:00 >> create subscription: Pro Monthly Rs 499, starts now; customer approves low_balance@mini (balance Rs 600.00) 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 cycle 1/12 paid Rs 499.00 (Pro Monthly); next charge 2027-02-01 00:00 2027-01-01 00:00 webhook invoice.paid -> 200 accepted 2027-01-01 00:00 webhook subscription.activated -> 200 accepted 2027-01-01 00:00 webhook subscription.charged -> 200 accepted 2027-01-01 00:00 >> advance the clock 40 days 2027-01-03 00:00 settlement setl_7k0CyPz4OhZQfB on 2027-01-03 00:00: gross Rs 499.00 - fee Rs 9.98 - GST on fee Rs 1.80 - refunds Rs 0.00 = Rs 487.22 2027-01-03 00:00 webhook settlement.processed -> 200 accepted 2027-01-31 00:00 pre-debit notice: Rs 499.00 will be debited on 2027-02-01 00:00 2027-02-01 00:00 payment pay_AbCcrzMNLTPIzD failed: insufficient_funds 2027-02-01 00:00 webhook payment.failed -> 200 accepted 2027-02-01 00:00 attempt 1 failed (insufficient_funds): pending, next try 2027-02-02 00:00 2027-02-01 00:00 webhook subscription.pending -> 200 accepted 2027-02-02 00:00 payment pay_G3OvhQT6eYssyG failed: insufficient_funds 2027-02-02 00:00 webhook payment.failed -> 200 accepted 2027-02-02 00:00 attempt 2 failed (insufficient_funds): pending, next try 2027-02-03 00:00 2027-02-02 00:00 webhook subscription.pending -> 200 accepted 2027-02-03 00:00 payment pay_TnVmiVOLiQWDjP failed: insufficient_funds 2027-02-03 00:00 webhook payment.failed -> 200 accepted 2027-02-03 00:00 attempt 3 failed (insufficient_funds): pending, next try 2027-02-04 00:00 2027-02-03 00:00 webhook subscription.pending -> 200 accepted 2027-02-04 00:00 payment pay_nk7EF0Q0UCDLu9 failed: insufficient_funds 2027-02-04 00:00 webhook payment.failed -> 200 accepted 2027-02-04 00:00 attempt 4 failed (insufficient_funds): halted 2027-02-04 00:00 webhook subscription.halted -> 200 accepted 2027-02-10 00:00 >> status=halted paid_count=1 Payments payment | at | amount | status | error pay_YNN1hkatfsJMA9 | 2027-01-01 00:00 | Rs 499.00 | captured | pay_AbCcrzMNLTPIzD | 2027-02-01 00:00 | Rs 499.00 | failed | insufficient_funds pay_G3OvhQT6eYssyG | 2027-02-02 00:00 | Rs 499.00 | failed | insufficient_funds pay_TnVmiVOLiQWDjP | 2027-02-03 00:00 | Rs 499.00 | failed | insufficient_funds pay_nk7EF0Q0UCDLu9 | 2027-02-04 00:00 | Rs 499.00 | failed | insufficient_funds 2027-02-10 00:00 >> customer tops up and pays the open invoice from the hosted page 2027-02-10 00:00 webhook payment.captured -> 200 accepted 2027-02-10 00:00 cycle 2/12 paid Rs 499.00 (Pro Monthly); next charge 2027-03-01 00:00 2027-02-10 00:00 webhook invoice.paid -> 200 accepted 2027-02-10 00:00 webhook subscription.activated -> 200 accepted 2027-02-10 00:00 webhook subscription.charged -> 200 accepted 2027-02-10 00:00 >> status=active
That is Razorpay's documented card schedule: fail at T, retry on T+1, T+2 and T+3, and after the fourth failure in a row the subscription is halted. Each failed try fires payment.failed and another subscription.pending, so a merchant who sends an email on every subscription.pending would have sent four. That is worth knowing before you write that handler.

The code that decides all of this is short enough to read in one go:
pythondef _dunning(self, sub, pay): sub["failed_attempts"] += 1 n = sub["failed_attempts"] if n == 1: sub["first_failed_at"] = self.now() if pay["error_code"] == "authentication_required": sub.update(status="pending", retry_at=None) # only the customer can fix this one elif n <= len(config.DUNNING_RETRY_OFFSETS): sub.update(status="pending", retry_at=sub["first_failed_at"] + config.DUNNING_RETRY_OFFSETS[n - 1]) else: sub.update(status="halted", retry_at=None) self.save(sub) self.log("sub", f"attempt {n} failed ({pay['error_code']}): halted", subscription_id=sub["id"]) return self.emit("subscription.halted", subscription=sub) self.save(sub)
The retry ladder is a plain list of offsets, an idea taken from Kill Bill in part 7. Running off the end of the list means halted. There is no clever state here, which is the point.
One branch is easy to miss. A debit above the mandate's no extra authentication limit fails with authentication_required, and retrying it is useless: the bank will say no every time until the customer approves it. So that case goes to pending with no retry date at all.
Run three: a forged webhook gets rejected
The part 4 attacks, run for real against the demo shop's receiver.
text=== scenario c: webhook_replay_rejected (simulated clock, UTC) === 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 cycle 1/12 paid Rs 499.00 (Pro Monthly); next charge 2027-02-01 00:00 2027-01-01 00:00 webhook invoice.paid -> 200 accepted 2027-01-01 00:00 webhook subscription.activated -> 200 accepted 2027-01-01 00:00 webhook subscription.charged -> 200 accepted 2027-01-01 00:00 >> captured one real delivery: evt_QopMn5CwFPAu4d, X-MiniPay-Signature 90ded1261d65a7d4... 2027-01-01 00:00 >> attacker replays the exact same request 2027-01-01 00:00 webhook subscription.charged -> 200 rejected: duplicate event id (replay), not processed again 2027-01-01 00:00 >> attacker changes the amount in the body and keeps the old signature 2027-01-01 00:00 webhook ? -> 400 rejected: bad signature 2027-01-01 00:00 >> attacker signs a forged body with a guessed secret 2027-01-01 00:00 webhook ? -> 400 rejected: bad signature 2027-01-04 00:00 >> 3 days later the receiver restarts and forgets its seen ids; the same request is replayed 2027-01-04 00:00 webhook subscription.charged -> 400 rejected: stale event (older than the replay window)
Four attacks, four different defences:
| Attack | Caught by | Response |
|---|---|---|
| Same request sent twice | event id already seen | 200, not processed again |
| Amount changed, old signature kept | HMAC over the raw body | 400 |
| Body signed with a guessed secret | HMAC again | 400 |
| Replay after the receiver forgot its ids | event older than the window | 400 |
The duplicate answers 200 on purpose. Gateways deliver at least once, so a duplicate is usually not an attack at all, just a retry. Saying "got it" stops the gateway from retrying again. Saying 4xx would make it try harder.
The last row is the subtle one. Remembering every event id forever does not scale, so the receiver forgets ids after two days. Without the age check, an old and validly signed event could be replayed the moment its id was forgotten. The window has to be longer than the gateway's own 24 hour retry period, or real retries would be refused.
We also sent a forged event to the live deploy:
text$ curl -s -X POST https://mini-pay-blogllm.vercel.app/demo/webhook \ -H 'X-MiniPay-Signature: deadbeef' -H 'X-MiniPay-Event-Id: evt_forged000001' \ -d '{"event":"subscription.charged","payload":{}}' { "result": "rejected: bad signature" } HTTP 400
The checkout widget
Razorpay merchants add checkout.js to a page, open a modal, and get back a payment id, an order or subscription id and a signature. mini-pay copies that shape with static/checkout.js. The demo shop uses it like this:
javascriptpost("/demo/create_order").then(function (o) { // the server creates the order with its secret key new MiniPay({ key: o.key_id, order_id: o.order_id, name: "Demo shop", description: "E-book: How Payments Work", prefill: { email: "customer@example.com" }, handler: function (resp) { // never trust this alone: verify on the server post("/demo/verify", resp).then(function (v) { var el = document.getElementById("buy-status"); el.className = "status " + (v.verified ? "paid" : ""); el.textContent = v.verified ? "Paid. Signature verified for " + resp.minipay_payment_id : "Signature check FAILED"; }); }, modal: { ondismiss: function () { document.getElementById("buy-status").textContent = "Checkout closed"; } } }).open(); });

The modal has three tabs. Card takes only the test numbers. UPI has a collect flow, where you type a test UPI id, and a QR flow, where a "Simulate scan & pay" button plays the part of your phone. Netbanking shows a pretend bank page with Success and Failure buttons.

The browser handler is the part people get wrong. Anyone can call a JavaScript function with made up values, so the handler only passes the result to the server, and the server checks the signature with the secret key. The recipe is the one Razorpay documents: HMAC SHA256 of order_id|payment_id for a one time payment, or payment_id|subscription_id for a subscription.
pythondef checkout_message(payment_id, order_id=None, subscription_id=None, payment_link_id=None): if order_id: return order_id + "|" + payment_id if subscription_id: return payment_id + "|" + subscription_id return payment_link_id + "|" + payment_id def verify(message, signature, secret): return hmac.compare_digest(sign(message, secret), str(signature or ""))
hmac.compare_digest instead of == is not decoration. A plain comparison can stop at the first wrong character, and the time that takes can leak how much of a guess was right.
The local browser test clicked through all of this:
textPASS merchant page loads with TEST MODE banner PASS Buy opens the widget modal with its own TEST MODE banner PASS Luhn valid non-test card refused in the browser PASS declined test card shows the decline and keeps the modal open PASS test card 4111 pays, handler posts to /demo/verify, page shows Paid PASS UPI tab shows a simulated QR for the mandate PASS Simulate scan & pay approves the mandate: subscription authenticated, webhook received PASS skip ahead 8 days: trial converts to active, subscription.charged webhook received PASS netbanking Failure button fails the payment PASS netbanking Success button pays the order PASS closing the modal calls modal.ondismiss PASS hosted /checkout/{sub_id} page opens the widget by itself PASS dashboard renders tables PASS no JavaScript errors on any page: none
Upgrades, coupons and refunds
Three more scenarios run the money rules from part 6. The upgrade is the interesting one:
text=== scenario d: upgrade_proration (simulated clock, UTC) === 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 cycle 1/12 paid Rs 499.00 (Pro Monthly); next charge 2027-02-01 00:00 2027-01-01 00:00 webhook invoice.paid -> 200 accepted 2027-01-01 00:00 webhook subscription.activated -> 200 accepted 2027-01-01 00:00 webhook subscription.charged -> 200 accepted 2027-01-01 00:00 >> advance the clock 10 days 2027-01-03 00:00 settlement setl_yvt3xZCGQGDBdT on 2027-01-03 00:00: gross Rs 499.00 - fee Rs 9.98 - GST on fee Rs 1.80 - refunds Rs 0.00 = Rs 487.22 2027-01-03 00:00 webhook settlement.processed -> 200 accepted 2027-01-11 00:00 >> upgrade to Pro Plus Monthly Rs 999, schedule_change_at=now 2027-01-11 00:00 webhook payment.captured -> 200 accepted 2027-01-11 00:00 webhook invoice.paid -> 200 accepted 2027-01-11 00:00 plan changed to Pro Plus Monthly: credit Rs 338.03, charged Rs 660.97; next charge 2027-02-11 00:00 2027-01-11 00:00 webhook subscription.updated -> 200 accepted proration: {"days_in_cycle": 31, "change_day": 11, "days_unused": 21, "credit": 33803, "new_amount": 99900, "net": 66097} Upgrade invoice line items line | amount Pro Plus Monthly | Rs 999.00 Credit: 21 unused days of Pro Monthly | Rs -338.03 Total charged now (GST inclusive) | Rs 660.97 of which GST at 18% | Rs 100.83 2027-01-11 00:00 >> advance the clock 31 days 2027-01-13 00:00 settlement setl_XasdoubJbvnwGL on 2027-01-13 00:00: gross Rs 660.97 - fee Rs 13.22 - GST on fee Rs 2.38 - refunds Rs 0.00 = Rs 645.37 2027-01-13 00:00 webhook settlement.processed -> 200 accepted 2027-02-10 00:00 pre-debit notice: Rs 999.00 will be debited on 2027-02-11 00:00 2027-02-11 00:00 webhook payment.captured -> 200 accepted 2027-02-11 00:00 cycle 2/12 paid Rs 999.00 (Pro Plus Monthly); next charge 2027-03-11 00:00 2027-02-11 00:00 webhook invoice.paid -> 200 accepted 2027-02-11 00:00 webhook subscription.charged -> 200 accepted Invoices invoice | status | period | amount | of which GST | discount inv_LgWYTcYeMxnLef | paid | 2027-01-01 to 2027-02-01 | Rs 499.00 | Rs 76.12 | Rs 0.00 inv_8BVq1uHsKK9x92 | paid | 2027-01-11 to 2027-02-11 | Rs 660.97 | Rs 100.83 | Rs 0.00 inv_aGcQN5Kh4U74SN | paid | 2027-02-11 to 2027-03-11 | Rs 999.00 | Rs 152.39 | Rs 0.00

The credit uses Razorpay's documented formula: the old price per day, times the days not yet used, counting the change day as unused. One honest difference: when you upgrade with "change now", mini-pay starts a fresh cycle on the upgrade day and charges the full new price minus the credit. Razorpay's own example in part 6 keeps the old cycle dates and charges only for the days left. Both are defensible. Ours is simpler to read, and it means the next renewal moves to the 11th. Pick one on purpose in your own system, and tell customers which one it is.
The coupon run gives 50% off for two cycles, then goes back to full price on cycle three:
text=== scenario e: coupon_half_two_cycles (simulated clock, UTC) === 2027-01-01 00:00 >> offer offer_VYkvAFvtZBrwHz: 50% off for 2 cycles 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 cycle 1/12 paid Rs 249.50 (Pro Monthly); next charge 2027-02-01 00:00 2027-01-01 00:00 webhook invoice.paid -> 200 accepted 2027-01-01 00:00 webhook subscription.activated -> 200 accepted 2027-01-01 00:00 webhook subscription.charged -> 200 accepted 2027-01-01 00:00 >> advance the clock 62 days 2027-01-03 00:00 settlement setl_U7acqUITe8kJkl on 2027-01-03 00:00: gross Rs 249.50 - fee Rs 4.99 - GST on fee Rs 0.90 - refunds Rs 0.00 = Rs 243.61 2027-01-03 00:00 webhook settlement.processed -> 200 accepted 2027-01-31 00:00 pre-debit notice: Rs 249.50 will be debited on 2027-02-01 00:00 2027-02-01 00:00 webhook payment.captured -> 200 accepted 2027-02-01 00:00 cycle 2/12 paid Rs 249.50 (Pro Monthly); next charge 2027-03-01 00:00 2027-02-01 00:00 webhook invoice.paid -> 200 accepted 2027-02-01 00:00 webhook subscription.charged -> 200 accepted 2027-02-03 00:00 settlement setl_xcSKYRTSmsFODH on 2027-02-03 00:00: gross Rs 249.50 - fee Rs 4.99 - GST on fee Rs 0.90 - refunds Rs 0.00 = Rs 243.61 2027-02-03 00:00 webhook settlement.processed -> 200 accepted 2027-02-28 00:00 pre-debit notice: Rs 499.00 will be debited on 2027-03-01 00:00 2027-03-01 00:00 webhook payment.captured -> 200 accepted 2027-03-01 00:00 cycle 3/12 paid Rs 499.00 (Pro Monthly); next charge 2027-04-01 00:00 2027-03-01 00:00 webhook invoice.paid -> 200 accepted 2027-03-01 00:00 webhook subscription.charged -> 200 accepted 2027-03-03 00:00 settlement setl_ddPRnFBkf2Yd84 on 2027-03-03 00:00: gross Rs 499.00 - fee Rs 9.98 - GST on fee Rs 1.80 - refunds Rs 0.00 = Rs 487.22 2027-03-03 00:00 webhook settlement.processed -> 200 accepted Invoices invoice | status | period | amount | of which GST | discount inv_VsTfFHBawt7Fki | paid | 2027-01-01 to 2027-02-01 | Rs 249.50 | Rs 38.06 | Rs 249.50 inv_0wMY2X1MlcGJwx | paid | 2027-02-01 to 2027-03-01 | Rs 249.50 | Rs 38.06 | Rs 249.50 inv_kSYFtFLMNHmKvM | paid | 2027-03-01 to 2027-04-01 | Rs 499.00 | Rs 76.12 | Rs 0.00
And a one time order plus a partial refund, landing in one settlement:
text=== scenario f: refund_and_settlement (simulated clock, UTC) === 2027-01-01 00:00 >> order order_mx8xf5ZM2iUzjK Rs 199 for an e-book, paid by card 4111 (auto capture) 2027-01-01 00:00 webhook payment.authorized -> 200 accepted 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 webhook order.paid -> 200 accepted 2027-01-01 00:00 >> a Rs 499 subscription starts on success@mini 2027-01-01 00:00 webhook payment.captured -> 200 accepted 2027-01-01 00:00 cycle 1/12 paid Rs 499.00 (Pro Monthly); next charge 2027-02-01 00:00 2027-01-01 00:00 webhook invoice.paid -> 200 accepted 2027-01-01 00:00 webhook subscription.activated -> 200 accepted 2027-01-01 00:00 webhook subscription.charged -> 200 accepted 2027-01-01 00:00 >> advance the clock 1 day 2027-01-02 00:00 >> partial refund of Rs 50 on pay_O6cSOG3Rpp2d9K 2027-01-02 00:00 refund Rs 50.00 on pay_O6cSOG3Rpp2d9K (partial) 2027-01-02 00:00 webhook refund.processed -> 200 accepted 2027-01-02 00:00 >> advance the clock 2 days 2027-01-03 00:00 settlement setl_UGcHhuXoF2fn9m on 2027-01-03 00:00: gross Rs 698.00 - fee Rs 13.96 - GST on fee Rs 2.51 - refunds Rs 50.00 = Rs 631.53 2027-01-03 00:00 webhook settlement.processed -> 200 accepted 2027-01-04 00:00 >> payment pay_O6cSOG3Rpp2d9K: status captured, refund_status partial Settlements settlement | gross | fee | GST on fee | refunds | paid out | utr setl_UGcHhuXoF2fn9m | Rs 698.00 | Rs 13.96 | Rs 2.51 | Rs 50.00 | Rs 631.53 | SIMUTR7YXAS9EW62
Notice that the Rs 50 refund comes out of the payout. The fee on the refunded Rs 50 does not come back. That matches what part 1 said about refunds and fees, and it is the kind of thing you only feel when the numbers are in front of you.
Running it on Vercel
The live copy runs as a single Vercel Python function. vercel.json sends every path to api/index.py, which reuses the same request handler as the local server. No framework, no build step.
json{ "functions": { "api/index.py": { "includeFiles": "{minipay,examples,static}/**" } }, "rewrites": [ { "source": "/(.*)", "destination": "/api/index" } ] }
The catch is storage. A serverless function has no disk that survives, so the live demo keeps its SQLite file in /tmp. That file disappears whenever the function cold starts, and two instances would not share it. For a demo where data should reset anyway, that is fine. For anything real it is wrong: you would swap store.py for Postgres or similar. The store only has five methods, so that is a small job. Everyone using the live demo also shares one simulated clock, so if the dates jump while you are clicking, someone else pressed "Skip ahead".
What mini-pay leaves out
A clone this size has to skip things. These are the big ones:
- Real banks and networks. No NPCI, no card schemes, no actual mandate registration. Everything in
network.pyis a lookup table. - Real GST. One flat 18% rate. No place of supply, no CGST and SGST split, no SAC codes.
- UPI's own retry rules. The dunning ladder is the card one. Part 2 covers how UPI AutoPay limits retries and blocks peak hours. mini-pay does not model either.
- Concurrency and scale. One process, one lock. Good enough for a laptop.
- Disputes and chargebacks. Not there at all.
If any of those is what you need, read part 7 again and look at Lago, Kill Bill and Hyperswitch. They have spent years on exactly these.
Try it
bashgit clone https://github.com/NafiGit/mini-pay cd mini-pay python3 -m unittest discover -s tests -p 'test_*.py' # 37 tests python3 scripts/scenarios.py b # the failed renewal run python3 -m minipay.server # then open http://127.0.0.1:8090
Then break it on purpose. Shorten DUNNING_RETRY_OFFSETS to one day and watch subscriptions halt faster. Set RECEIVER_WINDOW_SECONDS below 24 hours and watch real webhook retries get refused as stale. Each of those is a real decision a billing team makes, and now you can see what it costs.
What's next
That is the end of the series. If you skipped ahead, start at part 1, the glossary told as the story of one Rs 499 subscription. Every term in this post links back to it. The full series is at How Subscriptions Work.
Sources
- mini-pay source code (MIT)
- Razorpay: Subscription workflow
- Razorpay: Subscription states
- Razorpay: Subscription payment retries
- Razorpay: Test subscriptions
- Razorpay: Update a subscription
- Razorpay: Webhooks
- Razorpay: Webhook best practices
- Razorpay: Validate and test webhooks
- RBI: Digital Payments, E-mandate Framework, 2026
- Python docs: hmac.compare_digest
- Vercel docs: Python runtime
- killbill/killbill at killbill-0.25.7
