billing.rs

  1use std::str::FromStr;
  2use std::sync::Arc;
  3use std::time::Duration;
  4
  5use anyhow::{anyhow, bail, Context};
  6use axum::{
  7    extract::{self, Query},
  8    routing::{get, post},
  9    Extension, Json, Router,
 10};
 11use chrono::{DateTime, SecondsFormat};
 12use reqwest::StatusCode;
 13use sea_orm::ActiveValue;
 14use serde::{Deserialize, Serialize};
 15use stripe::{
 16    BillingPortalSession, CheckoutSession, CreateBillingPortalSession,
 17    CreateBillingPortalSessionFlowData, CreateBillingPortalSessionFlowDataAfterCompletion,
 18    CreateBillingPortalSessionFlowDataAfterCompletionRedirect,
 19    CreateBillingPortalSessionFlowDataType, CreateCheckoutSession, CreateCheckoutSessionLineItems,
 20    CreateCustomer, Customer, CustomerId, EventObject, EventType, Expandable, ListEvents,
 21    Subscription, SubscriptionId, SubscriptionStatus,
 22};
 23use util::ResultExt;
 24
 25use crate::db::billing_subscription::StripeSubscriptionStatus;
 26use crate::db::{
 27    billing_customer, BillingSubscriptionId, CreateBillingCustomerParams,
 28    CreateBillingSubscriptionParams, CreateProcessedStripeEventParams, UpdateBillingCustomerParams,
 29    UpdateBillingSubscriptionParams,
 30};
 31use crate::{AppState, Error, Result};
 32
 33pub fn router() -> Router {
 34    Router::new()
 35        .route(
 36            "/billing/subscriptions",
 37            get(list_billing_subscriptions).post(create_billing_subscription),
 38        )
 39        .route(
 40            "/billing/subscriptions/manage",
 41            post(manage_billing_subscription),
 42        )
 43}
 44
 45#[derive(Debug, Deserialize)]
 46struct ListBillingSubscriptionsParams {
 47    github_user_id: i32,
 48}
 49
 50#[derive(Debug, Serialize)]
 51struct BillingSubscriptionJson {
 52    id: BillingSubscriptionId,
 53    name: String,
 54    status: StripeSubscriptionStatus,
 55    cancel_at: Option<String>,
 56    /// Whether this subscription can be canceled.
 57    is_cancelable: bool,
 58}
 59
 60#[derive(Debug, Serialize)]
 61struct ListBillingSubscriptionsResponse {
 62    subscriptions: Vec<BillingSubscriptionJson>,
 63}
 64
 65async fn list_billing_subscriptions(
 66    Extension(app): Extension<Arc<AppState>>,
 67    Query(params): Query<ListBillingSubscriptionsParams>,
 68) -> Result<Json<ListBillingSubscriptionsResponse>> {
 69    let user = app
 70        .db
 71        .get_user_by_github_user_id(params.github_user_id)
 72        .await?
 73        .ok_or_else(|| anyhow!("user not found"))?;
 74
 75    let subscriptions = app.db.get_billing_subscriptions(user.id).await?;
 76
 77    Ok(Json(ListBillingSubscriptionsResponse {
 78        subscriptions: subscriptions
 79            .into_iter()
 80            .map(|subscription| BillingSubscriptionJson {
 81                id: subscription.id,
 82                name: "Zed Pro".to_string(),
 83                status: subscription.stripe_subscription_status,
 84                cancel_at: subscription.stripe_cancel_at.map(|cancel_at| {
 85                    cancel_at
 86                        .and_utc()
 87                        .to_rfc3339_opts(SecondsFormat::Millis, true)
 88                }),
 89                is_cancelable: subscription.stripe_subscription_status.is_cancelable()
 90                    && subscription.stripe_cancel_at.is_none(),
 91            })
 92            .collect(),
 93    }))
 94}
 95
 96#[derive(Debug, Deserialize)]
 97struct CreateBillingSubscriptionBody {
 98    github_user_id: i32,
 99}
