返回资讯中心
外部精选
软件工程
#开发者实时流

使用 Chargebee 和 Razorpay 构建订阅计费(附代码示例)

来源标题:Building Subscription Billing with Chargebee and Razorpay (With Code Samples)

PresenceWave 近期上线了付费方案,并分享了其订阅计费的构建方式:文章介绍了计费模型、支付流程、使用 Chargebee 和 Razorpay 时遇到的意外之处,以及容易被忽视的印度税务细节。他们还开源了一个精简版代码骨架 saas-billing-chargebee(Spring Boot、MIT 许可、含无需数据库或 Chargebee 账户即可运行的单元测试)。团队位于印度、面向全球销售:Razorpay 处理印度卡、国际卡及印度储备银行(RBI)的定期扣款规则;Chargebee 提供托管结账、自助服务门户、符合 GST 要求的发票和催款功能。最关键的设计决策是所有支付页面都由 Chargebee 托管,结账、支付未付发票、更新卡片和计费门户均为跳转,卡信息不经过自家服务器,因此无需承担 PCI 相关工作。计费对象是账户而非单个网站:每个账户只有一个订阅,方案包含一定数量

Hacker News 最新sushrutb2026/12/3 · 今天21 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

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.

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.

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:

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.

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:

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:

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.

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:

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 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.

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.

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:

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.

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:

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.)

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

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.

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

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.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →