← Back to Blog

How We Built Subscription Billing with Chargebee and Razorpay (and Open-Sourced the Skeleton)

How We Built Subscription Billing with Chargebee and Razorpay (and Open-Sourced the Skeleton)

We recently switched on paid plans at PresenceWave. Billing is the kind of feature where every shortcut eventually costs you a support ticket, an angry email or a tax problem. So we want to share how we built it: the model, the flows, the parts of Chargebee and Razorpay that surprised us, and the Indian tax details nobody warns you about.

We've also open-sourced a cleaned-up skeleton of the code: saas-billing-chargebee, Spring Boot, MIT licensed, with unit tests that run without a database or a Chargebee account.

The stack, and why

  • Chargebee runs subscriptions, invoices, tax, dunning (retrying failed payments) and billing emails.
  • Razorpay is the payment gateway, connected inside Chargebee. Our app never holds Razorpay keys.
  • Our app (Spring Boot) keeps a cached copy of each account's billing state and turns it into what the product cares about.

We're based in India and sell worldwide. Razorpay handles Indian cards, international cards and RBI's recurring-payment rules. Chargebee gives us hosted checkout, a self-serve portal, GST-ready invoices and dunning, so we didn't have to build any of them.

The most important decision: every payment screen is a Chargebee-hosted page. Checkout, paying an unpaid invoice, updating a card and the billing portal are all redirects. Card details never touch our servers, so there's no PCI work on our side.

The model in one paragraph

We bill the account, not each website. An account has one subscription: a plan that includes a number of domains (we call them slots), plus an optional extra-slot add-on. The product needs exactly one number from billing: how many domains this account may have. Domains are just occupants of slots. Adding, deleting or swapping a domain never touches billing as long as a slot is free.

That one decision made everything else simpler. Here's what each concern looks like:

ConcernWhere it lives
Prices, bundles, promos, couponsChargebee catalog
How many slots a plan givesMetadata on the Chargebee price, e.g. {"slots": 3}
Renewals, failed payments, retries, receiptsChargebee
Taxes and invoicesChargebee (with two India-specific fixes, below)
"May this account add another domain?"Our app, from a cached slot count

Launch pricing is Starter at $29/month or $199/year with one domain, and extra domains at the same price each. In India the prices are ₹2,499/month or ₹14,999/year, tax included everywhere. A new promo is a new price in Chargebee with the right metadata, with no code change and no deploy.

Rule one: never trust the webhook

Chargebee tells you about changes through webhooks. The tempting design is a handler per event type: subscription_created does this, payment_failed does that. We didn't do that.

Every event becomes "re-sync this customer." The handler finds the customer the event is about, then calls the same sync method we use everywhere else. That method re-reads the customer and subscription from Chargebee's API and writes our copy:

@Transactional
public SyncResult sync(AccountBilling billing) {
  String before = snapshot(billing);
  chargebee.retrieveCustomer(billing.getChargebeeCustomerId()).ifPresent(this::applyCustomer);
  Subscription subscription = findSubscription(billing);
  if (subscription != null) {
    apply(billing, subscription);           // status, plan, slots, term dates
  }
  AccountBilling saved = repository.save(billing);
  entitlements.setSlotLimit(saved.getAccountId(), saved.paidSlots());
  return new SyncResult(saved, !before.equals(snapshot(saved)));
}

What this buys us:

  • Duplicates and retries don't matter. Syncing twice gives the same result. We still record each event id, so a redelivered event is a no-op, but correctness doesn't depend on it.
  • Order doesn't matter. If payment_succeeded arrives before subscription_created, both syncs end in the same state.
  • Lost events don't matter. A nightly job re-syncs every subscribed account and logs anything that changed. The return from a hosted checkout also syncs immediately, so the customer sees their new plan without waiting for the webhook.
  • One code path to test. The webhook, the checkout return and the nightly reconcile all call the same method.

Two smaller details:

  • Chargebee doesn't sign webhooks. You configure basic-auth credentials on the endpoint instead, and we check them in constant time.
  • The webhook stores no payload. It holds names and addresses, and the sync doesn't need it.