100
101#[derive(Debug, Serialize)]
102struct CreateBillingSubscriptionResponse {
103    checkout_session_url: String,
104}
105
106/// Initiates a Stripe Checkout session for creating a billing subscription.
107async fn create_billing_subscription(
108    Extension(app): Extension<Arc<AppState>>,
109    extract::Json(body): extract::Json<CreateBillingSubscriptionBody>,
110) -> Result<Json<CreateBillingSubscriptionResponse>> {
111    let user = app
112        .db
113        .get_user_by_github_user_id(body.github_user_id)
114        .await?
115        .ok_or_else(|| anyhow!("user not found"))?;
116
117    let Some((stripe_client, stripe_price_id)) = app
118        .stripe_client
119        .clone()
120        .zip(app.config.stripe_price_id.clone())
121    else {
122        log::error!("failed to retrieve Stripe client or price ID");
123        Err(Error::Http(
124            StatusCode::NOT_IMPLEMENTED,
125            "not supported".into(),
126        ))?
127    };
128
129    let customer_id =
130        if let Some(existing_customer) = app.db.get_billing_customer_by_user_id(user.id).await? {
131            CustomerId::from_str(&existing_customer.stripe_customer_id)
132                .context("failed to parse customer ID")?
133        } else {
134            let customer = Customer::create(
135                &stripe_client,
136                CreateCustomer {
137                    email: user.email_address.as_deref(),
138                    ..Default::default()
139                },
140            )
141            .await?;
142
143            customer.id
144        };
145
146    let checkout_session = {
147        let mut params = CreateCheckoutSession::new();
148        params.mode = Some(stripe::CheckoutSessionMode::Subscription);
149        params.customer = Some(customer_id);
150        params.client_reference_id = Some(user.github_login.as_str());
151        params.line_items = Some(vec![CreateCheckoutSessionLineItems {
152            price: Some(stripe_price_id.to_string()),
153            quantity: Some(1),
154            ..Default::default()
155        }]);
156        let success_url = format!("{}/settings", app.config.zed_dot_dev_url());
157        params.success_url = Some(&success_url);
158
159        CheckoutSession::create(&stripe_client, params).await?
160    };
161
162    Ok(Json(CreateBillingSubscriptionResponse {
163        checkout_session_url: checkout_session
164            .url
165            .ok_or_else(|| anyhow!("no checkout session URL"))?,
166    }))
167}
168
169#[derive(Debug, PartialEq, Deserialize)]
170#[serde(rename_all = "snake_case")]
171enum ManageSubscriptionIntent {
172    /// The user intends to cancel their subscription.
173    Cancel,
174    /// The user intends to stop the cancelation of their subscription.
175    StopCancelation,
176}
177
178#[derive(Debug, Deserialize)]
179struct ManageBillingSubscriptionBody {
180    github_user_id: i32,
181    intent: ManageSubscriptionIntent,
182    /// The ID of the subscription to manage.
183    subscription_id: BillingSubscriptionId,
184}
185
186#[derive(Debug, Serialize)]
187struct ManageBillingSubscriptionResponse {
188    billing_portal_session_url: Option<String>,
189}
190
191/// Initiates a Stripe customer portal session for managing a billing subscription.
192async fn manage_billing_subscription(
193    Extension(app): Extension<Arc<AppState>>,
194    extract::Json(body): extract::Json<ManageBillingSubscriptionBody>,
195) -> Result<Json<ManageBillingSubscriptionResponse>> {
196    let user = app
197        .db
198        .get_user_by_github_user_id(body.github_user_id)
199        .await?
200        .ok_or_else(|| anyhow!("user not found"))?;
201
202    let Some(stripe_client) = app.stripe_client.clone() else {
203        log::error!("failed to retrieve Stripe client");
204        Err(Error::Http(
205            StatusCode::NOT_IMPLEMENTED,
206            "not supported".into(),
207        ))?
208    };
209
210    let customer = app
211        .db
212        .get_billing_customer_by_user_id(user.id)
213        .await?
214        .ok_or_else(|| anyhow!("billing customer not found"))?;
215    let customer_id = CustomerId::from_str(&customer.stripe_customer_id)
216        .context("failed to parse customer ID")?;
217
218    let subscription = app
219        .db
220        .get_billing_subscription_by_id(body.subscription_id)
221        .await?
222        .ok_or_else(|| anyhow!("subscription not found"))?;
223
224    if body.intent == ManageSubscriptionIntent::StopCancelation {
225        let subscription_id = SubscriptionId::from_str(&subscription.stripe_subscription_id)
226            .context("failed to parse subscription ID")?;
227
228        let updated_stripe_subscription = Subscription::update(
229            &stripe_client,
230            &subscription_id,
231            stripe::UpdateSubscription {
232                cancel_at_period_end: Some(false),
233                ..Default::default()
234            },
235        )
236        .await?;
237
238        app.db
239            .update_billing_subscription(
240                subscription.id,
241                &UpdateBillingSubscriptionParams {
242                    stripe_cancel_at: ActiveValue::set(
243                        updated_stripe_subscription
244                            .cancel_at
245                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
246                            .map(|time| time.naive_utc()),
247                    ),
248                    ..Default::default()
249                },
250            )
251            .await?;
252
253        return Ok(Json(ManageBillingSubscriptionResponse {
254            billing_portal_session_url: None,
255        }));
256    }
257
258    let flow = match body.intent {
259        ManageSubscriptionIntent::Cancel => CreateBillingPortalSessionFlowData {
260            type_: CreateBillingPortalSessionFlowDataType::SubscriptionCancel,
261            after_completion: Some(CreateBillingPortalSessionFlowDataAfterCompletion {
262                type_: stripe::CreateBillingPortalSessionFlowDataAfterCompletionType::Redirect,
263                redirect: Some(CreateBillingPortalSessionFlowDataAfterCompletionRedirect {
264                    return_url: format!("{}/settings", app.config.zed_dot_dev_url()),
265                }),
266                ..Default::default()
267            }),
268            subscription_cancel: Some(
269                stripe::CreateBillingPortalSessionFlowDataSubscriptionCancel {
270                    subscription: subscription.stripe_subscription_id,
271                    retention: None,
272                },
273            ),
274            ..Default::default()
275        },
276        ManageSubscriptionIntent::StopCancelation => unreachable!(),
277    };
278
279    let mut params = CreateBillingPortalSession::new(customer_id);
280    params.flow_data = Some(flow);
281    let return_url = format!("{}/settings", app.config.zed_dot_dev_url());
282    params.return_url = Some(&return_url);
283
284    let session = BillingPortalSession::create(&stripe_client, params).await?;
285
286    Ok(Json(ManageBillingSubscriptionResponse {
287        billing_portal_session_url: Some(session.url),
288    }))
289}
290
291const POLL_EVENTS_INTERVAL: Duration = Duration::from_secs(5 * 60);
292
293/// Polls the Stripe events API periodically to reconcile the records in our
294/// database with the data in Stripe.
295pub fn poll_stripe_events_periodically(app: Arc<AppState>) {
296    let Some(stripe_client) = app.stripe_client.clone() else {
297        log::warn!("failed to retrieve Stripe client");
298        return;
299    };
300
301    let executor = app.executor.clone();
302    executor.spawn_detached({
303        let executor = executor.clone();
304        async move {
305            loop {
306                poll_stripe_events(&app, &stripe_client).await.log_err();
307
308                executor.sleep(POLL_EVENTS_INTERVAL).await;
309            }
310        }
311    });
312}
313
314async fn poll_stripe_events(
315    app: &Arc<AppState>,
316    stripe_client: &stripe::Client,
317) -> anyhow::Result<()> {
318    fn event_type_to_string(event_type: EventType) -> String {
319        // Calling `to_string` on `stripe::EventType` members gives us a quoted string,
320        // so we need to unquote it.
321        event_type.to_string().trim_matches('"').to_string()
322    }
323
324    let event_types = [
325        EventType::CustomerCreated,
326        EventType::CustomerUpdated,
327        EventType::CustomerSubscriptionCreated,
328        EventType::CustomerSubscriptionUpdated,
329        EventType::CustomerSubscriptionPaused,
330        EventType::CustomerSubscriptionResumed,
331        EventType::CustomerSubscriptionDeleted,
332    ]
333    .into_iter()
334    .map(event_type_to_string)
335    .collect::<Vec<_>>();
336
337    let mut unprocessed_events = Vec::new();
338
339    loop {
340        log::info!("retrieving events from Stripe: {}", event_types.join(", "));
341
342        let mut params = ListEvents::new();
343        params.types = Some(event_types.clone());
344        params.limit = Some(100);
345
346        let events = stripe::Event::list(stripe_client, &params).await?;
347
348        let processed_event_ids = {
349            let event_ids = &events
350                .data
351                .iter()
352                .map(|event| event.id.as_str())
353                .collect::<Vec<_>>();
354
355            app.db
356                .get_processed_stripe_events_by_event_ids(event_ids)
357                .await?
358                .into_iter()
359                .map(|event| event.stripe_event_id)
360                .collect::<Vec<_>>()
361        };
362
363        for event in events.data {
364            if processed_event_ids.contains(&event.id.to_string()) {
365                log::info!("Stripe event {} already processed: skipping", event.id);
366            } else {
367                unprocessed_events.push(event);
368            }
369        }
370
371        if !events.has_more {
372            break;
373        }
374    }
375
376    log::info!(
377        "unprocessed events from Stripe: {}",
378        unprocessed_events.len()
379    );
380
381    // Sort all of the unprocessed events in ascending order, so we can handle them in the order they occurred.
382    unprocessed_events.sort_by(|a, b| a.created.cmp(&b.created).then_with(|| a.id.cmp(&b.id)));
383
384    for event in unprocessed_events {
385        let processed_event_params = CreateProcessedStripeEventParams {
386            stripe_event_id: event.id.to_string(),
387            stripe_event_type: event_type_to_string(event.type_),
388            stripe_event_created_timestamp: event.created,
389        };
390
391        match event.type_ {
392            EventType::CustomerCreated | EventType::CustomerUpdated => {
393                handle_customer_event(app, stripe_client, event)
394                    .await
395                    .log_err();
396            }
397            EventType::CustomerSubscriptionCreated
398            | EventType::CustomerSubscriptionUpdated
399            | EventType::CustomerSubscriptionPaused
400            | EventType::CustomerSubscriptionResumed
401            | EventType::CustomerSubscriptionDeleted => {
402                handle_customer_subscription_event(app, stripe_client, event)
403                    .await
404                    .log_err();
405            }
406            _ => {}
407        }
408
409        app.db
410            .create_processed_stripe_event(&processed_event_params)
411            .await?;
412    }
413
414    Ok(())
415}
416
417async fn handle_customer_event(
418    app: &Arc<AppState>,
419    _stripe_client: &stripe::Client,
420    event: stripe::Event,
421) -> anyhow::Result<()> {
422    let EventObject::Customer(customer) = event.data.object else {
423        bail!("unexpected event payload for {}", event.id);
424    };
425
426    log::info!("handling Stripe {} event: {}", event.type_, event.id);
427
428    let Some(email) = customer.email else {
429        log::info!("Stripe customer has no email: skipping");
430        return Ok(());
431    };
432
433    let Some(user) = app.db.get_user_by_email(&email).await? else {
434        log::info!("no user found for email: skipping");
435        return Ok(());
436    };
437
438    if let Some(existing_customer) = app
439        .db
440        .get_billing_customer_by_stripe_customer_id(&customer.id)
441        .await?
442    {
443        app.db
444            .update_billing_customer(
445                existing_customer.id,
446                &UpdateBillingCustomerParams {
447                    // For now we just leave the information as-is, as it is not
448                    // likely to change.
449                    ..Default::default()
450                },
451            )
452            .await?;
453    } else {
454        app.db
455            .create_billing_customer(&CreateBillingCustomerParams {
456                user_id: user.id,
457                stripe_customer_id: customer.id.to_string(),
458            })
459            .await?;
460    }
461
462    Ok(())
463}
464
465async fn handle_customer_subscription_event(
466    app: &Arc<AppState>,
467    stripe_client: &stripe::Client,
468    event: stripe::Event,
469) -> anyhow::Result<()> {
470    let EventObject::Subscription(subscription) = event.data.object else {
471        bail!("unexpected event payload for {}", event.id);
472    };
473
474    log::info!("handling Stripe {} event: {}", event.type_, event.id);
475
476    let billing_customer =
477        find_or_create_billing_customer(app, stripe_client, subscription.customer)
478            .await?
479            .ok_or_else(|| anyhow!("billing customer not found"))?;
480
481    if let Some(existing_subscription) = app
482        .db
483        .get_billing_subscription_by_stripe_subscription_id(&subscription.id)
484        .await?
485    {
486        app.db
487            .update_billing_subscription(
488                existing_subscription.id,
489                &UpdateBillingSubscriptionParams {
490                    billing_customer_id: ActiveValue::set(billing_customer.id),
491                    stripe_subscription_id: ActiveValue::set(subscription.id.to_string()),
492                    stripe_subscription_status: ActiveValue::set(subscription.status.into()),
493                    stripe_cancel_at: ActiveValue::set(
494                        subscription
495                            .cancel_at
496                            .and_then(|cancel_at| DateTime::from_timestamp(cancel_at, 0))
497                            .map(|time| time.naive_utc()),
498                    ),
499                },
500            )
501            .await?;
502    } else {
503        app.db
504            .create_billing_subscription(&CreateBillingSubscriptionParams {
505                billing_customer_id: billing_customer.id,
506                stripe_subscription_id: subscription.id.to_string(),
507                stripe_subscription_status: subscription.status.into(),
508            })
509            .await?;
510    }
511
512    Ok(())
513}
514
515impl From<SubscriptionStatus> for StripeSubscriptionStatus {
516    fn from(value: SubscriptionStatus) -> Self {
517        match value {
518            SubscriptionStatus::Incomplete => Self::Incomplete,
519            SubscriptionStatus::IncompleteExpired => Self::IncompleteExpired,
520            SubscriptionStatus::Trialing => Self::Trialing,
521            SubscriptionStatus::Active => Self::Active,
522            SubscriptionStatus::PastDue => Self::PastDue,
523            SubscriptionStatus::Canceled => Self::Canceled,
524            SubscriptionStatus::Unpaid => Self::Unpaid,
525            SubscriptionStatus::Paused => Self::Paused,
526        }
527    }
528}
529
530/// Finds or creates a billing customer using the provided customer.
531async fn find_or_create_billing_customer(
532    app: &Arc<AppState>,
533    stripe_client: &stripe::Client,
534    customer_or_id: Expandable<Customer>,
535) -> anyhow::Result<Option<billing_customer::Model>> {
536    let customer_id = match &customer_or_id {
537        Expandable::Id(id) => id,
538        Expandable::Object(customer) => customer.id.as_ref(),
539    };
540
541    // If we already have a billing customer record associated with the Stripe customer,
542    // there's nothing more we need to do.
543    if let Some(billing_customer) = app
544        .db
545        .get_billing_customer_by_stripe_customer_id(&customer_id)
546        .await?
547    {
548        return Ok(Some(billing_customer));
549    }
550
551    // If all we have is a customer ID, resolve it to a full customer record by
552    // hitting the Stripe API.
553    let customer = match customer_or_id {
554        Expandable::Id(id) => Customer::retrieve(&stripe_client, &id, &[]).await?,
555        Expandable::Object(customer) => *customer,
556    };
557
558    let Some(email) = customer.email else {
559        return Ok(None);
560    };
561
562    let Some(user) = app.db.get_user_by_email(&email).await? else {
563        return Ok(None);
564    };
565
566    let billing_customer = app
567        .db
568        .create_billing_customer(&CreateBillingCustomerParams {
569            user_id: user.id,
570            stripe_customer_id: customer.id.to_string(),
571        })
572        .await?;
573
574    Ok(Some(billing_customer))
575}