Skip to content

g1t/services/billing/src/stripe.rs

1,483 lines65,232 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Paid features: a workspace turns on Deployments with a monthly plan1//! The card processor, behind the calls billing needs: start a payment
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look2//! page, save and verify a card, ask whether a payment was made, and start,
3//! read or end the monthly plan. Stripe speaks form-encoded requests and
4//! JSON answers.
5//!
6//! Every Stripe object billing needs beyond customers and their payments
7//! (the plan's product, the billing page's settings) is made the first time
8//! it is needed, and found again by its `metadata[g1t]` after that.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit9//!
10//! Every request names the API version it is written for
11//! (`STRIPE_VERSION`). Without it Stripe answers at the account's default,
12//! which for an account made today is a newer version than this code reads:
13//! invoices no longer carry `subscription`, charges no longer carry
14//! `invoice`, and parameters this code sends can be refused. A failure is
15//! never shown raw: `friendly` turns it into a sentence for the page.
Agents as a team: lifecycle, merge queue, billing and a new shell16
17use serde::Deserialize;
18use worker::{Error, Fetch, Headers, Method, Request, RequestInit, Result};
19
20const API: &str = "https://api.stripe.com/v1";
21
Usage, Billing settings and prepaid AI credit; fixes from the UX audit22/// The Stripe API version billing is written against. Changing it is a
23/// code change: read Stripe's upgrade notes for every field billing reads.
24pub(crate) const STRIPE_VERSION: &str = "2025-02-24.acacia";
25
Merge Stripe Tax, the card fee on card payments, and one free workspace per person26/// Stripe Tax's code for what g1t sells, on every product, price and
27/// invoice line: software as a service, for business use. A card fee line
28/// carries it too, since a fee for paying for a sale is taxed as the sale.
29pub(crate) const TAX_CODE: &str = "txcd_10103001";
30
31/// What every payment page (payment or subscription mode) asks of Stripe
32/// Tax: tax worked out on top of the price shown, from a billing address
33/// it always collects, with the buyer's tax ID if they have one. With a
34/// customer already, what was entered is saved on it, so invoices and
35/// off-session charges later find the address too. Checkout refuses
36/// `automatic_tax` for a customer with no address unless it may save one
37/// (`customer_update[address]`), and `tax_id_collection` unless it may save
38/// the name (`customer_update[name]`).
39pub(crate) fn checkout_tax_fields(customer: Option<&str>) -> Vec<(&'static str, String)> {
40 let mut fields = vec![
41 ("automatic_tax[enabled]", "true".to_owned()),
42 ("billing_address_collection", "required".to_owned()),
43 ("tax_id_collection[enabled]", "true".to_owned()),
44 ];
45 if customer.is_some() {
46 fields.extend([("customer_update[address]", "auto".to_owned()), ("customer_update[name]", "auto".to_owned())]);
47 }
48 fields
49}
50
51/// Whether Stripe refused because it could not tell where the customer is
52/// for tax: no address, or not enough of one.
53pub(crate) fn is_tax_location_error(error: &Error) -> bool {
54 let text = error.to_string();
55 text.contains("customer_tax_location_invalid") || text.contains("requires_location_inputs")
56}
57
58/// Whether an address is enough for Stripe Tax to place the customer: a
59/// country, and in the United States a postal code (in Canada a postal
60/// code or a province).
61pub(crate) fn address_places_customer(address: &serde_json::Value) -> bool {
62 let text = |key: &str| address[key].as_str().map(str::trim).unwrap_or_default().to_owned();
63 match text("country").to_uppercase().as_str() {
64 "" => false,
65 "US" => !text("postal_code").is_empty(),
66 "CA" => !text("postal_code").is_empty() || !text("state").is_empty(),
67 _ => true,
68 }
69}
70
Usage, Billing settings and prepaid AI credit; fixes from the UX audit71/// What a Stripe failure says, for the person on the page: Stripe's own
72/// message when it gave one (never the request or any key), else that it
73/// could not be reached.
74pub(crate) fn friendly(error: &Error) -> String {
75 let text = error.to_string();
76 let message = text
77 .split_once(": ")
78 .and_then(|(_, body)| serde_json::from_str::<serde_json::Value>(body).ok())
79 .and_then(|body| body["error"]["message"].as_str().map(str::to_owned));
80 match message {
81 Some(message) => format!("Stripe refused it: {}", message.trim_end_matches('.').to_owned() + "."),
82 None if text.contains("the card processor answered") => "Stripe refused it. Try again in a minute; if it keeps happening, write to support@g1t.sh.".to_owned(),
83 None => "Stripe could not be reached. Try again in a minute.".to_owned(),
84 }
85}
86
87/// Whether Stripe declined a card (as opposed to refusing the request).
88pub(crate) fn is_card_error(error: &Error) -> bool {
89 let text = error.to_string();
90 text.contains("\"card_error\"") || text.contains("authentication_required")
91}
92
Agents as a team: lifecycle, merge queue, billing and a new shell93pub struct Stripe {
94 key: String,
95}
96
97/// A payment page, and the payment made through it.
98#[derive(Deserialize)]
99pub struct Session {
100 pub id: String,
101 /// Where to send the person. Absent once the page has been used.
102 pub url: Option<String>,
103 /// `paid` once the money has been taken.
104 pub payment_status: String,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person105 /// What was paid, in cents, tax included.
Agents as a team: lifecycle, merge queue, billing and a new shell106 pub amount_total: Option<u32>,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person107 /// What the lines came to before tax, in cents.
108 #[serde(default)]
109 pub amount_subtotal: Option<u32>,
110 /// The tax Stripe added (`amount_tax`), among other totals.
111 #[serde(default)]
112 pub total_details: Option<TotalDetails>,
113 /// For a payment page: the payment that took the money.
114 #[serde(default)]
115 pub payment_intent: Option<String>,
Agents as a team: lifecycle, merge queue, billing and a new shell116 pub customer: Option<String>,
Paid features: a workspace turns on Deployments with a monthly plan117 /// For a plan's page: the subscription it started.
118 #[serde(default)]
119 pub subscription: Option<String>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look120 /// For a card check's page: the setup that saved and verified the card.
121 #[serde(default)]
122 pub setup_intent: Option<String>,
123}
124
Merge Stripe Tax, the card fee on card payments, and one free workspace per person125#[derive(Default, Deserialize)]
126pub struct TotalDetails {
127 #[serde(default)]
128 pub amount_tax: i64,
129}
130
131impl Session {
132 /// The tax Stripe added on the page, in cents.
133 pub fn tax_cents(&self) -> i64 {
134 self.total_details.as_ref().map_or(0, |t| t.amount_tax.max(0))
135 }
136
137 /// What the page's lines came to before tax, in cents: the total less
138 /// the tax when Stripe gives no subtotal.
139 pub fn before_tax_cents(&self) -> i64 {
140 match self.amount_subtotal {
141 Some(subtotal) => i64::from(subtotal),
142 None => (i64::from(self.amount_total.unwrap_or(0)) - self.tax_cents()).max(0),
143 }
144 }
145}
146
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look147/// A card saved and verified: what a card check found.
148#[derive(Debug, Deserialize)]
149pub struct CheckedCard {
150 pub payment_method: String,
151 pub fingerprint: Option<String>,
152 pub brand: Option<String>,
153 pub last4: Option<String>,
154 /// `credit`, `debit`, `prepaid` or `unknown`.
155 pub funding: Option<String>,
156 pub country: Option<String>,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person157 /// The billing address entered with the card, as Stripe keeps it.
158 #[serde(default)]
159 pub address: Option<serde_json::Value>,
Agents as a team: lifecycle, merge queue, billing and a new shell160}
161
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace162/// g1t's settings for Stripe's hosted billing page.
163#[derive(Debug, Deserialize)]
164pub struct PortalConfiguration {
165 pub id: String,
166 #[serde(default)]
167 pub login_page: Option<LoginPage>,
168 #[serde(default)]
169 pub metadata: Option<std::collections::HashMap<String, String>>,
170}
171
172#[derive(Debug, Deserialize)]
173pub struct LoginPage {
174 pub url: Option<String>,
175}
176
Paid features: a workspace turns on Deployments with a monthly plan177/// A monthly plan.
178#[derive(Deserialize)]
179pub struct StripeSubscription {
180 pub id: String,
181 /// `active`, `trialing`, `past_due`, `unpaid`, `canceled`, `incomplete`…
182 pub status: String,
183 #[serde(default)]
184 pub cancel_at_period_end: bool,
185 /// Unix seconds. Older API versions carry it here…
186 #[serde(default)]
187 pub current_period_end: Option<i64>,
188 /// …newer ones on each item.
189 #[serde(default)]
190 pub items: Option<Items>,
191}
192
193#[derive(Deserialize)]
194pub struct Items {
195 pub data: Vec<Item>,
196}
197
198#[derive(Deserialize)]
199pub struct Item {
200 #[serde(default)]
201 pub current_period_end: Option<i64>,
202}
203
204impl StripeSubscription {
205 /// When the period paid for ends, in Unix seconds.
206 pub fn period_end(&self) -> Option<i64> {
207 self.current_period_end.or_else(|| {
208 self.items
209 .as_ref()
210 .and_then(|items| items.data.iter().filter_map(|item| item.current_period_end).max())
211 })
212 }
213}
214
Agents as a team: lifecycle, merge queue, billing and a new shell215/// Percent-encodes a form value.
216fn encode(value: &str) -> String {
217 let mut encoded = String::with_capacity(value.len());
218 for byte in value.bytes() {
219 match byte {
220 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
221 encoded.push(byte as char);
222 }
223 _ => encoded.push_str(&format!("%{byte:02X}")),
224 }
225 }
226 encoded
227}
228
229/// `name=value` pairs as a form body.
Billing: ask Stripe for tax only where Stripe Tax is active230/// Requests that carry `automatic_tax`: payment pages, invoices and
231/// subscriptions. When Stripe Tax is not active for the key's mode (a test
232/// account where it was never turned on), Stripe refuses them outright, so
233/// the field is left out and the payment goes through untaxed.
234pub(crate) fn taxed_path(path: &str) -> bool {
235 path == "/checkout/sessions" || path == "/invoices" || path == "/subscriptions"
236}
237
238/// A form body without its `automatic_tax[…]` fields.
239pub(crate) fn without_automatic_tax(body: &str) -> String {
240 body.split('&').filter(|pair| !pair.starts_with("automatic_tax")).collect::<Vec<_>>().join("&")
241}
242
243/// How long whether Stripe Tax is active is believed, in milliseconds.
244const TAX_ACTIVE_FOR_MS: u64 = 10 * 60 * 1000;
245
246thread_local! {
247 /// Whether Stripe Tax is active for the key, and when that was read.
248 static TAX_ACTIVE: std::cell::Cell<Option<(bool, u64)>> = const { std::cell::Cell::new(None) };
249}
250
Agents as a team: lifecycle, merge queue, billing and a new shell251pub(crate) fn form(fields: &[(&str, String)]) -> String {
252 fields
253 .iter()
254 .map(|(name, value)| format!("{}={}", encode(name), encode(value)))
255 .collect::<Vec<_>>()
256 .join("&")
257}
258
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging259/// The idempotency key for starting a plan on a saved card: the same
260/// workspace, plan and card within the same ten minutes is one subscription,
261/// however many times it is asked for (a double click, two tabs), so a
262/// workspace is never billed twice for one plan. A different card is a new
263/// attempt, as Stripe refuses a key reused with other fields.
264pub(crate) fn plan_key(workspace: &str, feature: &str, payment_method: &str, now_ms: u64) -> String {
265 format!("plan/{workspace}/{feature}/{payment_method}/{}", now_ms / 600_000)
266}
267
Agents as a team: lifecycle, merge queue, billing and a new shell268impl Stripe {
269 pub fn new(key: String) -> Self {
270 Stripe { key }
271 }
272
273 /// Whether the key is for real cards, not Stripe's test mode.
274 pub fn live(&self) -> bool {
275 is_live(&self.key)
276 }
277
Stripe webhooks, enterprise invoices, and sudo for both278 /// A GET of any Stripe resource, for the webhook handlers.
279 pub(crate) async fn get<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
280 self.call(Method::Get, path, None).await
281 }
282
Usage, Billing settings and prepaid AI credit; fixes from the UX audit283 /// A DELETE of any Stripe resource.
284 pub(crate) async fn delete<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
285 self.call(Method::Delete, path, None).await
286 }
287
Stripe webhooks, enterprise invoices, and sudo for both288 /// A form POST to any Stripe resource.
289 pub(crate) async fn post<T: for<'a> Deserialize<'a>>(&self, path: &str, fields: &[(&str, String)]) -> Result<T> {
290 self.call(Method::Post, path, Some(form(fields))).await
291 }
292
Two limits, real invoices, trust that grows by itself, sales signals293 /// A form POST that Stripe does at most once for `key`, however often
294 /// it is sent.
295 pub(crate) async fn post_idempotent<T: for<'a> Deserialize<'a>>(
296 &self,
297 path: &str,
298 fields: &[(&str, String)],
299 key: &str,
300 ) -> Result<T> {
301 self.send(Method::Post, path, Some(form(fields)), Some(key)).await
302 }
303
Agents as a team: lifecycle, merge queue, billing and a new shell304 async fn call<T: for<'a> Deserialize<'a>>(
305 &self,
306 method: Method,
307 path: &str,
308 body: Option<String>,
309 ) -> Result<T> {
Billing accounts, terms and enterprises; g1t is no longer free310 self.send(method, path, body, None).await
311 }
312
313 async fn send<T: for<'a> Deserialize<'a>>(
314 &self,
315 method: Method,
316 path: &str,
317 body: Option<String>,
318 idempotency_key: Option<&str>,
319 ) -> Result<T> {
Billing: ask Stripe for tax only where Stripe Tax is active320 let body = match body {
321 Some(body) if matches!(method, Method::Post) && taxed_path(path) && body.contains("automatic_tax") && !self.tax_active().await => {
322 Some(without_automatic_tax(&body))
323 }
324 body => body,
325 };
326 self.send_raw(method, path, body, idempotency_key).await
327 }
328
329 /// The request itself, as given: `send` without the Stripe Tax check.
330 async fn send_raw<T: for<'a> Deserialize<'a>>(
331 &self,
332 method: Method,
333 path: &str,
334 body: Option<String>,
335 idempotency_key: Option<&str>,
336 ) -> Result<T> {
Agents as a team: lifecycle, merge queue, billing and a new shell337 let headers = Headers::new();
338 headers.set("authorization", &format!("Bearer {}", self.key))?;
Usage, Billing settings and prepaid AI credit; fixes from the UX audit339 headers.set("stripe-version", STRIPE_VERSION)?;
Billing accounts, terms and enterprises; g1t is no longer free340 if let Some(key) = idempotency_key {
341 headers.set("idempotency-key", key)?;
342 }
Agents as a team: lifecycle, merge queue, billing and a new shell343 if body.is_some() {
344 headers.set("content-type", "application/x-www-form-urlencoded")?;
345 }
346 let mut init = RequestInit::new();
347 init.with_method(method).with_headers(headers);
348 if let Some(body) = body {
349 init.with_body(Some(body.into()));
350 }
351 let request = Request::new_with_init(&format!("{API}{path}"), &init)?;
352 let mut response = Fetch::Request(request).send().await?;
353 if response.status_code() != 200 {
354 return Err(Error::RustError(format!(
355 "the card processor answered {}: {}",
356 response.status_code(),
357 response.text().await.unwrap_or_default()
358 )));
359 }
360 response.json().await
Billing accounts, terms and enterprises; g1t is no longer free361 }
362
Billing: ask Stripe for tax only where Stripe Tax is active363 /// Whether Stripe Tax is active for this key's mode (`GET /tax/settings`,
364 /// `status` `active`), read at most every ten minutes. When it cannot be
365 /// read, it is taken as active: asking for tax and being refused says
366 /// why, where leaving it out would undercharge without a word.
367 pub async fn tax_active(&self) -> bool {
368 let now = crate::now_ms();
369 if let Some((active, at)) = TAX_ACTIVE.with(|cell| cell.get())
370 && now.saturating_sub(at) < TAX_ACTIVE_FOR_MS
371 {
372 return active;
373 }
374 #[derive(Deserialize)]
375 struct Settings {
376 status: String,
377 }
378 let active = match self.send_raw::<Settings>(Method::Get, "/tax/settings", None, None).await {
379 Ok(settings) => settings.status == "active",
380 Err(error) => {
381 worker::console_error!("Stripe Tax settings could not be read; asking for tax anyway: {error}");
382 true
383 }
384 };
385 TAX_ACTIVE.with(|cell| cell.set(Some((active, now))));
386 active
387 }
388
Billing on Stripe's pages, month-end charges, warnings; sudo by workspace389 /// A customer for a workspace that has none yet.
390 pub async fn create_customer(&self, workspace: &str) -> Result<String> {
391 #[derive(Deserialize)]
392 struct Customer {
393 id: String,
394 }
395 let fields = [
396 ("name", workspace.to_owned()),
397 ("metadata[workspace]", workspace.to_owned()),
398 ];
399 let customer: Customer = self.call(Method::Post, "/customers", Some(form(&fields))).await?;
400 Ok(customer.id)
401 }
402
403 /// A session on Stripe's hosted billing page (the customer portal) for
404 /// the customer, coming back to `return_url`.
405 pub async fn portal_session(&self, customer: &str, return_url: &str) -> Result<String> {
406 #[derive(Deserialize)]
407 struct Portal {
408 url: String,
409 }
410 let configuration = self.portal_configuration().await?;
411 let fields = [
412 ("customer", customer.to_owned()),
413 ("return_url", return_url.to_owned()),
414 ("configuration", configuration.id),
415 ];
416 let portal: Portal = self.call(Method::Post, "/billing_portal/sessions", Some(form(&fields))).await?;
417 Ok(portal.url)
418 }
419
420 /// g1t's billing page settings at Stripe, made the first time they are
421 /// needed: cards, invoices, billing details, and a sign-in page.
422 pub async fn portal_configuration(&self) -> Result<PortalConfiguration> {
423 #[derive(Deserialize)]
424 struct List {
425 data: Vec<PortalConfiguration>,
426 }
427 let list: List = self
428 .call(Method::Get, "/billing_portal/configurations?active=true&limit=20", None)
429 .await?;
430 if let Some(existing) = list
431 .data
432 .into_iter()
433 .find(|c| c.metadata.as_ref().and_then(|m| m.get("g1t")).is_some())
434 {
435 return Ok(existing);
436 }
437 let fields = [
438 ("business_profile[headline]", "g1t billing: your card, invoices and billing details".to_owned()),
439 ("features[payment_method_update][enabled]", "true".to_owned()),
440 ("features[invoice_history][enabled]", "true".to_owned()),
441 ("features[customer_update][enabled]", "true".to_owned()),
442 ("features[customer_update][allowed_updates][0]", "email".to_owned()),
443 ("features[customer_update][allowed_updates][1]", "address".to_owned()),
444 ("features[customer_update][allowed_updates][2]", "name".to_owned()),
445 ("features[customer_update][allowed_updates][3]", "tax_id".to_owned()),
446 ("login_page[enabled]", "true".to_owned()),
447 ("metadata[g1t]", "billing".to_owned()),
448 ];
449 self.call(Method::Post, "/billing_portal/configurations", Some(form(&fields))).await
450 }
451
452 /// The customer's email at Stripe, if they gave one.
453 pub async fn customer_email(&self, customer: &str) -> Result<Option<String>> {
454 #[derive(Deserialize)]
455 struct Customer {
456 email: Option<String>,
457 }
458 let found: Customer = self.call(Method::Get, &format!("/customers/{}", encode(customer)), None).await?;
459 Ok(found.email)
460 }
461
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look462 /// Starts a page on which `amount_cents` is paid in advance: by card,
463 /// with 3-D Secure asked for wherever the card supports it, the card
464 /// kept for later charges; or, with `bank_transfer` and a customer, by
465 /// bank transfer to the account details Stripe gives, counted when the
466 /// money arrives.
Agents as a team: lifecycle, merge queue, billing and a new shell467 pub async fn start_checkout(
468 &self,
469 workspace: &str,
470 amount_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person471 fee_cents: u32,
Agents as a team: lifecycle, merge queue, billing and a new shell472 customer: Option<&str>,
473 return_url: &str,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look474 bank_transfer: bool,
Agents as a team: lifecycle, merge queue, billing and a new shell475 ) -> Result<Session> {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person476 let fields = prepay_fields(workspace, amount_cents, fee_cents, customer, return_url, bank_transfer);
477 let key = page_key(
478 "prepay",
479 workspace,
480 &format!("{amount_cents}/{fee_cents}/{bank_transfer}/{}", customer.unwrap_or("new")),
481 g1t_kit::now_ms(),
482 );
Usage, Billing settings and prepaid AI credit; fixes from the UX audit483 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
Agents as a team: lifecycle, merge queue, billing and a new shell484 }
485
Merge Stripe Tax, the card fee on card payments, and one free workspace per person486 /// Starts a page on which a feature's monthly plan is paid for by card,
487 /// with the card fee as a monthly line of its own.
488 #[allow(clippy::too_many_arguments)]
Paid features: a workspace turns on Deployments with a monthly plan489 pub async fn start_subscription(
490 &self,
491 workspace: &str,
492 feature: &str,
493 title: &str,
494 monthly_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person495 fee_cents: u32,
Paid features: a workspace turns on Deployments with a monthly plan496 customer: Option<&str>,
497 return_url: &str,
498 ) -> Result<Session> {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person499 let fields = subscription_fields(workspace, feature, title, monthly_cents, fee_cents, customer, return_url);
500 let key = page_key(
501 "plan",
502 workspace,
503 &format!("{feature}/{monthly_cents}/{fee_cents}/{}", customer.unwrap_or("new")),
504 g1t_kit::now_ms(),
505 );
Usage, Billing settings and prepaid AI credit; fixes from the UX audit506 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
Paid features: a workspace turns on Deployments with a monthly plan507 }
508
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look509 /// Starts a page that saves and verifies a card, with 3-D Secure asked
510 /// for wherever the card supports it. Nothing is charged: the card's
511 /// bank sees at most a $0 or $1 authorization that is never captured.
512 pub async fn start_card_check(&self, workspace: &str, customer: &str, return_url: &str) -> Result<Session> {
Usage, Billing settings and prepaid AI credit; fixes from the UX audit513 let fields = card_check_fields(workspace, customer, return_url);
514 let key = page_key("card_check", workspace, customer, g1t_kit::now_ms());
515 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
516 }
517
518 /// Starts a page on which AI credit is bought: one payment by card, the
519 /// card fee as its own line, the card kept for auto-reload.
520 pub async fn start_credit_checkout(&self, purchase: &CreditPurchase<'_>) -> Result<Session> {
521 let fields = credit_fields(purchase);
522 let key = page_key(
523 "ai_credit",
524 purchase.workspace,
525 &format!("{}/{}/{}", purchase.credit_cents, purchase.fee_cents, purchase.customer.unwrap_or("new")),
526 g1t_kit::now_ms(),
527 );
528 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
529 }
530
531 /// The customer's default payment method: the one its invoices are
532 /// charged to, else its newest card. None when it has none.
533 pub async fn default_payment_method(&self, customer: &str) -> Result<Option<SavedMethod>> {
534 let found: serde_json::Value = self
535 .call(
536 Method::Get,
537 &format!("/customers/{}?expand[]=invoice_settings.default_payment_method", encode(customer)),
538 None,
539 )
540 .await?;
541 if let Some(method) = SavedMethod::from_json(&found["invoice_settings"]["default_payment_method"]) {
542 return Ok(Some(method));
543 }
544 let list: serde_json::Value = self
545 .call(Method::Get, &format!("/payment_methods?customer={}&type=card&limit=1", encode(customer)), None)
546 .await?;
547 Ok(list["data"].as_array().and_then(|data| data.first()).and_then(SavedMethod::from_json))
548 }
549
550 /// The customer as Stripe keeps it, with its tax ids.
551 pub async fn customer(&self, customer: &str) -> Result<serde_json::Value> {
552 self.call(Method::Get, &format!("/customers/{}?expand[]=tax_ids", encode(customer)), None).await
553 }
554
555 /// The customer's invoices, newest first.
556 pub async fn invoices(&self, customer: &str) -> Result<Vec<serde_json::Value>> {
557 let list: serde_json::Value = self.call(Method::Get, &format!("/invoices?customer={}&limit=24", encode(customer)), None).await?;
558 Ok(list["data"].as_array().cloned().unwrap_or_default())
559 }
560
561 /// Charges a saved payment method now, with nobody there: auto-reload.
562 /// Done at most once for `key`, however often it is sent.
563 pub async fn charge_saved(&self, charge: &SavedCharge<'_>) -> Result<serde_json::Value> {
564 self.send(Method::Post, "/payment_intents", Some(form(&saved_charge_fields(charge))), Some(charge.key)).await
565 }
Merge Stripe Tax, the card fee on card payments, and one free workspace per person566
567 /// Stripe Tax's figure for an off-session charge, which no Checkout
568 /// page or invoice works out: the credit and the card fee, each at
569 /// g1t's tax code and excluding tax, for the customer's saved address.
570 /// A customer Stripe cannot place fails with
571 /// `customer_tax_location_invalid` (`is_tax_location_error`).
572 pub async fn tax_calculation(&self, charge: &SavedCharge<'_>) -> Result<TaxCalculation> {
Billing: ask Stripe for tax only where Stripe Tax is active573 if !self.tax_active().await {
574 // No Stripe Tax for this key's mode: no tax, and nothing to record.
575 return Ok(TaxCalculation { id: String::new(), tax_amount_exclusive: 0 });
576 }
Merge Stripe Tax, the card fee on card payments, and one free workspace per person577 let key = format!("{}/tax", charge.key);
578 self.send(Method::Post, "/tax/calculations", Some(form(&tax_calculation_fields(charge))), Some(&key)).await
579 }
580
581 /// Records a calculation as a tax transaction once its payment went
582 /// through, so Stripe Tax reports and files it; `reference` is the
583 /// PaymentIntent. Its id, for reversing it on a refund.
584 pub async fn record_tax(&self, calculation: &str, reference: &str) -> Result<String> {
585 #[derive(Deserialize)]
586 struct Transaction {
587 id: String,
588 }
589 let fields = [("calculation", calculation.to_owned()), ("reference", reference.to_owned())];
590 let made: Transaction = self
591 .send(Method::Post, "/tax/transactions/create_from_calculation", Some(form(&fields)), Some(&format!("tax/{reference}")))
592 .await?;
593 Ok(made.id)
594 }
595
596 /// Reverses a tax transaction in part for a refund: `refunded_cents` of
597 /// the payment, tax included, taken back across all of it.
598 pub async fn reverse_tax(&self, transaction: &str, reference: &str, refunded_cents: i64) -> Result<()> {
599 let _: serde_json::Value = self
600 .send(
601 Method::Post,
602 "/tax/transactions/create_reversal",
603 Some(form(&reversal_fields(transaction, reference, refunded_cents))),
604 Some(&format!("tax-reversal/{reference}")),
605 )
606 .await?;
607 Ok(())
608 }
609
610 /// Copies the billing address entered with a card onto the customer
611 /// when the customer has none Stripe Tax can use, so later invoices and
612 /// charges can be taxed. Never replaces an address an owner gave.
613 pub async fn fill_address(&self, customer: &str, address: &serde_json::Value) -> Result<bool> {
614 if !address_places_customer(address) {
615 return Ok(false);
616 }
617 let found = self.customer(customer).await?;
618 if address_places_customer(&found["address"]) {
619 return Ok(false);
620 }
621 let _: serde_json::Value = self.post(&format!("/customers/{}", encode(customer)), &address_fields(address)).await?;
622 Ok(true)
623 }
624
625 /// Whether the customer's address is enough for Stripe Tax.
626 pub async fn customer_placed(&self, customer: &str) -> Result<bool> {
627 let found = self.customer(customer).await?;
628 Ok(address_places_customer(&found["address"]) || address_places_customer(&found["shipping"]["address"]))
629 }
630}
631
632/// Stripe Tax's answer for an off-session charge.
633#[derive(Debug, Deserialize)]
634pub struct TaxCalculation {
635 pub id: String,
636 /// The tax on top, in cents.
637 #[serde(default)]
638 pub tax_amount_exclusive: i64,
639}
640
641/// A customer's address from an address Stripe gave.
642pub(crate) fn address_fields(address: &serde_json::Value) -> Vec<(&'static str, String)> {
643 let text = |key: &str| address[key].as_str().unwrap_or_default().to_owned();
644 vec![
645 ("address[line1]", text("line1")),
646 ("address[line2]", text("line2")),
647 ("address[city]", text("city")),
648 ("address[state]", text("state")),
649 ("address[postal_code]", text("postal_code")),
650 ("address[country]", text("country")),
651 ]
652}
653
654/// A tax calculation's fields: the credit and the card fee as lines at
655/// g1t's tax code, prices excluding tax.
656pub(crate) fn tax_calculation_fields(c: &SavedCharge<'_>) -> Vec<(&'static str, String)> {
657 let mut fields = vec![
658 ("currency", "usd".to_owned()),
659 ("customer", c.customer.to_owned()),
660 ("line_items[0][amount]", c.credit_cents.to_string()),
661 ("line_items[0][reference]", "ai_credit".to_owned()),
662 ("line_items[0][tax_code]", TAX_CODE.to_owned()),
663 ("line_items[0][tax_behavior]", "exclusive".to_owned()),
664 ];
665 if c.fee_cents > 0 {
666 fields.extend([
667 ("line_items[1][amount]", c.fee_cents.to_string()),
668 ("line_items[1][reference]", "card_fee".to_owned()),
669 ("line_items[1][tax_code]", TAX_CODE.to_owned()),
670 ("line_items[1][tax_behavior]", "exclusive".to_owned()),
671 ]);
672 }
673 fields
Usage, Billing settings and prepaid AI credit; fixes from the UX audit674}
675
Merge Stripe Tax, the card fee on card payments, and one free workspace per person676/// A refund's tax reversal: a part of the payment, as a negative amount.
677pub(crate) fn reversal_fields(transaction: &str, reference: &str, refunded_cents: i64) -> Vec<(&'static str, String)> {
678 vec![
679 ("mode", "partial".to_owned()),
680 ("original_transaction", transaction.to_owned()),
681 ("reference", reference.to_owned()),
682 ("flat_amount", (-refunded_cents.abs()).to_string()),
683 ]
684}
685
Usage, Billing settings and prepaid AI credit; fixes from the UX audit686/// An AI credit purchase, as its payment page needs it.
687pub struct CreditPurchase<'a> {
688 pub workspace: &'a str,
689 pub credit_cents: u32,
690 pub fee_cents: u32,
691 pub customer: Option<&'a str>,
692 pub return_url: &'a str,
693}
694
695/// A charge to a saved card with nobody there.
696pub struct SavedCharge<'a> {
697 pub workspace: &'a str,
698 pub customer: &'a str,
699 pub payment_method: &'a str,
700 pub credit_cents: u32,
701 pub fee_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person702 /// Tax on top, from `tax_calculation`.
703 pub tax_cents: u32,
704 /// The calculation the tax came from, kept on the payment.
705 pub tax_calculation: Option<&'a str>,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit706 pub key: &'a str,
707}
708
709/// A saved way to pay, as far as it is safe to show.
710#[derive(Clone, Debug, PartialEq)]
711pub struct SavedMethod {
712 pub id: String,
713 pub kind: String,
714 pub brand: Option<String>,
715 pub last4: Option<String>,
716 pub exp_month: Option<u32>,
717 pub exp_year: Option<u32>,
718}
719
720impl SavedMethod {
721 fn from_json(method: &serde_json::Value) -> Option<SavedMethod> {
722 let id = method["id"].as_str()?.to_owned();
723 let kind = method["type"].as_str().unwrap_or("card").to_owned();
724 let details = &method[kind.as_str()];
725 Some(SavedMethod {
726 id,
727 brand: details["brand"].as_str().or_else(|| details["bank_name"].as_str()).map(str::to_owned),
728 last4: details["last4"].as_str().map(str::to_owned),
729 exp_month: details["exp_month"].as_u64().map(|m| m as u32),
730 exp_year: details["exp_year"].as_u64().map(|y| y as u32),
731 kind,
732 })
733 }
734}
735
736/// The idempotency key for a payment page: the same workspace, purpose and
737/// details within ten minutes is one page, however often it is asked for (a
738/// double click, two tabs).
739pub(crate) fn page_key(purpose: &str, workspace: &str, details: &str, now_ms: u64) -> String {
740 format!("page/{purpose}/{workspace}/{details}/{}", now_ms / 600_000)
741}
742
743/// Where Stripe sends the person back, with the page's id under `name`.
744fn back_to(return_url: &str, name: &str) -> String {
745 let separator = if return_url.contains('?') { '&' } else { '?' };
746 // Stripe fills in the page's id.
747 format!("{return_url}{separator}{name}={{CHECKOUT_SESSION_ID}}")
748}
749
Merge Stripe Tax, the card fee on card payments, and one free workspace per person750/// The name of the card fee's line everywhere it appears: Checkout pages,
751/// subscriptions and invoices. Revenue figures find it by this name.
752pub(crate) const CARD_FEE_LINE: &str = "Card processing fee";
753
754/// The form keys of one line on a payment page, for the first two lines
755/// (what is bought, and the card fee).
756const LINE_KEYS: [[&str; 8]; 2] = [
757 [
758 "line_items[0][quantity]",
759 "line_items[0][price_data][currency]",
760 "line_items[0][price_data][unit_amount]",
761 "line_items[0][price_data][tax_behavior]",
762 "line_items[0][price_data][product_data][name]",
763 "line_items[0][price_data][product_data][tax_code]",
764 "line_items[0][price_data][product_data][description]",
765 "line_items[0][price_data][recurring][interval]",
766 ],
767 [
768 "line_items[1][quantity]",
769 "line_items[1][price_data][currency]",
770 "line_items[1][price_data][unit_amount]",
771 "line_items[1][price_data][tax_behavior]",
772 "line_items[1][price_data][product_data][name]",
773 "line_items[1][price_data][product_data][tax_code]",
774 "line_items[1][price_data][product_data][description]",
775 "line_items[1][price_data][recurring][interval]",
776 ],
777];
778
779/// One line on a payment page at g1t's tax code, its price excluding tax;
780/// monthly when `monthly`.
781fn page_line(index: usize, cents: u32, name: String, description: Option<String>, monthly: bool) -> Vec<(&'static str, String)> {
782 let keys = LINE_KEYS[index.min(1)];
783 let mut fields = vec![
784 (keys[0], "1".to_owned()),
785 (keys[1], "usd".to_owned()),
786 (keys[2], cents.to_string()),
787 (keys[3], "exclusive".to_owned()),
788 (keys[4], name),
789 (keys[5], TAX_CODE.to_owned()),
790 ];
791 if let Some(description) = description {
792 fields.push((keys[6], description));
793 }
794 if monthly {
795 fields.push((keys[7], "month".to_owned()));
796 }
797 fields
798}
799
800/// The card fee's line on a payment page, when there is a fee.
801fn fee_line(fee_cents: u32, monthly: bool) -> Vec<(&'static str, String)> {
802 if fee_cents == 0 {
803 return vec![];
804 }
805 page_line(1, fee_cents, CARD_FEE_LINE.to_owned(), Some("Stripe's fee for taking the payment by card, passed on at cost".to_owned()), monthly)
806}
807
808/// A prepayment page's fields. By card, the card fee is its own line; by
809/// bank transfer there is none.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit810pub(crate) fn prepay_fields(
811 workspace: &str,
812 amount_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person813 fee_cents: u32,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit814 customer: Option<&str>,
815 return_url: &str,
816 bank_transfer: bool,
817) -> Vec<(&'static str, String)> {
818 let mut fields = vec![("mode", "payment".to_owned())];
819 if bank_transfer {
820 fields.extend([
821 ("payment_method_types[0]", "customer_balance".to_owned()),
822 ("payment_method_options[customer_balance][funding_type]", "bank_transfer".to_owned()),
823 ("payment_method_options[customer_balance][bank_transfer][type]", "us_bank_transfer".to_owned()),
824 ]);
825 } else {
826 fields.extend([
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look827 ("payment_method_types[0]", "card".to_owned()),
828 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit829 ("payment_intent_data[setup_future_usage]", "off_session".to_owned()),
830 ]);
831 }
832 fields.extend([
833 ("success_url", back_to(return_url, "session")),
834 ("cancel_url", return_url.to_owned()),
835 ("client_reference_id", workspace.to_owned()),
836 ("metadata[workspace]", workspace.to_owned()),
837 ]);
Merge Stripe Tax, the card fee on card payments, and one free workspace per person838 fields.extend(page_line(0, amount_cents, format!("g1t usage paid in advance for {workspace}"), None, false));
839 if !bank_transfer {
840 fields.extend(fee_line(fee_cents, false));
841 }
842 fields.extend(checkout_tax_fields(customer));
Usage, Billing settings and prepaid AI credit; fixes from the UX audit843 match customer {
844 Some(customer) => fields.push(("customer", customer.to_owned())),
845 None => fields.push(("customer_creation", "always".to_owned())),
846 }
847 fields
848}
849
Merge Stripe Tax, the card fee on card payments, and one free workspace per person850/// A plan's page's fields: the plan, and the card fee as a monthly line of
851/// its own. In subscription mode Stripe makes the customer itself when
852/// there is none; `customer_creation` is for payment mode only. The
853/// subscription it starts keeps `automatic_tax`, so every renewal is taxed.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit854pub(crate) fn subscription_fields(
855 workspace: &str,
856 feature: &str,
857 title: &str,
858 monthly_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person859 fee_cents: u32,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit860 customer: Option<&str>,
861 return_url: &str,
862) -> Vec<(&'static str, String)> {
863 let mut fields = vec![
864 ("mode", "subscription".to_owned()),
865 ("payment_method_types[0]", "card".to_owned()),
866 ("success_url", back_to(return_url, "session")),
867 ("cancel_url", return_url.to_owned()),
868 ("client_reference_id", workspace.to_owned()),
869 ("metadata[workspace]", workspace.to_owned()),
870 ("metadata[feature]", feature.to_owned()),
871 ("subscription_data[metadata][workspace]", workspace.to_owned()),
872 ("subscription_data[metadata][feature]", feature.to_owned()),
873 ];
Merge Stripe Tax, the card fee on card payments, and one free workspace per person874 fields.extend(page_line(0, monthly_cents, format!("g1t {title} for {workspace}"), None, true));
875 fields.extend(fee_line(fee_cents, true));
876 fields.extend(checkout_tax_fields(customer));
Usage, Billing settings and prepaid AI credit; fixes from the UX audit877 if let Some(customer) = customer {
878 fields.push(("customer", customer.to_owned()));
879 }
880 fields
881}
882
Merge Stripe Tax, the card fee on card payments, and one free workspace per person883/// A card check's page's fields: setup mode, nothing charged, so nothing
884/// to tax. Setup mode takes no line items and no amount. The billing
885/// address is asked for all the same, and copied onto the customer once
886/// the card is checked (`fill_address`), so the plan and invoices that
887/// follow can be taxed.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit888pub(crate) fn card_check_fields(workspace: &str, customer: &str, return_url: &str) -> Vec<(&'static str, String)> {
889 vec![
890 ("mode", "setup".to_owned()),
891 ("customer", customer.to_owned()),
892 ("payment_method_types[0]", "card".to_owned()),
893 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
Merge Stripe Tax, the card fee on card payments, and one free workspace per person894 ("billing_address_collection", "required".to_owned()),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit895 ("success_url", back_to(return_url, "card_check")),
896 ("cancel_url", return_url.to_owned()),
897 ("client_reference_id", workspace.to_owned()),
898 ("metadata[workspace]", workspace.to_owned()),
899 ("metadata[purpose]", "card_check".to_owned()),
900 ("setup_intent_data[metadata][workspace]", workspace.to_owned()),
901 ("setup_intent_data[description]", format!("Card check for g1t workspace {workspace}; never charged")),
902 ]
903}
904
905/// An AI credit page's fields: the credit, and the card fee as its own
906/// line when there is one.
907pub(crate) fn credit_fields(p: &CreditPurchase<'_>) -> Vec<(&'static str, String)> {
908 let mut fields = vec![
909 ("mode", "payment".to_owned()),
910 ("payment_method_types[0]", "card".to_owned()),
911 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
912 // Kept for auto-reload, which charges it with nobody there.
913 ("payment_intent_data[setup_future_usage]", "off_session".to_owned()),
914 ("payment_intent_data[description]", format!("g1t AI credit for {}", p.workspace)),
915 ("payment_intent_data[metadata][workspace]", p.workspace.to_owned()),
916 ("payment_intent_data[metadata][purpose]", "ai_credit".to_owned()),
917 ("success_url", back_to(p.return_url, "ai_credit")),
918 ("cancel_url", p.return_url.to_owned()),
919 ("client_reference_id", p.workspace.to_owned()),
920 ("metadata[workspace]", p.workspace.to_owned()),
921 ("metadata[purpose]", "ai_credit".to_owned()),
922 ];
Merge Stripe Tax, the card fee on card payments, and one free workspace per person923 fields.extend(page_line(
924 0,
925 p.credit_cents,
926 "g1t AI credit".to_owned(),
927 Some(format!("Prepaid credit for Agent and AI Gateway usage in {}; expires a year after purchase", p.workspace)),
928 false,
929 ));
930 fields.extend(fee_line(p.fee_cents, false));
931 fields.extend(checkout_tax_fields(p.customer));
Usage, Billing settings and prepaid AI credit; fixes from the UX audit932 match p.customer {
933 Some(customer) => fields.push(("customer", customer.to_owned())),
934 None => fields.push(("customer_creation", "always".to_owned())),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look935 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit936 fields
937}
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look938
Merge Stripe Tax, the card fee on card payments, and one free workspace per person939/// An off-session charge's fields: the credit, the card fee and the tax
940/// Stripe Tax worked out for them, in one payment.
Usage, Billing settings and prepaid AI credit; fixes from the UX audit941pub(crate) fn saved_charge_fields(c: &SavedCharge<'_>) -> Vec<(&'static str, String)> {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person942 let mut fields = vec![
943 ("amount", (c.credit_cents + c.fee_cents + c.tax_cents).to_string()),
Usage, Billing settings and prepaid AI credit; fixes from the UX audit944 ("currency", "usd".to_owned()),
945 ("customer", c.customer.to_owned()),
946 ("payment_method", c.payment_method.to_owned()),
947 ("off_session", "true".to_owned()),
948 ("confirm", "true".to_owned()),
949 ("description", format!("g1t AI credit auto-reload for {}", c.workspace)),
950 ("metadata[workspace]", c.workspace.to_owned()),
951 ("metadata[purpose]", "ai_reload".to_owned()),
952 ("metadata[credit_cents]", c.credit_cents.to_string()),
953 ("metadata[fee_cents]", c.fee_cents.to_string()),
Merge Stripe Tax, the card fee on card payments, and one free workspace per person954 ("metadata[tax_cents]", c.tax_cents.to_string()),
955 ];
956 if let Some(calculation) = c.tax_calculation {
957 fields.push(("metadata[tax_calculation]", calculation.to_owned()));
958 }
959 fields
960}
961
962/// A Stripe invoice's tax settings, for every invoice g1t makes: worked out
963/// by Stripe Tax.
964pub(crate) fn invoice_tax_fields() -> Vec<(&'static str, String)> {
965 vec![("automatic_tax[enabled]", "true".to_owned())]
966}
967
968/// An invoice item's tax settings: g1t's tax code, the amount excluding tax.
969pub(crate) fn item_tax_fields() -> Vec<(&'static str, String)> {
970 vec![("tax_behavior", "exclusive".to_owned()), ("tax_code", TAX_CODE.to_owned())]
971}
972
973/// What a paid Stripe invoice comes to, as billing counts it: the tax
974/// (`tax`, in this API version), the card fee (its lines, by name), and
975/// what is left for what was sold, all in cents.
976#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
977pub(crate) struct InvoiceSplit {
978 pub tax_cents: i64,
979 pub fee_cents: i64,
980 pub net_cents: i64,
981}
982
983/// A plan started on a saved card, as its subscription needs it.
984pub(crate) struct SavedPlan<'a> {
985 pub workspace: &'a str,
986 pub feature: &'a str,
987 pub title: &'a str,
988 pub monthly_cents: u32,
989 pub fee_cents: u32,
990 pub customer: &'a str,
991 pub payment_method: &'a str,
Usage, Billing settings and prepaid AI credit; fixes from the UX audit992}
993
Merge Stripe Tax, the card fee on card payments, and one free workspace per person994/// A subscription's fields, started on a saved card: the plan, the card
995/// fee as a monthly item when there is one, each excluding tax, and Stripe
996/// Tax on.
997pub(crate) fn saved_subscription_fields(p: &SavedPlan<'_>, product: &str, fee_product: Option<&str>) -> Vec<(&'static str, String)> {
998 let mut fields = vec![
999 ("customer", p.customer.to_owned()),
1000 ("default_payment_method", p.payment_method.to_owned()),
1001 ("payment_behavior", "error_if_incomplete".to_owned()),
1002 ("automatic_tax[enabled]", "true".to_owned()),
1003 ("items[0][price_data][currency]", "usd".to_owned()),
1004 ("items[0][price_data][product]", product.to_owned()),
1005 ("items[0][price_data][unit_amount]", p.monthly_cents.to_string()),
1006 ("items[0][price_data][recurring][interval]", "month".to_owned()),
1007 ("items[0][price_data][tax_behavior]", "exclusive".to_owned()),
1008 ("metadata[workspace]", p.workspace.to_owned()),
1009 ("metadata[feature]", p.feature.to_owned()),
1010 ("description", format!("{} plan for {}", p.title, p.workspace)),
1011 ];
1012 if let (Some(fee_product), true) = (fee_product, p.fee_cents > 0) {
1013 fields.extend([
1014 ("items[1][price_data][currency]", "usd".to_owned()),
1015 ("items[1][price_data][product]", fee_product.to_owned()),
1016 ("items[1][price_data][unit_amount]", p.fee_cents.to_string()),
1017 ("items[1][price_data][recurring][interval]", "month".to_owned()),
1018 ("items[1][price_data][tax_behavior]", "exclusive".to_owned()),
1019 ]);
1020 }
1021 fields
1022}
1023
1024pub(crate) fn invoice_split(invoice: &serde_json::Value, amount_paid: i64) -> InvoiceSplit {
1025 let tax_cents = invoice["tax"].as_i64().unwrap_or(0).max(0);
1026 let fee_cents: i64 = invoice["lines"]["data"]
1027 .as_array()
1028 .map(|lines| {
1029 lines
1030 .iter()
1031 .filter(|line| line["description"].as_str().is_some_and(|d| d.contains(CARD_FEE_LINE)))
1032 .map(|line| line["amount"].as_i64().unwrap_or(0))
1033 .sum()
1034 })
1035 .unwrap_or(0);
1036 let fee_cents = fee_cents.max(0);
1037 InvoiceSplit { tax_cents, fee_cents, net_cents: (amount_paid - tax_cents - fee_cents).max(0) }
1038}
1039
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1040impl Stripe {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1041 /// What a card check's setup found, once it succeeded.
1042 pub async fn checked_card(&self, setup_intent: &str) -> Result<Option<CheckedCard>> {
1043 #[derive(Deserialize)]
1044 struct Setup {
1045 status: String,
1046 payment_method: Option<String>,
1047 }
1048 #[derive(Deserialize)]
1049 struct Card {
1050 fingerprint: Option<String>,
1051 brand: Option<String>,
1052 last4: Option<String>,
1053 funding: Option<String>,
1054 country: Option<String>,
1055 }
1056 #[derive(Deserialize)]
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1057 struct Billing {
1058 #[serde(default)]
1059 address: Option<serde_json::Value>,
1060 }
1061 #[derive(Deserialize)]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1062 struct PaymentMethod {
1063 card: Option<Card>,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1064 #[serde(default)]
1065 billing_details: Option<Billing>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1066 }
1067 let setup: Setup = self.call(Method::Get, &format!("/setup_intents/{}", encode(setup_intent)), None).await?;
1068 let (true, Some(method)) = (setup.status == "succeeded", setup.payment_method) else { return Ok(None) };
1069 let found: PaymentMethod = self.call(Method::Get, &format!("/payment_methods/{}", encode(&method)), None).await?;
1070 let card = found.card;
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1071 let address = found.billing_details.and_then(|b| b.address).filter(|a| a.is_object());
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1072 Ok(Some(CheckedCard {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1073 address,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1074 payment_method: method,
1075 fingerprint: card.as_ref().and_then(|c| c.fingerprint.clone()),
1076 brand: card.as_ref().and_then(|c| c.brand.clone()),
1077 last4: card.as_ref().and_then(|c| c.last4.clone()),
1078 funding: card.as_ref().and_then(|c| c.funding.clone()),
1079 country: card.as_ref().and_then(|c| c.country.clone()),
1080 }))
1081 }
1082
1083 /// Makes `payment_method` the card the customer's invoices are charged to.
1084 pub async fn set_default_card(&self, customer: &str, payment_method: &str) -> Result<()> {
1085 let _: serde_json::Value = self
1086 .call(
1087 Method::Post,
1088 &format!("/customers/{}", encode(customer)),
1089 Some(form(&[("invoice_settings[default_payment_method]", payment_method.to_owned())])),
1090 )
1091 .await?;
1092 Ok(())
1093 }
1094
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1095 /// One of g1t's products at Stripe, tagged `metadata[g1t]` (the plan's
1096 /// is `plan`, the card fee's `card_fee`), made the first time it is
1097 /// needed, with g1t's tax code. One made before Stripe Tax was on is
1098 /// given the code when it is found.
1099 async fn product(&self, tag: &str, name: &str) -> Result<String> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1100 #[derive(Deserialize)]
1101 struct Product {
1102 id: String,
1103 #[serde(default)]
1104 metadata: Option<std::collections::HashMap<String, String>>,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1105 #[serde(default)]
1106 tax_code: Option<serde_json::Value>,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1107 }
1108 #[derive(Deserialize)]
1109 struct List {
1110 data: Vec<Product>,
1111 }
1112 let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?;
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1113 let ours = |p: &Product| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1114 if let Some(found) = list.data.into_iter().find(ours) {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1115 let coded = found.tax_code.as_ref().is_some_and(|code| code.as_str() == Some(TAX_CODE) || code["id"].as_str() == Some(TAX_CODE));
1116 if !coded {
1117 let _: serde_json::Value = self
1118 .call(Method::Post, &format!("/products/{}", encode(&found.id)), Some(form(&[("tax_code", TAX_CODE.to_owned())])))
1119 .await?;
1120 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1121 return Ok(found.id);
1122 }
1123 let created: Product = self
1124 .call(
1125 Method::Post,
1126 "/products",
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1127 Some(form(&[("name", name.to_owned()), ("metadata[g1t]", tag.to_owned()), ("tax_code", TAX_CODE.to_owned())])),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1128 )
1129 .await?;
1130 Ok(created.id)
1131 }
1132
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1133 /// Starts the monthly plan on a saved card, at once, with tax worked
1134 /// out by Stripe Tax on every invoice and the card fee as a monthly item
1135 /// of its own. Fails rather than leaving it half-started when the card's
1136 /// bank wants the person again, or when Stripe Tax cannot place the
1137 /// customer (no billing address yet); the caller then sends them to
1138 /// Stripe's page, which asks for the address.
1139 #[allow(clippy::too_many_arguments)]
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1140 pub async fn subscribe_with_card(
1141 &self,
1142 workspace: &str,
1143 feature: &str,
1144 title: &str,
1145 monthly_cents: u32,
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1146 fee_cents: u32,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1147 customer: &str,
1148 payment_method: &str,
1149 ) -> Result<StripeSubscription> {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1150 let product = self.product(feature, &format!("{title} plan")).await?;
1151 let fee_product = if fee_cents > 0 { Some(self.product("card_fee", CARD_FEE_LINE).await?) } else { None };
1152 let plan = SavedPlan { workspace, feature, title, monthly_cents, fee_cents, customer, payment_method };
1153 let fields = saved_subscription_fields(&plan, &product, fee_product.as_deref());
1154 let key = plan_key(workspace, feature, &format!("{payment_method}/{monthly_cents}/{fee_cents}"), g1t_kit::now_ms());
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1155 self.send(Method::Post, "/subscriptions", Some(form(&fields)), Some(&key)).await
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1156 }
1157
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1158
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1159 /// Ends a subscription now: one that never started properly.
1160 pub async fn cancel_now(&self, id: &str) -> Result<StripeSubscription> {
1161 self.call(Method::Delete, &format!("/subscriptions/{}", encode(id)), None).await
1162 }
1163
Paid features: a workspace turns on Deployments with a monthly plan1164 pub async fn subscription(&self, id: &str) -> Result<StripeSubscription> {
1165 self.call(Method::Get, &format!("/subscriptions/{}", encode(id)), None)
1166 .await
1167 }
1168
1169 /// Ends a plan when its period does (`cancel` true), or takes that back.
1170 pub async fn cancel_at_period_end(&self, id: &str, cancel: bool) -> Result<StripeSubscription> {
1171 self.call(
1172 Method::Post,
1173 &format!("/subscriptions/{}", encode(id)),
1174 Some(form(&[("cancel_at_period_end", cancel.to_string())])),
1175 )
1176 .await
1177 }
1178
Agents as a team: lifecycle, merge queue, billing and a new shell1179 pub async fn session(&self, id: &str) -> Result<Session> {
1180 self.call(
1181 Method::Get,
1182 &format!("/checkout/sessions/{}", encode(id)),
1183 None,
1184 )
1185 .await
1186 }
1187}
1188
Project dependencies: addresses, preview stacks, Affects, and agents who know1189/// Whether the processor said an id it was given does not exist, as when
1190/// g1t moves to another Stripe account and ids saved from the old one stay
1191/// behind.
1192pub(crate) fn is_missing(error: &Error) -> bool {
1193 error.to_string().contains("resource_missing")
1194}
1195
Agents as a team: lifecycle, merge queue, billing and a new shell1196pub(crate) fn is_live(key: &str) -> bool {
1197 key.starts_with("sk_live_") || key.starts_with("rk_live_")
1198}
1199
1200#[cfg(test)]
Billing: ask Stripe for tax only where Stripe Tax is active1201mod tax_mode_tests {
1202 use super::*;
1203
1204 #[test]
1205 fn untaxed_requests_lose_only_automatic_tax() {
1206 let body = form(&[("mode", "payment".to_owned()), ("automatic_tax[enabled]", "true".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]);
1207 assert_eq!(without_automatic_tax(&body), form(&[("mode", "payment".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]));
1208 assert!(taxed_path("/checkout/sessions") && taxed_path("/invoices") && taxed_path("/subscriptions"));
1209 assert!(!taxed_path("/invoices/in_1/finalize") && !taxed_path("/payment_intents"));
1210 }
1211}
1212
1213#[cfg(test)]
Agents as a team: lifecycle, merge queue, billing and a new shell1214mod tests {
1215 use super::*;
1216
1217 #[test]
Billing: credits with a kind and expiry, discounts instead of comped, and safer charging1218 fn asking_twice_for_a_plan_starts_one() {
1219 let at = 1_791_000_000_000;
1220 assert_eq!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_1", at + 1_000));
1221 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_2", at));
1222 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("other", "plan", "pm_1", at));
1223 }
1224
1225 #[test]
Agents as a team: lifecycle, merge queue, billing and a new shell1226 fn form_values_are_percent_encoded() {
1227 assert_eq!(
1228 form(&[
1229 (
1230 "success_url",
1231 "https://g1t.sh/a/-/billing?session={ID}".to_owned()
1232 ),
1233 ("line_items[0][quantity]", "1".to_owned()),
1234 ]),
1235 "success_url=https%3A%2F%2Fg1t.sh%2Fa%2F-%2Fbilling%3Fsession%3D%7BID%7D&line_items%5B0%5D%5Bquantity%5D=1"
1236 );
1237 }
1238
1239 #[test]
1240 fn test_keys_are_not_live() {
1241 assert!(is_live("sk_live_abc"));
1242 assert!(!is_live("sk_test_abc"));
1243 assert!(!is_live(""));
1244 }
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1245
1246 fn has(fields: &[(&str, String)], name: &str) -> Option<String> {
1247 fields.iter().find(|(n, _)| *n == name).map(|(_, v)| v.clone())
1248 }
1249
1250 #[test]
1251 fn every_request_names_the_api_version_it_is_written_for() {
1252 // Without it a new Stripe account answers at its newest version, and
1253 // invoices, charges and pages read differently from what billing
1254 // expects.
1255 assert!(STRIPE_VERSION.starts_with("2025-02-24"));
1256 let source = include_str!("stripe.rs");
1257 assert!(source.contains(concat!("headers.set(\"stripe-", "version\", STRIPE_VERSION)")));
1258 }
1259
1260 #[test]
1261 fn the_plans_page_is_a_subscription_without_payment_mode_fields() {
1262 let url = "https://g1t.sh/acme/-/billing?plan=plan";
1263 for customer in [None, Some("cus_1")] {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1264 let fields = subscription_fields("acme", "plan", "g1t", 2_000, 92, customer, url);
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1265 assert_eq!(has(&fields, "mode").as_deref(), Some("subscription"));
1266 // customer_creation is for payment mode; Stripe refuses it here.
1267 assert!(has(&fields, "customer_creation").is_none());
1268 assert!(has(&fields, "payment_intent_data[setup_future_usage]").is_none());
1269 assert_eq!(has(&fields, "customer").as_deref(), customer);
1270 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?plan=plan&session={CHECKOUT_SESSION_ID}");
1271 assert_eq!(has(&fields, "line_items[0][price_data][recurring][interval]").as_deref(), Some("month"));
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1272 // The card fee is a monthly line of its own.
1273 assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("92"));
1274 assert_eq!(has(&fields, "line_items[1][price_data][recurring][interval]").as_deref(), Some("month"));
1275 assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some(CARD_FEE_LINE));
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1276 }
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1277 let fields = subscription_fields("acme", "plan", "g1t", 2_000, 0, None, url);
1278 assert!(has(&fields, "line_items[1][quantity]").is_none());
1279 }
1280
1281 /// Every field a page must carry for Stripe Tax: tax on top of the
1282 /// price, an address always asked for, the buyer's tax ID, and each
1283 /// line at g1t's tax code, excluding tax. With a customer, what is
1284 /// entered is saved on it (Checkout refuses `automatic_tax` and
1285 /// `tax_id_collection` for a customer otherwise).
1286 fn assert_taxed_page(fields: &[(&str, String)], customer: Option<&str>, lines: usize) {
1287 assert_eq!(has(fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1288 assert_eq!(has(fields, "billing_address_collection").as_deref(), Some("required"));
1289 assert_eq!(has(fields, "tax_id_collection[enabled]").as_deref(), Some("true"));
1290 let saved = if customer.is_some() { Some("auto") } else { None };
1291 assert_eq!(has(fields, "customer_update[address]").as_deref(), saved);
1292 assert_eq!(has(fields, "customer_update[name]").as_deref(), saved);
1293 for (line, keys) in LINE_KEYS.iter().enumerate().take(lines) {
1294 assert_eq!(has(fields, keys[3]).as_deref(), Some("exclusive"), "line {line}");
1295 assert_eq!(has(fields, keys[5]).as_deref(), Some(TAX_CODE), "line {line}");
1296 }
1297 // No key twice: Stripe takes the last, silently.
1298 let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
1299 names.sort_unstable();
1300 let count = names.len();
1301 names.dedup();
1302 assert_eq!(names.len(), count);
1303 }
1304
1305 #[test]
1306 fn every_payment_page_is_taxed_by_stripe_tax() {
1307 let url = "https://g1t.sh/acme/-/billing";
1308 for customer in [None, Some("cus_1")] {
1309 // The plan and Security and quality.
1310 assert_taxed_page(&subscription_fields("acme", "plan", "g1t", 2_000, 92, customer, url), customer, 2);
1311 assert_taxed_page(&subscription_fields("acme", "security", "Security and quality", 1_000, 61, customer, url), customer, 2);
1312 // Prepaying by card, with its fee, and by bank transfer, without.
1313 assert_taxed_page(&prepay_fields("acme", 5_000, 185, customer, url, false), customer, 2);
1314 assert_taxed_page(&prepay_fields("acme", 100_000, 0, customer, url, true), customer, 1);
1315 // AI credit.
1316 let purchase = CreditPurchase { workspace: "acme", credit_cents: 2_500, fee_cents: 106, customer, return_url: url };
1317 assert_taxed_page(&credit_fields(&purchase), customer, 2);
1318 }
1319 // tax_id_collection and customer_update are for payment and
1320 // subscription mode; a card check charges nothing, so it is not
1321 // taxed, but it asks for the address the plan will be taxed at.
1322 let check = card_check_fields("acme", "cus_1", url);
1323 assert!(has(&check, "automatic_tax[enabled]").is_none());
1324 assert_eq!(has(&check, "billing_address_collection").as_deref(), Some("required"));
1325 }
1326
1327 #[test]
1328 fn a_bank_transfer_has_no_card_fee() {
1329 let fields = prepay_fields("acme", 100_000, 3_100, Some("cus_1"), "https://g1t.sh/acme/-/billing", true);
1330 assert!(has(&fields, "line_items[1][quantity]").is_none());
1331 let fields = prepay_fields("acme", 5_000, 185, None, "https://g1t.sh/acme/-/billing", false);
1332 assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("185"));
1333 assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some(CARD_FEE_LINE));
1334 }
1335
1336 #[test]
1337 fn a_plan_on_a_saved_card_is_taxed_with_its_card_fee() {
1338 let plan = SavedPlan { workspace: "acme", feature: "plan", title: "g1t", monthly_cents: 2_000, fee_cents: 92, customer: "cus_1", payment_method: "pm_1" };
1339 let fields = saved_subscription_fields(&plan, "prod_plan", Some("prod_fee"));
1340 assert_eq!(has(&fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1341 assert_eq!(has(&fields, "items[0][price_data][tax_behavior]").as_deref(), Some("exclusive"));
1342 assert_eq!(has(&fields, "items[1][price_data][product]").as_deref(), Some("prod_fee"));
1343 assert_eq!(has(&fields, "items[1][price_data][unit_amount]").as_deref(), Some("92"));
1344 assert_eq!(has(&fields, "items[1][price_data][tax_behavior]").as_deref(), Some("exclusive"));
1345 let fields = saved_subscription_fields(&SavedPlan { fee_cents: 0, ..plan }, "prod_plan", None);
1346 assert!(has(&fields, "items[1][price_data][product]").is_none());
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1347 }
1348
1349 #[test]
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1350 fn invoices_and_their_lines_are_taxed() {
1351 assert_eq!(has(&invoice_tax_fields(), "automatic_tax[enabled]").as_deref(), Some("true"));
1352 let item = item_tax_fields();
1353 assert_eq!(has(&item, "tax_behavior").as_deref(), Some("exclusive"));
1354 assert_eq!(has(&item, "tax_code").as_deref(), Some(TAX_CODE));
1355 }
1356
1357 #[test]
1358 fn an_off_session_charge_is_its_credit_fee_and_tax() {
1359 let charge = SavedCharge {
1360 workspace: "acme",
1361 customer: "cus_1",
1362 payment_method: "pm_1",
1363 credit_cents: 1_600,
1364 fee_cents: 78,
1365 tax_cents: 134,
1366 tax_calculation: Some("taxcalc_1"),
1367 key: "reload/acme/2026-10/1",
1368 };
1369 let calculation = tax_calculation_fields(&charge);
1370 assert_eq!(has(&calculation, "customer").as_deref(), Some("cus_1"));
1371 assert_eq!(has(&calculation, "line_items[0][amount]").as_deref(), Some("1600"));
1372 assert_eq!(has(&calculation, "line_items[0][tax_behavior]").as_deref(), Some("exclusive"));
1373 assert_eq!(has(&calculation, "line_items[0][tax_code]").as_deref(), Some(TAX_CODE));
1374 assert_eq!(has(&calculation, "line_items[1][amount]").as_deref(), Some("78"));
1375 assert_eq!(has(&calculation, "line_items[1][tax_code]").as_deref(), Some(TAX_CODE));
1376 let fields = saved_charge_fields(&charge);
1377 assert_eq!(has(&fields, "amount").as_deref(), Some("1812"));
1378 assert_eq!(has(&fields, "metadata[tax_calculation]").as_deref(), Some("taxcalc_1"));
1379 let reversal = reversal_fields("tax_1", "pi_1/re_1", 500);
1380 assert_eq!(has(&reversal, "flat_amount").as_deref(), Some("-500"));
1381 assert_eq!(has(&reversal, "mode").as_deref(), Some("partial"));
1382 }
1383
1384 #[test]
1385 fn a_paid_invoice_splits_into_tax_card_fee_and_what_was_sold() {
1386 let invoice = serde_json::json!({
1387 "tax": 180,
1388 "lines": { "data": [
1389 { "description": "1 × g1t plan (at $20.00 / month)", "amount": 2000 },
1390 { "description": "1 × Card processing fee (at $0.92 / month)", "amount": 92 },
1391 ] }
1392 });
1393 assert_eq!(invoice_split(&invoice, 2_272), InvoiceSplit { tax_cents: 180, fee_cents: 92, net_cents: 2_000 });
1394 // Before Stripe Tax: no tax, no fee, all of it sold.
1395 assert_eq!(invoice_split(&serde_json::json!({ "tax": null }), 2_000).net_cents, 2_000);
1396 // A page's tax and what came before it.
1397 let session: Session = serde_json::from_value(serde_json::json!({
1398 "id": "cs_1", "payment_status": "paid", "amount_total": 5_585, "amount_subtotal": 5_185,
1399 "total_details": { "amount_tax": 400 }, "customer": "cus_1", "payment_intent": "pi_1"
1400 }))
1401 .unwrap();
1402 assert_eq!((session.tax_cents(), session.before_tax_cents()), (400, 5_185));
1403 }
1404
1405 #[test]
1406 fn an_address_places_a_customer_for_tax() {
1407 use serde_json::json;
1408 assert!(address_places_customer(&json!({ "country": "DE" })));
1409 assert!(address_places_customer(&json!({ "country": "US", "postal_code": "94107" })));
1410 assert!(!address_places_customer(&json!({ "country": "US", "postal_code": "" })));
1411 assert!(address_places_customer(&json!({ "country": "CA", "state": "ON" })));
1412 assert!(!address_places_customer(&json!({ "country": "" })));
1413 assert!(!address_places_customer(&serde_json::Value::Null));
1414 let error = Error::RustError(r#"the card processor answered 400: {"error":{"code":"customer_tax_location_invalid","message":"x"}}"#.into());
1415 assert!(is_tax_location_error(&error));
1416 }
1417
1418 #[test]
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1419 fn a_card_check_is_a_setup_page_with_no_amount() {
1420 let fields = card_check_fields("acme", "cus_1", "https://g1t.sh/acme/-/billing");
1421 assert_eq!(has(&fields, "mode").as_deref(), Some("setup"));
1422 assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items")));
1423 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?card_check={CHECKOUT_SESSION_ID}");
1424 assert_eq!(has(&fields, "customer").as_deref(), Some("cus_1"));
1425 }
1426
1427 #[test]
1428 fn an_ai_credit_page_has_the_card_fee_as_its_own_line() {
1429 let purchase = CreditPurchase { workspace: "acme", credit_cents: 2_500, fee_cents: 106, customer: None, return_url: "https://g1t.sh/acme/-/billing" };
1430 let fields = credit_fields(&purchase);
1431 assert_eq!(has(&fields, "mode").as_deref(), Some("payment"));
1432 assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("2500"));
1433 assert_eq!(has(&fields, "line_items[1][price_data][unit_amount]").as_deref(), Some("106"));
1434 assert_eq!(has(&fields, "line_items[1][price_data][product_data][name]").as_deref(), Some("Card processing fee"));
1435 assert_eq!(has(&fields, "customer_creation").as_deref(), Some("always"));
1436 assert_eq!(has(&fields, "payment_intent_data[setup_future_usage]").as_deref(), Some("off_session"));
1437 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?ai_credit={CHECKOUT_SESSION_ID}");
1438 // No fee: no second line.
1439 let fields = credit_fields(&CreditPurchase { fee_cents: 0, customer: Some("cus_1"), ..purchase });
1440 assert!(has(&fields, "line_items[1][quantity]").is_none());
1441 assert!(has(&fields, "customer_creation").is_none());
1442 }
1443
1444 #[test]
1445 fn an_auto_reload_is_one_off_session_charge() {
Merge Stripe Tax, the card fee on card payments, and one free workspace per person1446 let charge = SavedCharge {
1447 workspace: "acme",
1448 customer: "cus_1",
1449 payment_method: "pm_1",
1450 credit_cents: 1_600,
1451 fee_cents: 78,
1452 tax_cents: 0,
1453 tax_calculation: None,
1454 key: "reload/acme/2026-10/1",
1455 };
Usage, Billing settings and prepaid AI credit; fixes from the UX audit1456 let fields = saved_charge_fields(&charge);
1457 assert_eq!(has(&fields, "amount").as_deref(), Some("1678"));
1458 assert_eq!(has(&fields, "off_session").as_deref(), Some("true"));
1459 assert_eq!(has(&fields, "confirm").as_deref(), Some("true"));
1460 }
1461
1462 #[test]
1463 fn a_page_asked_for_twice_is_one_page() {
1464 let at = 1_791_000_000_000;
1465 assert_eq!(page_key("plan", "acme", "plan/2000", at), page_key("plan", "acme", "plan/2000", at + 60_000));
1466 assert_ne!(page_key("plan", "acme", "plan/2000", at), page_key("ai_credit", "acme", "plan/2000", at));
1467 }
1468
1469 #[test]
1470 fn a_stripe_failure_reads_as_a_sentence_never_raw() {
1471 let refused = Error::RustError(
1472 r#"the card processor answered 400: {"error":{"message":"You may only specify one of these parameters: customer, customer_creation.","type":"invalid_request_error"}}"#.into(),
1473 );
1474 assert_eq!(friendly(&refused), "Stripe refused it: You may only specify one of these parameters: customer, customer_creation.");
1475 assert!(!friendly(&refused).contains("invalid_request_error"));
1476 let odd = Error::RustError("the card processor answered 502: <html>".into());
1477 assert!(friendly(&odd).starts_with("Stripe refused it. Try again"));
1478 let down = Error::RustError("network connection lost".into());
1479 assert_eq!(friendly(&down), "Stripe could not be reached. Try again in a minute.");
1480 let declined = Error::RustError(r#"the card processor answered 402: {"error":{"type":"card_error","code":"card_declined","message":"Your card was declined."}}"#.into());
1481 assert!(is_card_error(&declined) && !is_card_error(&refused));
1482 }
Agents as a team: lifecycle, merge queue, billing and a new shell1483}

This file's history is long; its oldest lines are credited to the oldest commit read.