Laravel Cashier turns Stripe billing into a few method calls. Subscribe a customer, cancel at period end, send someone to Checkout, listen for a webhook. The PHP package has done this for years. Laravel Rust did not have an equivalent. rupirate-cashier is that equivalent, written from scratch in Rust for laravel-rust.
It is a fluent wrapper over the Stripe HTTP API. It covers customers, subscriptions, Checkout, the billing portal, invoices, and webhooks. It follows the shape of Laravel Cashier, so if you know Cashier in PHP, the Rust version reads the same way.
You can install it from crates.io: rupirate-cashier 0.2.0. The source lives in the rupirate repo on GitHub, under rupirate/rupirate-cashier/.
Install
From crates.io:
[dependencies] rupirate-cashier = "0.2.0" From a local checkout of the repo:
[dependencies] rupirate-cashier = { path = "../rupirate-cashier" } Then register the provider:
Application::configure().with_providers(|providers| { providers.add(rupirate_cashier::CashierServiceProvider); }) Set two environment variables:
STRIPE_SECRET=sk_test_... STRIPE_WEBHOOK_SECRET=whsec_... The package keeps no local subscription tables. Stripe is the source of truth. The structs in the crate are the Stripe objects themselves, with the status helpers Cashier adds. There is no offline mode. Without a Stripe key, every API call fails with a clear message.
Two more settings are optional:
| Env var | Default | What it does |
|---|---|---|
CASHIER_CURRENCY | usd | Default currency |
CASHIER_WEBHOOK_TOLERANCE | 300 | Max webhook timestamp age, in seconds |
A worked example: subscribe, listen, check
Here is the whole flow. A customer subscribes to a price. Stripe sends a webhook when the subscription is created. Your app checks the subscription when the customer visits a paid page.
First, subscribe the customer:
use laravel::container::Inject; use rupirate_cashier::Cashier; async fn start_subscription(cashier: Inject<Cashier>) -> laravel::Result<()> { let subscription = cashier.subscribe("cus_123", "price_monthly").await?; assert!(subscription.active()); Ok(()) } Then handle the webhook. The provider already registers POST /stripe/webhook. You only write a listener:
use laravel::event::{listener, Event}; use rupirate_cashier::{WebhookEvent, WebhookReceived}; #[listener] pub async fn handle_subscription(event: Event<WebhookReceived>) -> laravel::Result<()> { if let WebhookEvent::SubscriptionCreated(subscription) = &event.event { // Grant access for `subscription.customer`. // `subscription.metadata.get("user_id")` tells you which local user. } if let WebhookEvent::SubscriptionDeleted(subscription) = &event.event { // Revoke access for `subscription.customer`. } Ok(()) } Then gate a page on the subscription:
let subscribed = cashier.subscribed(&user).await?; if !subscribed { // Send them to the pricing page. } That is the core loop. The rest of this article covers each piece in more detail.
Customers and the Billable trait
A user model plugs in by implementing Billable:
use rupirate_cashier::Billable; impl Billable for User { fn stripe_customer_id(&self) -> Option<&str> { self.stripe_id.as_deref() } fn billable_email(&self) -> Option<&str> { Some(&self.email) } fn billable_name(&self) -> Option<&str> { Some(&self.name) } } Three methods. The Stripe customer id, when the record has one. The email and name Stripe uses when it creates the customer. billable_name has a default of None, so you can leave it out.
With that in place:
// Creates the Stripe customer from the record's email and name. let customer = cashier.create_customer_for(&user).await?; // Does the record have a current subscription on Stripe? let subscribed = cashier.subscribed(&user).await?; let subscription = cashier.subscription_for(&user).await?; subscribed answers a yes or no question. subscription_for returns the subscription itself, so you can read its price, status, and period end. Both go through StripeClient::list_subscriptions under the hood.
You can also work with raw Stripe ids when you do not have a model in hand:
let customer = cashier.create_customer("ada@example.com", "Ada Lovelace").await?; let fetched = cashier.customer("cus_123").await?; let updated = cashier.update_customer("cus_123", None, Some("Ada")).await?; For calls the service does not wrap, use cashier.client(). It returns the StripeClient with the same key, over the same faked HTTP client in tests.
Subscriptions
Subscribe, cancel, resume, swap, change seats:
// Subscribe a customer to a price. let subscription = cashier.subscribe("cus_123", "price_monthly").await?; // With a trial: 14 days, 3 seats. let trialing = cashier .subscribe_with_trial("cus_123", "price_monthly", 3, 14) .await?; // Cancel at period end (a grace period) or immediately. let cancelled = cashier.cancel_subscription(&subscription.id, true).await?; assert!(cancelled.on_grace_period()); // Resume a subscription cancelled at period end. let resumed = cashier.resume_subscription(&subscription.id).await?; // Swap price, change seats. let swapped = cashier.swap_price(&subscription, "price_yearly").await?; let seated = cashier.set_quantity(&subscription, 5).await?; cancel_subscription takes a boolean. true keeps the subscription active until the current period ends. false ends it now.
swap_price and set_quantity change the subscription's first item. Most subscriptions have one item, so that is the common case. For a subscription with several items, use the per-item versions with a proration choice:
use rupirate_cashier::ProrationBehavior; let swapped = cashier.swap_item_price( &subscription, "si_123", "price_yearly", ProrationBehavior::CreateProrations, ).await?; let seated = cashier.set_item_quantity( &subscription, "si_123", 5, ProrationBehavior::AlwaysInvoice, ).await?; ProrationBehavior has three variants. CreateProrations prorates the change and is the default. None takes effect at the next invoice without prorating. AlwaysInvoice prorates and invoices the difference immediately.
Subscription status
A Subscription carries Stripe's status plus helpers that answer the question your app actually asks: does this customer have access right now?
| Helper | Meaning |
|---|---|
active() | Active or trialing: the customer has access |
on_trial() | In its trial period |
cancelled() | Status is cancelled |
on_grace_period() | Cancelled at period end, but still paid up |
ended() | Ended (or cancelled past its period end) |
past_due() | Latest payment failed, Stripe retrying |
incomplete() | First payment never completed |
has_price(id) / price_ids() | What the subscription bills |
on_grace_period requires a current status (active or trialing). A subscription whose status is already cancelled is not on a grace period, even when ended_at is missing.
One more detail: Stripe adds new statuses over time. A status this crate was not written to expect parses as SubscriptionStatus::Unknown instead of failing the webhook. None of the helpers treat it as current, so access stays off until the crate learns the new status.
Money
Money is in the currency's minor unit. Cents for USD. Invoice::total_major() divides by 100, and it is for display only:
// Display only. Never feed this into arithmetic. let display = invoice.total_major(); // Use the raw `total` (minor units) for any math. let total_cents = invoice.total; The reason is simple: f64 cannot represent most decimal amounts exactly. Use the raw total for math. Zero-decimal currencies need the raw total too, since there is no division to do.
Checkout and the billing portal
Send a customer to Checkout for a subscription:
let session = cashier.checkout( Some("cus_123"), "price_monthly", 1, "https://example.com/success", "https://example.com/cancel", ).await?; // Redirect the customer to `session.url`. For a one-time payment instead of a subscription:
let session = cashier.checkout_payment( Some("cus_123"), "price_one_time", 1, "https://example.com/success", "https://example.com/cancel", ).await?; For promotion codes or an explicit mode, use checkout_with_options:
use rupirate_cashier::{CheckoutMode, CheckoutOptions}; let session = cashier.checkout_with_options( Some("cus_123"), "price_monthly", 1, "https://example.com/success", "https://example.com/cancel", CheckoutOptions { mode: CheckoutMode::Subscription, allow_promotion_codes: true, }, ).await?; CheckoutOptions defaults to a subscription session without promotion codes, so CheckoutOptions::default() works when you only want to change one field. Checkout validates that success_url and cancel_url are absolute http(s) URLs.
The billing portal lets customers manage their own subscription, payment method, and invoices:
let portal = cashier.billing_portal("cus_123", "https://example.com/account").await?; // Redirect the customer to `portal.url`. Invoices
List a customer's invoices, newest first, or fetch one by id:
let invoices = cashier.invoices("cus_123", 10).await?; let invoice = cashier.invoice("in_123").await?; Metadata
Customer, Subscription, Invoice, and CheckoutSession carry Stripe's metadata map (HashMap<String, String>). It is the standard place to store the local user id, so a webhook listener can correlate an event without another Stripe call:
if let WebhookEvent::SubscriptionDeleted(subscription) = &event.event { let user_id = subscription.metadata.get("user_id"); } Put the local user id in metadata when you create the customer or subscription, and every webhook about that object carries it back to you.
Webhooks: verification that fails closed
The provider registers POST /stripe/webhook. The route has no middleware group, so no CSRF or session. Stripe posts there. The handler reads the raw body, verifies the Stripe-Signature header with the endpoint secret, parses the event, and dispatches it as a WebhookReceived framework event.
Verification uses HMAC-SHA256 over the raw timestamp string and the raw payload bytes, exactly as Stripe sent them. It rejects timestamps older than the tolerance (300 seconds by default) and compares signatures in constant time. A bad signature or a stale timestamp is a 400.
The important part is what happens when the secret is missing. An empty webhook secret fails closed with a 500. The endpoint refuses to verify anything without a secret. This matters because HMAC accepts an empty key without complaint, so a missing secret would otherwise accept forged webhooks. The crate checks for the empty secret first, before any verification happens, and logs it as an error.
A verified payload with no event id is a 400. Stripe always sends one, and the dedup cannot work without it.
Handled event types are typed:
pub enum WebhookEvent { CustomerCreated(Customer), CustomerUpdated(Customer), CustomerDeleted(Customer), SubscriptionCreated(Subscription), SubscriptionUpdated(Subscription), SubscriptionDeleted(Subscription), InvoicePaid(Invoice), InvoicePaymentFailed(Invoice), CheckoutSessionCompleted(CheckoutSession), Unknown { kind: String, object: Json }, } Anything else arrives as WebhookEvent::Unknown, with its type name and raw object, so no webhook is dropped silently. The dispatched event carries the Stripe event id too, so listeners can log it or dedup on it themselves: event.id is Some("evt_...").
verify_signature and verify_and_parse are public, for apps that run their own endpoint instead of the built-in route.
Webhooks: deduplication with a lease
Stripe retries delivery. The same verified event must not be dispatched twice, or a listener would grant access twice, send two emails, or credit an account twice. The handler claims the event id in the default cache store before dispatching.
The claim is a short "processing" lease of 5 minutes. After a successful dispatch, the handler upgrades it to the full 7-day window. A duplicate delivery inside that window returns 200 without dispatching.
The lease exists for the crash case. If the process crashes during dispatch, the lease expires in minutes, and Stripe's retry re-dispatches the event instead of losing it. A plain 7-day claim would have marked the event as done and lost it. When a listener fails, the handler releases the claim right away, so Stripe's retry re-fires.
There is one thing the dedup depends on, and the crate says it loudly: the dedup is only as durable as the cache store. It needs a durable shared store, database or redis:
CACHE_STORE=database Two stores must never back it:
-
memory, the framework default, is per-process and lost on restart. A deploy or a second server re-fires every retried webhook. The crate logs a warning once per process when the default store ismemoryordiscard. -
discardstores nothing. The handler refuses every webhook with a500instead of silently dropping it with a200.
cache:clear also wipes dedup state. After a flush, any Stripe retry inside the 7-day window re-fires. The webhook route is throttled at 120 requests a minute per client IP, in its own bucket. Over-limit requests get a 429, which Stripe retries.
Idempotency keys
Every mutating Stripe call (POST, DELETE) sends an Idempotency-Key header. A lost response can be retried safely, because Stripe returns the first call's result instead of running the operation twice.
Each call gets a fresh key by default. For a safe app-level retry, build a client with a fixed key once per logical operation and retry through it, so every attempt carries the same key:
let keyed = cashier.with_idempotency_key("order_42_subscribe"); // Retrying this call reuses the key, so Stripe will not create a // second subscription. let subscription = keyed.subscribe("cus_123", "price_monthly").await?; A fresh key per attempt does not deduplicate app-level retries. The key must be the same across the attempts. The same method exists on StripeClient for direct client calls.
Audit logging
The crate logs through the log facade. Webhook receipt (type and event id), duplicate drops, dispatch failures, and verification failures are logged. A missing webhook secret is logged as an error. Secrets and payloads are never logged. To see the lines, configure a logger in the app.
The cashier:info command shows the currency, whether the key and webhook secret are set, the webhook dedup store, and the webhook endpoint. Secrets are never printed.
How it talks to Stripe
Every call is form-encoded and sends the pinned API version 2025-08-27.basil, with the secret key as a Bearer token. A failed call surfaces Stripe's own error message:
Stripe (card_error): Your card was declined. All Stripe calls go through the framework's HTTP client, so client::fake() intercepts them in tests. Stripe ids in URLs are percent-encoded, so one cannot break out of its path segment. Negative quantities are rejected with a clear error before any HTTP call happens.
Limits, stated plainly
- Stripe is the source of truth. There are no local subscription tables and no offline mode.
- The webhook dedup lives in the default cache store, not a database table. It needs a durable shared store, and
cache:clearwipes it. - Idempotency keys are verified at the header level only. No live Stripe was available when this was written, so whether Stripe deduplicates a retried charge on its side is Stripe's documented behavior, not something proven here.
- The durable-driver dedup was verified on the database store only. Redis was not tested. The code path is driver-agnostic, but Redis itself was not exercised.
- Paddle is not included. This package is the Stripe path, Cashier's default. A Paddle gateway would be a second client of the same shape.
Tests
The crate has 54 tests passing: 18 lib unit tests, 23 package tests, 10 red-team tests, and 3 doctests. They cover the trial path, set_quantity, the 400 paths, concurrency (parallel deliveries dispatch once), the listener-failure path, the dedup lease, and the red-team regressions. Clippy reports 0 warnings.
Where to go from here
Install it from crates.io, read the source in the rupirate repo, and wire up a subscription. The fastest way to learn it is the worked example above: subscribe a customer, handle the webhook, and gate a page on subscribed. The webhook security pieces (fail-closed secret, leased dedup, idempotency keys) are already in place, so the billing path you build on top of them starts from a solid base.