Functional Weave
Code in Rust

subscriptions.stripe-state

Folds Stripe's subscription and invoice webhook events into one normalised subscription state, in any order.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 33 tests, run in TypeScript, Python and Rust.

What it does

Keep one row per subscription in your database, up to date from Stripe's webhooks, without trusting the order they arrive in. Verify each webhook (the event is `{ id, type, created, object }`, exactly what `payments.stripe-checkout`'s `verifyWebhook` returns, so pass that straight in; `object` is the event's `data.object`), load the stored state for its subscription (or null), fold the event in, and store what comes back:

import { verifyWebhook } from "#fune/payments.stripe-checkout@^1";
import { applyStripeEvent } from "#fune/subscriptions.stripe-state@^1";

const event = verifyWebhook(await req.text(), req.headers.get("stripe-signature") ?? "");
const subId = subscriptionIdOf(event);               // yours: object.id, or the invoice's subscription
const next = applyStripeEvent(await db.load(subId), event);
if (next) await db.save(next);                       // unchanged state saves the same row

For example

  • apply_stripe_event(—, id evt_1, type customer.subscription.created, created 1,772,323,200, object …) → subscription id sub_1Pz, customer id cus_9, status trialing, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period… customer.subscription.created starts the state from the snapshot
  • apply_stripe_event(—, id evt_1, type customer.subscription.created, created 1,772,323,200, object …) → subscription id sub_1Pz, customer id cus_9, status active, price id price_team, quantity 3, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period … expanded customer and latest_invoice objects give their ids
  • apply_stripe_event(—, id evt_1, type customer.subscription.updated, created 1,772,323,200, object …) → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… newer API versions: the period is read from the subscription item

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

pub fn apply_stripe_event(state: Option<&SubscriptionState>, event: &Value) -> Option<SubscriptionState>
stateSubscriptionState?what the last event left, as stored; null before the first event for this subscription
eventjsona verified webhook event: id, type, created (Unix seconds) and object (its data.object), as payments.stripe-checkout's verifyWebhook returns it
returnsSubscriptionState?the new state to store; the same state when the event changes nothing; null while nothing is known

The types it declares, generated into your project

// StripeSubscriptionStatus is a string in Rust, one of: "incomplete", "incomplete_expired", "trialing", "active", "past_due", "canceled", "unpaid", "paused".
// Parameters take it as &str and results hold it as String.

/// One subscription as your app stores it, kept from the webhooks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubscriptionState {
    /// sub_...
    pub subscription_id: String,
    /// cus_...
    pub customer_id: String,
    /// Stripe's status, moved on by invoice events between snapshots
    pub status: String,
    /// the first item's price, price_...; null until a subscription event says
    pub price_id: Option<String>,
    /// the first item's quantity
    pub quantity: i64,
    /// Unix seconds
    pub current_period_start: Option<i64>,
    /// Unix seconds; access runs to here when cancelAtPeriodEnd
    pub current_period_end: Option<i64>,
    /// the customer cancelled and it ends at currentPeriodEnd
    pub cancel_at_period_end: bool,
    /// a scheduled cancellation time
    pub cancel_at: Option<i64>,
    /// when it was cancelled
    pub canceled_at: Option<i64>,
    /// when it ended
    pub ended_at: Option<i64>,
    /// when the trial ends or ended
    pub trial_end: Option<i64>,
    /// in_...
    pub latest_invoice_id: Option<String>,
    /// the latest invoice event was a failed payment
    pub payment_failed: bool,
    /// whether to give access: active, trialing or past_due (a grace period while Stripe retries)
    pub entitled: bool,
    /// created of the last subscription snapshot applied; 0 for none
    pub subscription_event_at: i64,
    /// created of the last invoice event applied; 0 for none
    pub invoice_event_at: i64,
    /// the last event applied, so a redelivery changes nothing
    pub last_event_id: String,
}

Your code names it in one line, in the file that uses it