Our own customer ids

When we create a Chargebee customer we choose its id: a fixed prefix plus our account id. It looks minor, but it fixes two real problems:

  1. A retried create can't make a second customer. It fails with "already exists", which we treat as success.
  2. A checkout we never saw return can still be matched. If the customer closes the tab right after paying, the webhook still names their customer id, and the prefix tells us which account it belongs to.

The trial lives in our app

New accounts get a 30-day trial with no card, and nothing exists in Chargebee during the trial. When they choose a plan early, we pass the trial's end date to the hosted checkout as the subscription's trial_end. Chargebee asks for the card now but charges when the trial would have ended, so choosing early costs nothing.

The checkout also pre-fills enough extra slots for the domains the customer already has, so nobody goes over their limit by paying.

When a trial ends without a plan, or a paid plan ends (cancelled, or retries ran out), we don't cut anyone off. An expired trial keeps its sites for 8 days, and an ended plan for 30. After that a nightly job switches off the account's custom domains and widgets. The dashboard stays open the whole time, so the customer can choose a plan and be back online at once.

Slots, and why we built our own "add a slot" dialog

We wanted every new slot to come with 30 days free. Chargebee's portal would apply standard proration instead, so slots are added through our own dialog, using the card Chargebee already holds:

  1. Raise the add-on quantity without proration. The slot works immediately and is billed in full from the next renewal.
  2. Cover the time until that renewal. With D the days until the renewal and T the days in the current term:
    • More than 30 days to go (a yearly plan, usually): charge now for the days after the free month, price × (D − 30) / T.
    • 30 days or fewer (monthly plans always): charge nothing now, and add Chargebee promotional credit for the rest of the 30 days, applied to the next invoice.

Two examples:

  • Yearly plan, renewing in 107 days. We charge $199 × 77 / 365 = $41.98 now, rounded down to $41.
  • Monthly plan, renewing in 8 days. Nothing now, and $29 × 22 / 30 = $21.27 of credit, rounded down to $21.

We round down to whole dollars (or rupees), skip anything under $5 (₹500), and send an idempotency key so a double click charges once. If the small charge fails, the customer keeps the slot and Chargebee's dunning chases the invoice. That's billing that is generous rather than exact. It costs us a few dollars now and then, and it removes a whole class of support conversations.

Removing a slot is scheduled for the end of the term, only allowed while a slot is unused, and never refunded.

The portal bug that would have billed 12× too much

The one Chargebee behaviour that genuinely surprised us showed up in local testing. A customer on a monthly plan with an extra slot switches to yearly in Chargebee's self-serve portal. The plan moves to the yearly price, but the add-on keeps its monthly price, and Chargebee bills it for every month of the yearly term: $348 a year for a slot that should cost $199.

The fix:

  • Turn plan changes (and add-on quantity changes) off in the portal settings.
  • Plan changes go through a hosted page we create with checkout_existing_for_items, which sends the complete new list of items: the new plan and the extra slots on the new plan's slot price.

It's still a hosted page, so there's still no card data on our side. If you use Chargebee add-ons that follow the plan's period, test this before launch.

Indian cards: INR, e-mandates and "unpaid but not failed"

Selling from India adds a few rules you won't find in most billing tutorials.

Indian cards pay in INR. Razorpay can't charge Indian cards in USD. So the billing country decides the currency: India pays in INR, everyone else in USD. It's not the browser's location, because people travel and use VPNs. Before a customer enters billing details, we show a preview in the currency their time zone suggests. Once they've paid, the currency is locked, because a Chargebee customer stays in one currency.

Recurring charges go through RBI's e-mandate rules:

  • The customer approves a mandate with an OTP when they subscribe, with a ceiling of ₹15,000 per automatic charge.
  • Each charge waits about a day after the invoice for a pre-debit notice.
  • During that wait the invoice is unpaid, but nothing has failed.

Our first version marked those accounts "payment failed" for a day. Now the sync checks whether each unpaid invoice already has a payment in progress, and if so the account stays active:

