use super::funejson::Value; 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 { 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 { 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 { 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 { 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) -> Value { v.map(Value::Int).unwrap_or(Value::Null) } fn opt_str_value(v: &Option) -> 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, } }