fune!(subscriptions.stripe-state@^1);  // then call apply_stripe_event(…)
impl/rust.rs · 297 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

const STATUSES: [&str; 8] = ["incomplete", "incomplete_expired", "trialing", "active", "past_due", "canceled", "unpaid", "paused"];
const SUBSCRIPTION_EVENTS: [&str; 6] = [
    "customer.subscription.created",
    "customer.subscription.updated",
    "customer.subscription.deleted",
    "customer.subscription.paused",
    "customer.subscription.resumed",
    "customer.subscription.trial_will_end",
];

// An id Stripe sends either as a string or, when expanded, as an object with one.
fn id_of(v: &Value) -> Option<String> {
    match v {
        Value::Str(s) if !s.is_empty() => Some(s.clone()),
        Value::Obj(_) => match v.get("id") {
            Value::Str(s) if !s.is_empty() => Some(s.clone()),
            _ => None,
        },
        _ => None,
    }
}

fn opt_int(o: &Value, key: &str) -> Option<i64> {
    match o.get(key) {
        Value::Null => None,
        Value::Int(i) => Some(*i),
        _ => panic!("subscription field {} must be a whole number or null", key),
    }
}

fn entitled_for(status: &str) -> bool {
    status == "active" || status == "trialing" || status == "past_due"
}

// Where an invoice event happened after a snapshot was taken, the snapshot
// does not know about the payment yet: keep the invoice's effect on top.
fn with_invoice_effect(status: &str, payment_failed: bool) -> String {
    if !payment_failed && (status == "incomplete" || status == "past_due" || status == "unpaid") {
        return "active".to_string();
    }
    if payment_failed && status == "active" {
        return "past_due".to_string();
    }
    status.to_string()
}

fn invoice_subscription(invoice: &Value) -> Option<String> {
    if let Some(direct) = id_of(invoice.get("subscription")) {
        return Some(direct);
    }
    // API versions from 2025 move it under parent.subscription_details.
    id_of(invoice.get("parent").get("subscription_details").get("subscription"))
}