boolean paymentInProgress = subscription.dueInvoicesCount() > 0
      && chargebee.unpaidInvoicesHavePaymentInProgress(subscription.id());

The ₹15,000 ceiling is also why our yearly INR price sits below it.

GST: two things Chargebee doesn't do for you

If you're registered for GST, Chargebee's India tax engine handles CGST, SGST and IGST. Two details still needed code.

1. Place of supply. Indian tax invoices must show the place of supply. For a customer in India that's their state with its GST code, like "Maharashtra (27)", and for an export it's "Outside India". Chargebee doesn't derive it from the address. We created a customer custom field, show it on invoices, and every sync fills it from the billing address. It writes only when the value changes, and a failure is logged without stopping the sync.

2. Exports. Services sold to customers outside India can be zero-rated under a Letter of Undertaking (LUT). Chargebee supports this, but only for customers explicitly marked as located outside India. So the sync sets that mark for any billing country other than India and clears it if the address moves to India.

One trap here: the API call that sets the mark, update_billing_info, clears every billing field you don't send. Send only the mark, and you've erased the customer's address and GSTIN. Our client reads the customer first and sends everything back with the change.

Ask for billing details before checkout. Our first version let checkout collect the address, which meant the very first invoice was created before we could set the place of supply or the export mark. Now the dashboard asks for the billing details first:

  • company name and address;
  • for India, the state and an optional GSTIN.

We check the GSTIN's format and check character, and that its first two digits match the chosen state. Then we set everything on the customer before checkout starts, so the first invoice is right, trial or not. (As always with tax, check your setup with your accountant.)

Who gets billed

Not every account is a self-serve customer, so each account has a plan kind:

KindMeaning
STANDARDSelf-serve: trial, then a Chargebee subscription. The sync sets the slots.
MANAGEDA deal agreed directly (an agency, say). We set the slots; the sync never touches them.
INTERNALOur own accounts.
GRANDFATHEREDCustomers from before billing, who keep what they had for free.

A database migration started every existing account as grandfathered, so on the day billing shipped nobody was charged and nothing changed. A deal can also be billed through Chargebee: a private price with {"slots": 25} and the account ids it's offered to in its metadata shows up in that account's plan picker only.

Rolling it out safely

  • A kill switch. BILLING_MODE is OFF, ALLOWLIST or ON. OFF hides every billing screen, ignores webhooks and idles the jobs, without a deploy.
  • A real-money check first. In ALLOWLIST mode, only listed test accounts were billed. They bought hidden $1 and ₹100 test plans with real cards. We confirmed the charges, receipts, webhooks, slot credits, cancel and reactivate, then archived the test prices.
  • Replaying events locally. A small script pulls recent events from Chargebee's API and posts them to the local webhook, so testing needs no tunnel. It also makes duplicate and out-of-order delivery easy to try.
  • Chargebee's Time Machine on the test site moves the clock forward to test renewals, dunning and end-of-term changes in minutes instead of months.

What we'd tell you before you start

  1. Bill the account, and give the product a single number. Everything else can stay in Chargebee.
  2. Make every webhook a re-sync, and add a nightly reconcile. You'll never debug event ordering.
  3. Use hosted pages for anything involving a card.
  4. Choose your own customer ids, and send idempotency keys on anything that charges.
  5. Test plan changes with add-ons before you launch.
  6. If you sell from India, plan for INR, e-mandates, the place of supply and the export mark from day one, and collect billing details before checkout.
  7. Be generous with rounding. A few dollars is cheaper than a support ticket.

The code

The skeleton is at github.com/JulioLabs/saas-billing-chargebee:

  • the Chargebee client;
  • the sync, the webhook and the slot pricing;
  • trial and grace handling;
  • the GST helpers.

It's written so your product only implements one interface:

public interface Entitlements {
  void setSlotLimit(String accountId, int slots);
  void setServing(String accountId, boolean serving);
}

It's reference code to read and adapt, not a drop-in library. Bring your own authentication, frontend and job locking. Questions and pull requests are welcome.

If you'd rather not build any of this and just want your business online, that's what PresenceWave is for.