Skip to main content

renox_billing/
lib.rs

1//! Subscriptions for Renox apps (Laravel Cashier): plans declared in code,
2//! free trials, upgrades and downgrades, cancellations with a grace period,
3//! with Stripe and Xendit.
4//!
5//! ```
6//! use renox::prelude::*;
7//! use renox_billing::{Billing, Interval, Plan};
8//!
9//! # let _ =
10//! App::new()
11//!     .module(Auth::new().account()) // the account page shows the subscription
12//!     .module(
13//!         Billing::new()
14//!             .plan(Plan::new("basic", "Basic").price(900, "USD", Interval::Month))
15//!             .plan(Plan::new("pro", "Pro").price(1_900, "USD", Interval::Month).trial_days(14))
16//!             .stripe(), // STRIPE_SECRET, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_BASIC, … in .env
17//!     )
18//! # ;
19//! ```
20//!
21//! A plans page (`/billing`) sends the user to the gateway's payment page;
22//! the subscription arrives by webhook (`/billing/webhooks/{gateway}`
23//! or `/billing/webhooks/{gateway}/{account}`, verified, stored once per event, applied by a queue worker) into the
24//! `subscriptions` table, and the account page shows it with "Change
25//! plan", "Cancel" and "Resume". In code, [`Billing::of`] answers
26//! `subscribed()`, `on_trial()`, `on_grace_period()` and does `checkout`,
27//! `swap`, `cancel`, `cancel_now`, `resume`, `pause` and `unpause`;
28//! [`SubscriptionRoutes::require_subscription`] guards routes. The guide is
29//! docs/billing.md in the Renox repository.
30
31#![warn(missing_docs)]
32
33use std::fmt;
34use std::sync::Arc;
35
36use renox::Config;
37use renox::auth::events::AccountDeleted;
38use renox::db::Migration;
39use renox::prelude::*;
40
41mod customer;
42pub mod events;
43pub mod gateway;
44mod guard;
45mod handlers;
46mod model;
47pub mod ngenius;
48pub mod payment;
49mod plan;
50pub mod stripe;
51mod sync;
52mod webhook;
53pub mod xendit;
54
55pub use customer::{Billable, Customer, Owner};
56pub use events::{
57    DisputeLost, DisputeOpened, DisputeWon, PaymentFailed, PaymentLinkExpired, PaymentRefunded,
58    PaymentSucceeded, RefundFailed, RefundSucceeded, SubscriptionCanceled, SubscriptionCreated,
59    SubscriptionPaused, SubscriptionUnpaused, SubscriptionUpdated,
60};
61pub use gateway::{BoxFuture, Checkout, CheckoutRequest, Gateway, Notice, Payment, Remote};
62pub use guard::SubscriptionRoutes;
63pub use model::{BillingCustomer, Subscription, SubscriptionStatus};
64pub use ngenius::Ngenius;
65pub use payment::{
66    BillingPayment, BillingRefund, Charge, ChargeRequest, DisputeState, DisputeUpdate, PaymentKind,
67    PaymentLink, PaymentPage, PaymentState, PaymentStatus, PaymentUpdate, Refund, RefundResult,
68    RefundStatus, RefundUpdate, Unsupported,
69};
70pub use plan::{Interval, Plan};
71pub use stripe::Stripe;
72pub use xendit::Xendit;
73
74const MIGRATIONS: &[Migration] = &[
75    Migration::new(
76        "00010101000900_create_billing_tables",
77        "",
78        Some(include_str!(
79            "../migrations/00010101000900_create_billing_tables.down.sql"
80        )),
81    )
82    .sqlite(
83        include_str!("../migrations/00010101000900_create_billing_tables.up.sql"),
84        None,
85    )
86    .postgres(
87        include_str!("../migrations/00010101000900_create_billing_tables.postgres.up.sql"),
88        None,
89    ),
90    Migration::new(
91        "00010101000910_create_billing_payments",
92        "",
93        Some(include_str!(
94            "../migrations/00010101000910_create_billing_payments.down.sql"
95        )),
96    )
97    .sqlite(
98        include_str!("../migrations/00010101000910_create_billing_payments.up.sql"),
99        None,
100    )
101    .postgres(
102        include_str!("../migrations/00010101000910_create_billing_payments.postgres.up.sql"),
103        None,
104    ),
105    Migration::new(
106        "00010101000920_add_gateway_intent_to_billing_payments",
107        "",
108        Some(include_str!(
109            "../migrations/00010101000920_add_gateway_intent_to_billing_payments.down.sql"
110        )),
111    )
112    .sqlite(
113        include_str!("../migrations/00010101000920_add_gateway_intent_to_billing_payments.up.sql"),
114        None,
115    )
116    .postgres(
117        include_str!(
118            "../migrations/00010101000920_add_gateway_intent_to_billing_payments.postgres.up.sql"
119        ),
120        None,
121    ),
122];
123
124/// The templates, compiled in. An app replaces one with a file of the same
125/// name under its views directory (`resources/views/billing/plans.html`).
126const VIEWS: &[(&str, &str)] = &[
127    ("billing/plans.html", include_str!("../views/plans.html")),
128    (
129        "billing/section.html",
130        include_str!("../views/section.html"),
131    ),
132];
133
134/// The billing module: plans, gateways and how changes behave. Add it next
135/// to `Auth` (with `.account()` for the subscription's card on the account
136/// page).
137#[derive(Clone)]
138pub struct Billing {
139    setup: Setup,
140}
141
142impl Default for Billing {
143    fn default() -> Self {
144        Self::new()
145    }
146}
147
148/// The module's settings, provided to the whole app (`state.provided`).
149#[derive(Clone, Default)]
150pub(crate) struct Setup {
151    pub(crate) plans: Vec<Plan>,
152    pub(crate) gateways: Vec<Arc<dyn Gateway>>,
153    pub(crate) generic_trials: bool,
154    pub(crate) prorate: bool,
155    pub(crate) redirect_to: Option<String>,
156}
157
158impl Billing {
159    /// The module, with no plan and no gateway yet. Plan changes are
160    /// prorated where the gateway does that.
161    pub fn new() -> Self {
162        Self {
163            setup: Setup {
164                prorate: true,
165                ..Setup::default()
166            },
167        }
168    }
169
170    /// Sells `plan`. Plans show in the order they're added; one with the
171    /// same key is replaced.
172    pub fn plan(mut self, plan: Plan) -> Self {
173        self.setup.plans.retain(|p| p.key != plan.key);
174        self.setup.plans.push(plan);
175        self
176    }
177
178    /// Adds Stripe, with `STRIPE_SECRET` and `STRIPE_WEBHOOK_SECRET` from
179    /// the configuration (off while the secret is missing).
180    pub fn stripe(self) -> Self {
181        self.gateway(Stripe::from_config())
182    }
183
184    /// Adds Xendit, with `XENDIT_SECRET_KEY` and `XENDIT_CALLBACK_TOKEN`
185    /// from the configuration (off while the key is missing).
186    pub fn xendit(self) -> Self {
187        self.gateway(Xendit::from_config())
188    }
189
190    /// Adds N-Genius (one-off payments only), with `NGENIUS_API_KEY`,
191    /// `NGENIUS_OUTLET_REF` and `NGENIUS_WEBHOOK_SECRET` from the
192    /// configuration (off while the API key is missing).
193    pub fn ngenius(self) -> Self {
194        self.gateway(Ngenius::from_config())
195    }
196
197    /// Adds a gateway: [`Stripe::new`] with keys given in code, or one of
198    /// your own ([`Gateway`]). One of the same name is replaced. Plans
199    /// without [`Plan::via`] use the first gateway that is set up.
200    pub fn gateway(mut self, gateway: impl Gateway) -> Self {
201        self.setup.gateways.retain(|g| g.name() != gateway.name());
202        self.setup.gateways.push(Arc::new(gateway));
203        self
204    }
205
206    /// Offers plans' free trials without a payment method ("Start free
207    /// trial" next to "Subscribe"); the days left carry over when the user
208    /// subscribes.
209    pub fn generic_trials(mut self) -> Self {
210        self.setup.generic_trials = true;
211        self
212    }
213
214    /// Plan changes take effect without charging or crediting the rest of
215    /// the period.
216    pub fn without_proration(mut self) -> Self {
217        self.setup.prorate = false;
218        self
219    }
220
221    /// Where users go after subscribing, changing plan or canceling (by
222    /// default the account page, else `/`).
223    pub fn redirect_to(mut self, path: impl Into<String>) -> Self {
224        self.setup.redirect_to = Some(path.into());
225        self
226    }
227}
228
229impl fmt::Debug for Billing {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        f.debug_struct("Billing")
232            .field(
233                "plans",
234                &self.setup.plans.iter().map(|p| &p.key).collect::<Vec<_>>(),
235            )
236            .field(
237                "gateways",
238                &self
239                    .setup
240                    .gateways
241                    .iter()
242                    .map(|g| g.name().to_owned())
243                    .collect::<Vec<_>>(),
244            )
245            .finish_non_exhaustive()
246    }
247}
248
249impl Setup {
250    /// The plan `key`; a refusal naming it otherwise.
251    pub(crate) fn plan(&self, key: &str) -> Result<&Plan> {
252        self.plans
253            .iter()
254            .find(|p| p.key == key)
255            .ok_or_else(|| Error::BadRequest(format!("There's no plan `{key}`.")))
256    }
257
258    /// The gateway `name`, when its keys are set.
259    pub(crate) fn gateway(&self, state: &AppState, name: &str) -> Option<Arc<dyn Gateway>> {
260        self.gateways
261            .iter()
262            .find(|g| g.name() == name && g.configured(&state.config))
263            .cloned()
264    }
265
266    /// The gateway named `name` (the first configured one without a name)
267    /// for a one-off payment.
268    pub(crate) fn payment_gateway(
269        &self,
270        state: &AppState,
271        name: Option<&str>,
272    ) -> Result<Arc<dyn Gateway>> {
273        let found = match name {
274            Some(name) => self.gateway(state, name),
275            None => self
276                .gateways
277                .iter()
278                .find(|g| g.configured(&state.config))
279                .cloned(),
280        };
281        found.ok_or_else(|| {
282            renox::anyhow::anyhow!(
283                "no payment gateway is set up{}: set its keys in .env",
284                name.map(|n| format!(" for `{n}`")).unwrap_or_default()
285            )
286            .into()
287        })
288    }
289
290    /// The gateway that sells `plan`.
291    pub(crate) fn gateway_for(&self, state: &AppState, plan: &Plan) -> Result<Arc<dyn Gateway>> {
292        let found = match &plan.gateway {
293            Some(name) => self.gateway(state, name),
294            None => self
295                .gateways
296                .iter()
297                .find(|g| g.configured(&state.config))
298                .cloned(),
299        };
300        found.ok_or_else(|| {
301            renox::anyhow::anyhow!(
302                "no payment gateway is set up for the plan `{}`: set its keys in .env \
303                 (STRIPE_SECRET, XENDIT_SECRET_KEY, …)",
304                plan.key
305            )
306            .into()
307        })
308    }
309
310    /// The plan whose price id at `gateway` is `price`.
311    pub(crate) fn plan_by_price(
312        &self,
313        config: &Config,
314        gateway: &str,
315        price: &str,
316    ) -> Option<&Plan> {
317        self.plans
318            .iter()
319            .find(|p| p.price_id_for(gateway, config).as_deref() == Some(price))
320    }
321}
322
323/// The module's settings, as the module provided them.
324pub(crate) fn setup(state: &AppState) -> Result<Arc<Setup>> {
325    state.provided::<Setup>().ok_or_else(|| {
326        renox::anyhow::anyhow!("renox-billing: add the module with App::module(Billing::new()…)")
327            .into()
328    })
329}
330
331impl Module for Billing {
332    fn name(&self) -> &'static str {
333        "billing"
334    }
335
336    fn migrations(&self) -> &'static [Migration] {
337        MIGRATIONS
338    }
339
340    fn routes(&self) -> Routes {
341        handlers::routes()
342    }
343
344    fn register(&self, app: &mut Registry) {
345        app.provide(self.setup.clone());
346        app.webhook::<webhook::BillingWebhook>();
347        app.templates(|env| {
348            for (name, source) in VIEWS {
349                // The app's own file of that name wins.
350                if env.get_template(name).is_err() {
351                    renox::view::add_template(env, *name, *source)
352                        .expect("a built-in template compiles");
353                }
354            }
355        });
356        app.command(
357            "billing:expire-links",
358            "Expire payment links that ran out unpaid",
359            |_args, state| async move {
360                let expired = Billing::expire_links(&state).await?;
361                println!("Expired {expired} payment links.");
362                Ok(())
363            },
364        );
365        app.schedule()
366            .hourly("billing:expire-links", |state| async move {
367                Billing::expire_links(&state).await.map(|_| ())
368            });
369        app.account_section("billing/section.html", 30, |user, state| async move {
370            let setup = setup(&state)?;
371            let billing = Billing::of(&state, &user);
372            let current = match billing.subscription().await? {
373                Some(s) => Some(handlers::Current::of(&state, &setup, &billing, s).await?),
374                None => None,
375            };
376            Ok(renox::serde_json::json!({
377                "current": current,
378                "plans_url": state.url("billing.plans", &[])?,
379            }))
380        });
381        // A deleted account's subscriptions end at the gateway too.
382        app.listen(|e: AccountDeleted, state| async move {
383            forget(&state, &Owner::new("user", e.user_id)).await
384        });
385        // Recorded in the activity log when the app has the `Audit` module.
386        app.listen(|e: SubscriptionCreated, state| async move {
387            let s = &e.subscription;
388            audit(&state, s.owner(), "billing.subscribed", s, None).await
389        })
390        .listen(|e: SubscriptionCanceled, state| async move {
391            let s = &e.subscription;
392            audit(&state, s.owner(), "billing.canceled", s, None).await
393        })
394        .listen(|e: PaymentFailed, state| async move {
395            match (&e.owner, &e.subscription) {
396                (Some(owner), Some(s)) => {
397                    audit(
398                        &state,
399                        owner.clone(),
400                        "billing.payment_failed",
401                        s,
402                        Some(e.amount),
403                    )
404                    .await
405                }
406                _ => Ok(()),
407            }
408        });
409    }
410}
411
412/// Ends `owner`'s running subscriptions at their gateways (a failure is
413/// logged) and deletes their billing rows.
414async fn forget(state: &AppState, owner: &Owner) -> Result {
415    let setup = setup(state)?;
416    for subscription in Subscription::of(&state.db, owner).await? {
417        if subscription.ended() || subscription.gateway_id.is_none() {
418            continue;
419        }
420        if let Some(gateway) = setup.gateway(state, &subscription.gateway)
421            && let Err(err) = gateway.cancel(state, &subscription, false).await
422        {
423            tracing::warn!(error = ?err, subscription = subscription.id, "billing: couldn't cancel a deleted account's subscription");
424        }
425    }
426    for table in ["subscriptions", "billing_customers"] {
427        renox::db::sql(format!(
428            "DELETE FROM {table} WHERE billable_type = ? AND billable_id = ?"
429        ))
430        .bind(owner.kind.as_str())
431        .bind(owner.id)
432        .execute(&state.db)
433        .await?;
434    }
435    Ok(())
436}
437
438/// Records a user's billing change when the app has the `Audit` module.
439async fn audit(
440    state: &AppState,
441    owner: Owner,
442    action: &str,
443    subscription: &Subscription,
444    amount: Option<i64>,
445) -> Result {
446    if owner.kind != "user" {
447        return Ok(());
448    }
449    let has_log = renox::db::sql("SELECT COUNT(*) FROM audit_logs WHERE 1 = 0")
450        .scalar::<i64>(&state.db)
451        .await
452        .is_ok();
453    if has_log {
454        let entry =
455            renox::audit::Entry::new(action)
456                .user(owner.id)
457                .data(renox::serde_json::json!({
458                    "plan": subscription.plan,
459                    "gateway": subscription.gateway,
460                    "amount": amount,
461                }));
462        renox::audit::record(&state.db, entry).await?;
463    }
464    Ok(())
465}
466
467/// Compiles the Rust in docs/billing.md (the guide) as doctests.
468#[cfg(doctest)]
469#[doc = include_str!("../../../docs/billing.md")]
470pub struct Guide;