/// Folds one verified Stripe webhook event into the stored state of one
/// subscription. Stripe does not promise delivery order or delivery once, so
/// subscription snapshots and invoice events each keep their own clock and an
/// older one is ignored, a redelivered event changes nothing, and a cancelled
/// subscription stays cancelled.
///
/// # Panics
/// Panics on a malformed event, or one for another subscription than `state`.
pub fn apply_stripe_event(state: Option<&SubscriptionState>, event: &Value) -> Option<SubscriptionState> {
    if !matches!(event, Value::Obj(_)) {
        panic!("event must be a JSON object");
    }
    let event_id = match event.get("id") {
        Value::Str(s) if !s.is_empty() => s.clone(),
        _ => panic!("event id must be a non-empty string"),
    };
    let kind = match event.get("type") {
        Value::Str(s) if !s.is_empty() => s.clone(),
        _ => panic!("event type must be a non-empty string"),
    };
    let created = match event.get("created") {
        Value::Int(i) if *i >= 0 => *i,
        _ => panic!("event created must be a whole number of seconds"),
    };
    let obj = event.get("object");
    if !matches!(obj, Value::Obj(_)) {
        panic!("event object must be a JSON object");
    }
    if let Some(s) = state {
        if event_id == s.last_event_id {
            return Some(s.clone());
        }
    }
    let kind = kind.as_str();

    if SUBSCRIPTION_EVENTS.contains(&kind) {
        let id = id_of(obj.get("id"));
        let customer = id_of(obj.get("customer"));
        let raw_status = match obj.get("status") {
            Value::Str(s) => Some(s.clone()),
            _ => None,
        };
        let (id, customer, raw_status) = match (id, customer, raw_status) {
            (Some(a), Some(b), Some(c)) => (a, b, c),
            _ => panic!("subscription object needs id, customer and status"),
        };
        if !STATUSES.contains(&raw_status.as_str()) {
            panic!("unknown subscription status \"{}\"", raw_status);
        }
        if let Some(s) = state {
            if id != s.subscription_id {
                panic!("event is for subscription {}, not {}", id, s.subscription_id);
            }
        }
        let snapshot_status = if kind == "customer.subscription.deleted" { "canceled".to_string() } else { raw_status };
        if let Some(s) = state {
            // Cancelled is final in Stripe: a late snapshot never revives it.
            if s.status == "canceled" && snapshot_status != "canceled" {
                return Some(s.clone());
            }
            if created < s.subscription_event_at {
                return Some(s.clone());
            }
        }
        let item = obj.get("items").get("data").at(0);
        let item = if matches!(item, Value::Obj(_)) { item.clone() } else { Value::Obj(vec![]) };
        let quantity = opt_int(&item, "quantity").unwrap_or(1);
        let period_start = opt_int(obj, "current_period_start").or_else(|| opt_int(&item, "current_period_start"));
        let period_end = opt_int(obj, "current_period_end").or_else(|| opt_int(&item, "current_period_end"));
        let cape = match obj.get("cancel_at_period_end") {
            Value::Null => false,
            Value::Bool(b) => *b,
            _ => panic!("subscription field cancel_at_period_end must be true or false"),
        };
        let payment_failed = state.map(|s| s.payment_failed).unwrap_or(false);
        let invoice_event_at = state.map(|s| s.invoice_event_at).unwrap_or(0);
        let status = if invoice_event_at > created {
            with_invoice_effect(&snapshot_status, payment_failed)
        } else {
            snapshot_status
        };
        let latest = id_of(obj.get("latest_invoice")).or_else(|| state.and_then(|s| s.latest_invoice_id.clone()));
        return Some(SubscriptionState {
            subscription_id: id,
            customer_id: customer,
            entitled: entitled_for(&status),
            status,
            price_id: id_of(item.get("price")),
            quantity,
            current_period_start: period_start,
            current_period_end: period_end,
            cancel_at_period_end: cape,
            cancel_at: opt_int(obj, "cancel_at"),
            canceled_at: opt_int(obj, "canceled_at"),
            ended_at: opt_int(obj, "ended_at"),
            trial_end: opt_int(obj, "trial_end"),
            latest_invoice_id: latest,
            payment_failed,
            subscription_event_at: created,
            invoice_event_at,
            last_event_id: event_id.clone(),
        });
    }

    let paid = kind == "invoice.paid" || kind == "invoice.payment_succeeded";
    if paid || kind == "invoice.payment_failed" {
        let sub = match invoice_subscription(obj) {
            Some(s) => s,
            None => return state.cloned(),
        };
        let invoice_id = id_of(obj.get("id"));
        let s = match state {
            None => {
                let customer = match id_of(obj.get("customer")) {
                    Some(c) => c,
                    None => panic!("invoice object needs customer"),
                };
                let status = if paid { "active" } else { "incomplete" };
                return Some(SubscriptionState {
                    subscription_id: sub,
                    customer_id: customer,
                    status: status.to_string(),
                    price_id: None,
                    quantity: 1,
                    current_period_start: None,
                    current_period_end: None,
                    cancel_at_period_end: false,
                    cancel_at: None,
                    canceled_at: None,
                    ended_at: None,
                    trial_end: None,
                    latest_invoice_id: invoice_id,
                    payment_failed: !paid,
                    entitled: entitled_for(status),
                    subscription_event_at: 0,
                    invoice_event_at: created,
                    last_event_id: event_id.clone(),
                });
            }
            Some(s) => s,
        };
        if sub != s.subscription_id {
            panic!("event is for subscription {}, not {}", sub, s.subscription_id);
        }
        if created < s.invoice_event_at {
            return Some(s.clone());
        }
        let status = with_invoice_effect(&s.status, !paid);
        let mut next = s.clone();
        next.entitled = entitled_for(&status);
        next.status = status;
        next.latest_invoice_id = invoice_id.or_else(|| s.latest_invoice_id.clone());
        next.payment_failed = !paid;
        next.invoice_event_at = created;
        next.last_event_id = event_id.clone();
        return Some(next);
    }

    state.cloned()
}

fn opt_int_value(v: Option<i64>) -> Value {
    v.map(Value::Int).unwrap_or(Value::Null)
}

fn opt_str_value(v: &Option<String>) -> Value {
    v.as_ref().map(|s| Value::str(s)).unwrap_or(Value::Null)
}

pub fn subscription_state_to_value(s: &SubscriptionState) -> Value {
    Value::obj(vec![
        ("subscriptionId", Value::str(&s.subscription_id)),
        ("customerId", Value::str(&s.customer_id)),
        ("status", Value::str(&s.status)),
        ("priceId", opt_str_value(&s.price_id)),
        ("quantity", Value::Int(s.quantity)),
        ("currentPeriodStart", opt_int_value(s.current_period_start)),
        ("currentPeriodEnd", opt_int_value(s.current_period_end)),
        ("cancelAtPeriodEnd", Value::Bool(s.cancel_at_period_end)),
        ("cancelAt", opt_int_value(s.cancel_at)),
        ("canceledAt", opt_int_value(s.canceled_at)),
        ("endedAt", opt_int_value(s.ended_at)),
        ("trialEnd", opt_int_value(s.trial_end)),
        ("latestInvoiceId", opt_str_value(&s.latest_invoice_id)),
        ("paymentFailed", Value::Bool(s.payment_failed)),
        ("entitled", Value::Bool(s.entitled)),
        ("subscriptionEventAt", Value::Int(s.subscription_event_at)),
        ("invoiceEventAt", Value::Int(s.invoice_event_at)),
        ("lastEventId", Value::str(&s.last_event_id)),
    ])
}

fn state_from_value(v: &Value) -> SubscriptionState {
    let text = |k: &str| match v.get(k) {
        Value::Str(s) => s.clone(),
        _ => panic!("state field {} must be a string", k),
    };
    let opt_text = |k: &str| match v.get(k) {
        Value::Str(s) => Some(s.clone()),
        _ => None,
    };
    let int = |k: &str| match v.get(k) {
        Value::Int(i) => *i,
        _ => panic!("state field {} must be a whole number", k),
    };
    let opt = |k: &str| match v.get(k) {
        Value::Int(i) => Some(*i),
        _ => None,
    };
    SubscriptionState {
        subscription_id: text("subscriptionId"),
        customer_id: text("customerId"),
        status: text("status"),
        price_id: opt_text("priceId"),
        quantity: int("quantity"),
        current_period_start: opt("currentPeriodStart"),
        current_period_end: opt("currentPeriodEnd"),
        cancel_at_period_end: v.get("cancelAtPeriodEnd").as_bool(),
        cancel_at: opt("cancelAt"),
        canceled_at: opt("canceledAt"),
        ended_at: opt("endedAt"),
        trial_end: opt("trialEnd"),
        latest_invoice_id: opt_text("latestInvoiceId"),
        payment_failed: v.get("paymentFailed").as_bool(),
        entitled: v.get("entitled").as_bool(),
        subscription_event_at: int("subscriptionEventAt"),
        invoice_event_at: int("invoiceEventAt"),
        last_event_id: text("lastEventId"),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    let state = match &args[0] {
        Value::Null => None,
        v => Some(state_from_value(v)),
    };
    match apply_stripe_event(state.as_ref(), &args[1]) {
        Some(s) => subscription_state_to_value(&s),
        None => Value::Null,
    }
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add subscriptions.stripe-state
Download for Rust subscriptions.stripe-state-1.0.0-rust.fune · 63,421 bytes sha256 26622a008f15a2f820ebfa670fff48d59576eefe64eaca97ac7fbd9f9a4a6fa6

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./subscriptions.stripe-state-1.0.0-rust.fune, or fetch it from a terminal with fune pull subscriptions.stripe-state@1.0.0:rust.

The whole function, every language, is one file too: subscriptions.stripe-state-1.0.0.fune, 79,658 bytes, sha256 bbaf14bffdc2c8c8e9aabb126b79bd59b5bc42d690449941bcc1bd7711ab72bf. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before subscriptions.stripe-state

after — your function gets the result and the arguments, and returns the final result.

// fune: after subscriptions.stripe-state

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show subscriptions.stripe-state --steps.

// fune: step subscriptions.stripe-state after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
customer.subscription.created starts the state from the snapshot —, id evt_1, type customer.subscription.created, created 1,772,323,200, object … → subscription id sub_1Pz, customer id cus_9, status trialing, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
expanded customer and latest_invoice objects give their ids —, id evt_1, type customer.subscription.created, created 1,772,323,200, object … → subscription id sub_1Pz, customer id cus_9, status active, price id price_team, quantity 3, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period …
newer API versions: the period is read from the subscription item —, id evt_1, type customer.subscription.updated, created 1,772,323,200, object … → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
the customer cancels at the period end: still entitled until then subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
customer.subscription.deleted is cancelled and not entitled, whatever status it carries subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status canceled, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
cancelled is final: a later snapshot saying active does not revive it subscription id sub_1Pz, customer id cus_9, status canceled, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period… → subscription id sub_1Pz, customer id cus_9, status canceled, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
a snapshot older than the one applied is ignored subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
a redelivered event changes nothing subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
invoice.payment_failed moves active to past_due, still entitled while Stripe retries subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status past_due, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
a failed payment during a trial leaves it trialing subscription id sub_1Pz, customer id cus_9, status trialing, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period… → subscription id sub_1Pz, customer id cus_9, status trialing, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
Show the other 23 tests
CaseArgumentsExpected
invoice.paid after a failure moves past_due back to active subscription id sub_1Pz, customer id cus_9, status past_due, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
newer API versions: invoice.payment_succeeded finds the subscription under parent, and unpaid becomes active subscription id sub_1Pz, customer id cus_9, status unpaid, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
an invoice event older than the last one applied is ignored subscription id sub_1Pz, customer id cus_9, status past_due, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period… → subscription id sub_1Pz, customer id cus_9, status past_due, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period…
invoice.paid before any subscription event starts an active state —, id evt_1, type invoice.paid, created 1,772,323,260, object … → subscription id sub_1Pz, customer id cus_9, status active, price id —, quantity 1, current period start —, current period end —, cancel at period end false, cancel at —, canceled …
the subscription.created that arrives after its paid invoice fills the plan in and stays active subscription id sub_1Pz, customer id cus_9, status active, price id —, quantity 1, current period start —, current period end —, cancel at period end false, cancel at —, canceled … → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
invoice.payment_failed before any subscription event starts an incomplete state, not entitled —, id evt_1, type invoice.payment_failed, created 1,772,323,260, object … → subscription id sub_1Pz, customer id cus_9, status incomplete, price id —, quantity 1, current period start —, current period end —, cancel at period end false, cancel at —, cance…
a one-off invoice with no subscription changes nothing subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
an event this reducer does not read leaves no state as no state —, id evt_9, type checkout.session.completed, created 1,772,700,000, object … → —
customer.updated leaves the state unchanged subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
customer.subscription.paused: paused is not entitled subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status paused, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
a snapshot at the same second as the last one applies subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 5, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e…
trial_will_end with no items: no price, quantity 1 —, id evt_1, type customer.subscription.trial_will_end, created 1,773,273,600, object … → subscription id sub_1Pz, customer id cus_9, status trialing, price id —, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period end fal…
an event for another subscription is an error subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → error: event is for subscription sub_other, not sub_1Pz
an invoice for another subscription is an error subscription id sub_1Pz, customer id cus_9, status active, price id price_pro, quantity 1, current period start 1,772,323,200, current period end 1,775,001,600, cancel at period e… → error: event is for subscription sub_other, not sub_1Pz
an unknown status is an error —, id evt_1, type customer.subscription.updated, created 1,772,800,000, object … → error: unknown subscription status "expired"
a subscription without its customer is an error —, id evt_1, type customer.subscription.created, created 1,772,800,000, object … → error: subscription object needs id, customer and status
an empty event id is an error —, id , type invoice.paid, created 1,772,800,000, object … → error: event id must be a non-empty string
a fractional created time is an error —, id evt_1, type invoice.paid, created 1,772,800,000.5, object … → error: event created must be a whole number of seconds
an object that is not a JSON object is an error —, id evt_1, type invoice.paid, created 1,772,800,000, object in_2 → error: event object must be a JSON object
a period end that is text is an error —, id evt_1, type customer.subscription.created, created 1,772,800,000, object … → error: subscription field current_period_end must be a whole number or null
a first invoice without its customer is an error —, id evt_1, type invoice.paid, created 1,772,800,000, object … → error: invoice object needs customer
an event that is not an object is an error —, evt_1 → error: event must be a JSON object
an event without a type is an error —, id evt_1, created 1,772,800,000, object … → error: event type must be a non-empty string

Verification

Verified by the operator, not the sandbox 33 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

What it reads:

- `customer.subscription.created`, `.updated`, `.deleted`, `.paused`, `.resumed` and `.trial_will_end` carry the whole subscription: a snapshot. The status, the first item's price and quantity, the current period (top level on older API versions, on the item since 2025), the cancellation fields, trial end and latest invoice are taken from it. `.deleted` is always `canceled`. - `invoice.paid` and `invoice.payment_succeeded` clear `paymentFailed` and move `past_due`, `unpaid` or `incomplete` to `active`; `invoice.payment_failed` sets `paymentFailed` and moves `active` to `past_due` (a trial stays `trialing`). The subscription is `object.subscription`, or `object.parent.subscription_details.subscription` on newer API versions, as a string or an expanded object. An invoice without a subscription (a one-off) is ignored. - Every other event type returns the state unchanged (and null stays null).

Ordering. Stripe neither promises order nor delivers exactly once, so:

- snapshots and invoice events each keep their own clock (`subscriptionEventAt`, `invoiceEventAt`, the events' `created`): an older one than the last applied is ignored, one at the same second applies; - the same event id as `lastEventId` changes nothing; - when a snapshot is older than the last invoice event (a paid invoice arriving before `customer.subscription.created`), the invoice's effect is kept on top of the snapshot's status, so the paid subscription does not fall back to `incomplete`; - an invoice event with no state yet starts one (`active` when paid, `incomplete` when failed), with no price and `subscriptionEventAt` 0, so the first snapshot to arrive still fills it in; - `canceled` is final, as in Stripe: a later snapshot with another status does not revive it (a later cancelled one may still fill in `endedAt`).

`entitled` is the access decision: true for `active`, `trialing` and `past_due`. Counting `past_due` is a deliberate grace period while Stripe retries the card (see `subscriptions.dunning-schedule`); an app that wants to cut access at the first failure checks `status == "active" || "trialing"` itself. A customer who cancels at the period end stays `active` with `cancelAtPeriodEnd` true until Stripe sends the deletion.

Errors: a malformed event (not an object, no id or type, `created` not a whole number, `object` not an object, a subscription without id, customer or status, an unknown status, a non-integer time field) and an event for a different subscription than the state's (`event is for subscription sub_x, not sub_y`) throw: look the state up by the event's subscription id.

Out of scope: several items per subscription (only the first item's price and quantity are kept), schedules, and checkout sessions (store the customer id from `checkout.session.completed` yourself).

Files

PathBytes
README.md3,809
impl/python.py8,117
impl/rust.rs11,760
impl/typescript.ts7,430
vectors.json37,114