Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
1,472 linesCodeBlameRaw
1//! The card processor, behind the calls billing needs: start a payment
2//! 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.
9//!
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.
16
17use serde::Deserialize;
18use worker::{Error, Fetch, Headers, Method, Request, RequestInit, Result};
19
20const API: &str = "https://api.stripe.com/v1";
21
22/// 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
26/// Stripe Tax's code for what g1t sells, on every product, price and
27/// invoice line: software as a service, for business use.
28pub(crate) const TAX_CODE: &str = "txcd_10103001";
29
30/// What every payment page (payment or subscription mode) asks of Stripe
31/// Tax: tax worked out on top of the price shown, from a billing address
32/// it always collects, with the buyer's tax ID if they have one. With a
33/// customer already, what was entered is saved on it, so invoices and
34/// off-session charges later find the address too. Checkout refuses
35/// `automatic_tax` for a customer with no address unless it may save one
36/// (`customer_update[address]`), and `tax_id_collection` unless it may save
37/// the name (`customer_update[name]`).
38pub(crate) fn checkout_tax_fields(customer: Option<&str>) -> Vec<(&'static str, String)> {
39 let mut fields = vec![
40 ("automatic_tax[enabled]", "true".to_owned()),
41 ("billing_address_collection", "required".to_owned()),
42 ("tax_id_collection[enabled]", "true".to_owned()),
43 ];
44 if customer.is_some() {
45 fields.extend([("customer_update[address]", "auto".to_owned()), ("customer_update[name]", "auto".to_owned())]);
46 }
47 fields
48}
49
50/// Whether Stripe refused because it could not tell where the customer is
51/// for tax: no address, or not enough of one.
52pub(crate) fn is_tax_location_error(error: &Error) -> bool {
53 let text = error.to_string();
54 text.contains("customer_tax_location_invalid") || text.contains("requires_location_inputs")
55}
56
57/// Whether an address is enough for Stripe Tax to place the customer: a
58/// country, and in the United States a postal code (in Canada a postal
59/// code or a province).
60pub(crate) fn address_places_customer(address: &serde_json::Value) -> bool {
61 let text = |key: &str| address[key].as_str().map(str::trim).unwrap_or_default().to_owned();
62 match text("country").to_uppercase().as_str() {
63 "" => false,
64 "US" => !text("postal_code").is_empty(),
65 "CA" => !text("postal_code").is_empty() || !text("state").is_empty(),
66 _ => true,
67 }
68}
69
70/// What a Stripe failure says, for the person on the page: Stripe's own
71/// message when it gave one (never the request or any key), else that it
72/// could not be reached.
73pub(crate) fn friendly(error: &Error) -> String {
74 let text = error.to_string();
75 let message = text
76 .split_once(": ")
77 .and_then(|(_, body)| serde_json::from_str::<serde_json::Value>(body).ok())
78 .and_then(|body| body["error"]["message"].as_str().map(str::to_owned));
79 match message {
80 Some(message) => format!("Stripe refused it: {}", message.trim_end_matches('.').to_owned() + "."),
81 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(),
82 None => "Stripe could not be reached. Try again in a minute.".to_owned(),
83 }
84}
85
86pub struct Stripe {
87 key: String,
88}
89
90/// A payment page, and the payment made through it.
91#[derive(Deserialize)]
92pub struct Session {
93 pub id: String,
94 /// Where to send the person. Absent once the page has been used.
95 pub url: Option<String>,
96 /// `paid` once the money has been taken.
97 pub payment_status: String,
98 /// What was paid, in cents, tax included.
99 pub amount_total: Option<u32>,
100 /// What the lines came to before tax, in cents.
101 #[serde(default)]
102 pub amount_subtotal: Option<u32>,
103 /// The tax Stripe added (`amount_tax`), among other totals.
104 #[serde(default)]
105 pub total_details: Option<TotalDetails>,
106 /// For a payment page: the payment that took the money.
107 #[serde(default)]
108 pub payment_intent: Option<String>,
109 pub customer: Option<String>,
110 /// For a plan's page: the subscription it started.
111 #[serde(default)]
112 pub subscription: Option<String>,
113 /// For a card check's page: the setup that saved and verified the card.
114 #[serde(default)]
115 pub setup_intent: Option<String>,
116}
117
118#[derive(Default, Deserialize)]
119pub struct TotalDetails {
120 #[serde(default)]
121 pub amount_tax: i64,
122}
123
124impl Session {
125 /// The tax Stripe added on the page, in cents.
126 pub fn tax_cents(&self) -> i64 {
127 self.total_details.as_ref().map_or(0, |t| t.amount_tax.max(0))
128 }
129
130 /// What the page's lines came to before tax, in cents: the total less
131 /// the tax when Stripe gives no subtotal.
132 pub fn before_tax_cents(&self) -> i64 {
133 match self.amount_subtotal {
134 Some(subtotal) => i64::from(subtotal),
135 None => (i64::from(self.amount_total.unwrap_or(0)) - self.tax_cents()).max(0),
136 }
137 }
138}
139
140/// A card saved and verified: what a card check found.
141#[derive(Debug, Deserialize)]
142pub struct CheckedCard {
143 pub payment_method: String,
144 pub fingerprint: Option<String>,
145 pub brand: Option<String>,
146 pub last4: Option<String>,
147 /// `credit`, `debit`, `prepaid` or `unknown`.
148 pub funding: Option<String>,
149 pub country: Option<String>,
150 /// The billing address entered with the card, as Stripe keeps it.
151 #[serde(default)]
152 pub address: Option<serde_json::Value>,
153}
154
155/// g1t's settings for Stripe's hosted billing page.
156#[derive(Debug, Deserialize)]
157pub struct PortalConfiguration {
158 pub id: String,
159 #[serde(default)]
160 pub active: bool,
161 #[serde(default)]
162 pub login_page: Option<LoginPage>,
163 #[serde(default)]
164 pub metadata: Option<std::collections::HashMap<String, String>>,
165}
166
167#[derive(Debug, Deserialize)]
168pub struct LoginPage {
169 pub url: Option<String>,
170}
171
172/// A monthly plan.
173#[derive(Deserialize)]
174pub struct StripeSubscription {
175 pub id: String,
176 /// `active`, `trialing`, `past_due`, `unpaid`, `canceled`, `incomplete`…
177 pub status: String,
178 #[serde(default)]
179 pub cancel_at_period_end: bool,
180 /// Unix seconds. Older API versions carry it here…
181 #[serde(default)]
182 pub current_period_end: Option<i64>,
183 /// …newer ones on each item.
184 #[serde(default)]
185 pub items: Option<Items>,
186}
187
188#[derive(Deserialize)]
189pub struct Items {
190 pub data: Vec<Item>,
191}
192
193#[derive(Deserialize)]
194pub struct Item {
195 #[serde(default)]
196 pub current_period_end: Option<i64>,
197}
198
199impl StripeSubscription {
200 /// When the period paid for ends, in Unix seconds.
201 pub fn period_end(&self) -> Option<i64> {
202 self.current_period_end.or_else(|| {
203 self.items
204 .as_ref()
205 .and_then(|items| items.data.iter().filter_map(|item| item.current_period_end).max())
206 })
207 }
208}
209
210/// Percent-encodes a form value.
211fn encode(value: &str) -> String {
212 let mut encoded = String::with_capacity(value.len());
213 for byte in value.bytes() {
214 match byte {
215 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
216 encoded.push(byte as char);
217 }
218 _ => encoded.push_str(&format!("%{byte:02X}")),
219 }
220 }
221 encoded
222}
223
224/// `name=value` pairs as a form body.
225/// Requests that carry `automatic_tax`: payment pages, invoices and
226/// subscriptions. When Stripe Tax is not active for the key's mode (a test
227/// account where it was never turned on), Stripe refuses them outright, so
228/// in test mode the field is left out and the payment goes through untaxed;
229/// with a live key the request is refused instead (`untaxed_body`).
230pub(crate) fn taxed_path(path: &str) -> bool {
231 path == "/checkout/sessions" || path == "/invoices" || path == "/subscriptions"
232}
233
234/// A form body without its `automatic_tax[…]` fields.
235pub(crate) fn without_automatic_tax(body: &str) -> String {
236 body.split('&').filter(|pair| !pair.starts_with("automatic_tax")).collect::<Vec<_>>().join("&")
237}
238
239/// What a request asking for tax becomes when Stripe Tax is not active.
240/// In test mode, the body without `automatic_tax`: the payment goes through
241/// untaxed. With a live key, nothing is sent: charging real money without
242/// the tax owed on it would under-collect, so the charge, page or invoice
243/// is refused, loudly, until Stripe Tax is turned on.
244pub(crate) fn untaxed_body(live: bool, body: &str) -> Result<String> {
245 if live {
246 return Err(Error::RustError(format!(
247 "the card processor answered 400: {}",
248 serde_json::json!({ "error": { "type": "g1t_tax_not_active", "message": "Payments are paused while g1t sets up sales tax. Try again later" } })
249 )));
250 }
251 Ok(without_automatic_tax(body))
252}
253
254/// How long whether Stripe Tax is active is believed, in milliseconds.
255const TAX_ACTIVE_FOR_MS: u64 = 10 * 60 * 1000;
256
257thread_local! {
258 /// Whether Stripe Tax is active for the key, and when that was read.
259 static TAX_ACTIVE: std::cell::Cell<Option<(bool, u64)>> = const { std::cell::Cell::new(None) };
260 /// When g1t's portal configuration was last brought in line with
261 /// `portal_fields` in this isolate.
262 static PORTAL_SYNCED: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
263}
264
265/// How long a portal configuration brought in line is taken to stay so.
266const PORTAL_SYNCED_FOR_MS: u64 = 60 * 60 * 1000;
267
268/// The `metadata[g1t]` of the portal configuration billing makes.
269pub(crate) const PORTAL_TAG: &str = "billing";
270
271/// Why a customer can end a plan on Stripe's page: Stripe asks for the
272/// list whenever it asks for a reason.
273const CANCELLATION_REASONS: [&str; 8] =
274 ["too_expensive", "missing_features", "switched_service", "unused", "customer_service", "too_complex", "low_quality", "other"];
275
276/// g1t's settings for Stripe's hosted billing page (the customer portal),
277/// where every card, billing detail, tax ID, invoice and receipt is
278/// managed, and the plan ended: the customer's details (email, address,
279/// name, tax IDs, phone), the card, the invoice history, and ending the
280/// plan at the end of the period with a reason. Never changing the plan
281/// there: g1t has one.
282pub(crate) fn portal_fields() -> Vec<(&'static str, String)> {
283 let mut fields = vec![
284 ("business_profile[headline]", "g1t billing: your card, billing details, tax IDs and invoices".to_owned()),
285 ("business_profile[privacy_policy_url]", "https://g1t.sh/policies/privacy".to_owned()),
286 ("business_profile[terms_of_service_url]", "https://g1t.sh/policies/terms".to_owned()),
287 ("features[customer_update][enabled]", "true".to_owned()),
288 ("features[customer_update][allowed_updates][0]", "email".to_owned()),
289 ("features[customer_update][allowed_updates][1]", "address".to_owned()),
290 ("features[customer_update][allowed_updates][2]", "name".to_owned()),
291 ("features[customer_update][allowed_updates][3]", "tax_id".to_owned()),
292 ("features[customer_update][allowed_updates][4]", "phone".to_owned()),
293 ("features[payment_method_update][enabled]", "true".to_owned()),
294 ("features[invoice_history][enabled]", "true".to_owned()),
295 ("features[subscription_cancel][enabled]", "true".to_owned()),
296 ("features[subscription_cancel][mode]", "at_period_end".to_owned()),
297 ("features[subscription_cancel][cancellation_reason][enabled]", "true".to_owned()),
298 ("features[subscription_update][enabled]", "false".to_owned()),
299 ("login_page[enabled]", "true".to_owned()),
300 ("metadata[g1t]", PORTAL_TAG.to_owned()),
301 ];
302 const OPTION_KEYS: [&str; 8] = [
303 "features[subscription_cancel][cancellation_reason][options][0]",
304 "features[subscription_cancel][cancellation_reason][options][1]",
305 "features[subscription_cancel][cancellation_reason][options][2]",
306 "features[subscription_cancel][cancellation_reason][options][3]",
307 "features[subscription_cancel][cancellation_reason][options][4]",
308 "features[subscription_cancel][cancellation_reason][options][5]",
309 "features[subscription_cancel][cancellation_reason][options][6]",
310 "features[subscription_cancel][cancellation_reason][options][7]",
311 ];
312 fields.extend(OPTION_KEYS.iter().zip(CANCELLATION_REASONS).map(|(key, reason)| (*key, reason.to_owned())));
313 fields
314}
315
316/// g1t's portal configuration among Stripe's, by its tag: an active one
317/// first.
318pub(crate) fn ours(configurations: Vec<PortalConfiguration>) -> Option<PortalConfiguration> {
319 let mut tagged: Vec<PortalConfiguration> = configurations
320 .into_iter()
321 .filter(|c| c.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(PORTAL_TAG))
322 .collect();
323 tagged.sort_by_key(|c| !c.active);
324 tagged.into_iter().next()
325}
326
327/// Stripe Tax's settings, for the go-live checklist: `active` once it can
328/// collect tax, else `pending` with what is missing (`head_office`, …).
329#[derive(Debug, Default, Deserialize)]
330pub struct TaxSettings {
331 #[serde(default)]
332 pub status: String,
333 #[serde(default)]
334 pub status_details: TaxStatusDetails,
335}
336
337#[derive(Debug, Default, Deserialize)]
338pub struct TaxStatusDetails {
339 #[serde(default)]
340 pub pending: Option<TaxPending>,
341}
342
343#[derive(Debug, Default, Deserialize)]
344pub struct TaxPending {
345 #[serde(default)]
346 pub missing_fields: Option<Vec<String>>,
347}
348
349pub(crate) fn form(fields: &[(&str, String)]) -> String {
350 fields
351 .iter()
352 .map(|(name, value)| format!("{}={}", encode(name), encode(value)))
353 .collect::<Vec<_>>()
354 .join("&")
355}
356
357/// The idempotency key for starting a plan on a saved card: the same
358/// workspace, plan and card within the same ten minutes is one subscription,
359/// however many times it is asked for (a double click, two tabs), so a
360/// workspace is never billed twice for one plan. A different card is a new
361/// attempt, as Stripe refuses a key reused with other fields.
362pub(crate) fn plan_key(workspace: &str, feature: &str, payment_method: &str, now_ms: u64) -> String {
363 format!("plan/{workspace}/{feature}/{payment_method}/{}", now_ms / 600_000)
364}
365
366impl Stripe {
367 pub fn new(key: String) -> Self {
368 Stripe { key }
369 }
370
371 /// Whether the key is for real cards, not Stripe's test mode.
372 pub fn live(&self) -> bool {
373 is_live(&self.key)
374 }
375
376 /// A GET of any Stripe resource, for the webhook handlers.
377 pub(crate) async fn get<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
378 self.call(Method::Get, path, None).await
379 }
380
381 /// A DELETE of any Stripe resource.
382 pub(crate) async fn delete<T: for<'a> Deserialize<'a>>(&self, path: &str) -> Result<T> {
383 self.call(Method::Delete, path, None).await
384 }
385
386 /// A form POST to any Stripe resource.
387 pub(crate) async fn post<T: for<'a> Deserialize<'a>>(&self, path: &str, fields: &[(&str, String)]) -> Result<T> {
388 self.call(Method::Post, path, Some(form(fields))).await
389 }
390
391 /// A form POST that Stripe does at most once for `key`, however often
392 /// it is sent.
393 pub(crate) async fn post_idempotent<T: for<'a> Deserialize<'a>>(
394 &self,
395 path: &str,
396 fields: &[(&str, String)],
397 key: &str,
398 ) -> Result<T> {
399 self.send(Method::Post, path, Some(form(fields)), Some(key)).await
400 }
401
402 async fn call<T: for<'a> Deserialize<'a>>(
403 &self,
404 method: Method,
405 path: &str,
406 body: Option<String>,
407 ) -> Result<T> {
408 self.send(method, path, body, None).await
409 }
410
411 async fn send<T: for<'a> Deserialize<'a>>(
412 &self,
413 method: Method,
414 path: &str,
415 body: Option<String>,
416 idempotency_key: Option<&str>,
417 ) -> Result<T> {
418 let body = match body {
419 Some(body) if matches!(method, Method::Post) && taxed_path(path) && body.contains("automatic_tax") && !self.tax_active().await => {
420 if self.live() {
421 worker::console_error!(
422 "STRIPE TAX IS NOT ACTIVE for the live key: refused {path} rather than charge without tax. Turn it on in Stripe (Tax → Settings)."
423 );
424 }
425 Some(untaxed_body(self.live(), &body)?)
426 }
427 body => body,
428 };
429 self.send_raw(method, path, body, idempotency_key).await
430 }
431
432 /// The request itself, as given: `send` without the Stripe Tax check.
433 async fn send_raw<T: for<'a> Deserialize<'a>>(
434 &self,
435 method: Method,
436 path: &str,
437 body: Option<String>,
438 idempotency_key: Option<&str>,
439 ) -> Result<T> {
440 let headers = Headers::new();
441 headers.set("authorization", &format!("Bearer {}", self.key))?;
442 headers.set("stripe-version", STRIPE_VERSION)?;
443 if let Some(key) = idempotency_key {
444 headers.set("idempotency-key", key)?;
445 }
446 if body.is_some() {
447 headers.set("content-type", "application/x-www-form-urlencoded")?;
448 }
449 let deleting = matches!(method, Method::Delete);
450 let mut init = RequestInit::new();
451 init.with_method(method).with_headers(headers);
452 if let Some(body) = body {
453 init.with_body(Some(body.into()));
454 }
455 let request = Request::new_with_init(&format!("{API}{path}"), &init)?;
456 let mut response = Fetch::Request(request).send().await?;
457 if response.status_code() != 200 {
458 return Err(Error::RustError(format!(
459 "the card processor answered {}: {}",
460 response.status_code(),
461 response.text().await.unwrap_or_default()
462 )));
463 }
464 let found: serde_json::Value = response.json().await?;
465 // A deleted customer is read back with a 200 and `deleted: true`:
466 // as good as missing, so every caller that forgets a missing
467 // customer forgets this one too.
468 if !deleting && is_deleted_customer(&found) {
469 return Err(Error::RustError(DELETED_CUSTOMER.to_owned()));
470 }
471 serde_json::from_value(found).map_err(|error| Error::RustError(format!("the card processor's answer to {path} was unexpected: {error}")))
472 }
473
474 /// Whether Stripe Tax is active for this key's mode (`GET /tax/settings`,
475 /// `status` `active`), read at most every ten minutes. When it cannot be
476 /// read, it is taken as active: asking for tax and being refused says
477 /// why, where leaving it out would undercharge without a word.
478 pub async fn tax_active(&self) -> bool {
479 let now = crate::now_ms();
480 if let Some((active, at)) = TAX_ACTIVE.with(|cell| cell.get())
481 && now.saturating_sub(at) < TAX_ACTIVE_FOR_MS
482 {
483 return active;
484 }
485 #[derive(Deserialize)]
486 struct Settings {
487 status: String,
488 }
489 let active = match self.send_raw::<Settings>(Method::Get, "/tax/settings", None, None).await {
490 Ok(settings) => settings.status == "active",
491 Err(error) => {
492 worker::console_error!("Stripe Tax settings could not be read; asking for tax anyway: {error}");
493 true
494 }
495 };
496 TAX_ACTIVE.with(|cell| cell.set(Some((active, now))));
497 active
498 }
499
500 /// A customer for a workspace that has none yet, with the email its
501 /// receipts go to and the billing page signs in with. Two asking at once
502 /// make one customer (`customer_key`).
503 pub async fn create_customer(&self, workspace: &str, email: Option<&str>) -> Result<String> {
504 #[derive(Deserialize)]
505 struct Customer {
506 id: String,
507 }
508 let fields = customer_fields(workspace, email);
509 let key = customer_key(workspace, email, g1t_kit::now_ms());
510 let customer: Customer = self.send(Method::Post, "/customers", Some(form(&fields)), Some(&key)).await?;
511 Ok(customer.id)
512 }
513
514 /// A session on Stripe's hosted billing page (the customer portal) for
515 /// the customer, coming back to `return_url`.
516 pub async fn portal_session(&self, customer: &str, return_url: &str) -> Result<String> {
517 #[derive(Deserialize)]
518 struct Portal {
519 url: String,
520 }
521 let configuration = self.portal_configuration().await?;
522 let fields = [
523 ("customer", customer.to_owned()),
524 ("return_url", return_url.to_owned()),
525 ("configuration", configuration.id),
526 ];
527 let portal: Portal = self.call(Method::Post, "/billing_portal/sessions", Some(form(&fields))).await?;
528 Ok(portal.url)
529 }
530
531 /// g1t's billing page settings at Stripe (`portal_fields`), made the
532 /// first time they are needed, and an existing one (`metadata[g1t]` =
533 /// `billing`) brought in line with them rather than a second made: at
534 /// most once an hour in an isolate.
535 pub async fn portal_configuration(&self) -> Result<PortalConfiguration> {
536 let now = crate::now_ms();
537 let existing = self.our_portal().await?;
538 let fresh = PORTAL_SYNCED.with(|cell| cell.get()).is_some_and(|at| now.saturating_sub(at) < PORTAL_SYNCED_FOR_MS);
539 let configuration: PortalConfiguration = match existing {
540 Some(existing) if fresh && existing.active => existing,
541 Some(existing) => {
542 let mut fields = portal_fields();
543 fields.push(("active", "true".to_owned()));
544 self.call(Method::Post, &format!("/billing_portal/configurations/{}", encode(&existing.id)), Some(form(&fields))).await?
545 }
546 None => self.call(Method::Post, "/billing_portal/configurations", Some(form(&portal_fields()))).await?,
547 };
548 PORTAL_SYNCED.with(|cell| cell.set(Some(now)));
549 Ok(configuration)
550 }
551
552 /// g1t's portal configuration as Stripe has it, without making or
553 /// changing it. None when there is none yet.
554 pub async fn our_portal(&self) -> Result<Option<PortalConfiguration>> {
555 #[derive(Deserialize)]
556 struct List {
557 data: Vec<PortalConfiguration>,
558 }
559 let list: List = self.call(Method::Get, "/billing_portal/configurations?limit=100", None).await?;
560 Ok(ours(list.data))
561 }
562
563 /// Stripe Tax's settings for this key's mode, read now.
564 pub async fn tax_settings(&self) -> Result<TaxSettings> {
565 self.send_raw(Method::Get, "/tax/settings", None, None).await
566 }
567
568 /// The customer's email at Stripe, if they gave one.
569 pub async fn customer_email(&self, customer: &str) -> Result<Option<String>> {
570 #[derive(Deserialize)]
571 struct Customer {
572 email: Option<String>,
573 }
574 let found: Customer = self.call(Method::Get, &format!("/customers/{}", encode(customer)), None).await?;
575 Ok(found.email)
576 }
577
578 /// Starts a page on which `amount_cents` is paid in advance: by card,
579 /// with 3-D Secure asked for wherever the card supports it, the card
580 /// kept for later charges; or, with `bank_transfer` and a customer, by
581 /// bank transfer to the account details Stripe gives, counted when the
582 /// money arrives.
583 pub async fn start_checkout(
584 &self,
585 workspace: &str,
586 amount_cents: u32,
587 customer: Option<&str>,
588 return_url: &str,
589 bank_transfer: bool,
590 ) -> Result<Session> {
591 let fields = prepay_fields(workspace, amount_cents, customer, return_url, bank_transfer);
592 let key = page_key(
593 "prepay",
594 workspace,
595 &format!("{amount_cents}/{bank_transfer}/{}", customer.unwrap_or("new")),
596 g1t_kit::now_ms(),
597 );
598 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
599 }
600
601 /// Starts a page on which a feature's monthly plan is paid for by card,
602 /// at its price and nothing more, tax added where it applies.
603 pub async fn start_subscription(
604 &self,
605 workspace: &str,
606 feature: &str,
607 title: &str,
608 monthly_cents: u32,
609 customer: Option<&str>,
610 return_url: &str,
611 ) -> Result<Session> {
612 let fields = subscription_fields(workspace, feature, title, monthly_cents, customer, return_url);
613 let key = page_key(
614 "plan",
615 workspace,
616 &format!("{feature}/{monthly_cents}/{}", customer.unwrap_or("new")),
617 g1t_kit::now_ms(),
618 );
619 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
620 }
621
622 /// Starts a page that saves and verifies a card, with 3-D Secure asked
623 /// for wherever the card supports it. Nothing is charged: the card's
624 /// bank sees at most a $0 or $1 authorization that is never captured.
625 pub async fn start_card_check(&self, workspace: &str, customer: &str, return_url: &str) -> Result<Session> {
626 let fields = card_check_fields(workspace, customer, return_url);
627 let key = page_key("card_check", workspace, customer, g1t_kit::now_ms());
628 self.send(Method::Post, "/checkout/sessions", Some(form(&fields)), Some(&key)).await
629 }
630
631 /// The customer's default payment method: the one its invoices are
632 /// charged to, else its newest card. None when it has none.
633 pub async fn default_payment_method(&self, customer: &str) -> Result<Option<SavedMethod>> {
634 let found: serde_json::Value = self
635 .call(
636 Method::Get,
637 &format!("/customers/{}?expand[]=invoice_settings.default_payment_method", encode(customer)),
638 None,
639 )
640 .await?;
641 if let Some(method) = SavedMethod::from_json(&found["invoice_settings"]["default_payment_method"]) {
642 return Ok(Some(method));
643 }
644 let list: serde_json::Value = self
645 .call(Method::Get, &format!("/payment_methods?customer={}&type=card&limit=1", encode(customer)), None)
646 .await?;
647 Ok(list["data"].as_array().and_then(|data| data.first()).and_then(SavedMethod::from_json))
648 }
649
650 /// The customer as Stripe keeps it, with its tax ids.
651 pub async fn customer(&self, customer: &str) -> Result<serde_json::Value> {
652 self.call(Method::Get, &format!("/customers/{}?expand[]=tax_ids", encode(customer)), None).await
653 }
654
655 /// The customer's invoices, newest first.
656 pub async fn invoices(&self, customer: &str) -> Result<Vec<serde_json::Value>> {
657 let list: serde_json::Value = self.call(Method::Get, &format!("/invoices?customer={}&limit=24", encode(customer)), None).await?;
658 Ok(list["data"].as_array().cloned().unwrap_or_default())
659 }
660
661 /// Reverses a tax transaction in part for a refund: `refunded_cents` of
662 /// the payment, tax included, taken back across all of it.
663 pub async fn reverse_tax(&self, transaction: &str, reference: &str, refunded_cents: i64) -> Result<()> {
664 let _: serde_json::Value = self
665 .send(
666 Method::Post,
667 "/tax/transactions/create_reversal",
668 Some(form(&reversal_fields(transaction, reference, refunded_cents))),
669 Some(&format!("tax-reversal/{reference}")),
670 )
671 .await?;
672 Ok(())
673 }
674
675 /// Copies the billing address entered with a card onto the customer
676 /// when the customer has none Stripe Tax can use, so later invoices and
677 /// charges can be taxed. Never replaces an address an owner gave.
678 pub async fn fill_address(&self, customer: &str, address: &serde_json::Value) -> Result<bool> {
679 if !address_places_customer(address) {
680 return Ok(false);
681 }
682 let found = self.customer(customer).await?;
683 if address_places_customer(&found["address"]) {
684 return Ok(false);
685 }
686 let _: serde_json::Value = self.post(&format!("/customers/{}", encode(customer)), &address_fields(address)).await?;
687 Ok(true)
688 }
689
690 /// Whether the customer's address is enough for Stripe Tax.
691 pub async fn customer_placed(&self, customer: &str) -> Result<bool> {
692 let found = self.customer(customer).await?;
693 Ok(address_places_customer(&found["address"]) || address_places_customer(&found["shipping"]["address"]))
694 }
695}
696
697/// A customer's address from an address Stripe gave.
698pub(crate) fn address_fields(address: &serde_json::Value) -> Vec<(&'static str, String)> {
699 let text = |key: &str| address[key].as_str().unwrap_or_default().to_owned();
700 vec![
701 ("address[line1]", text("line1")),
702 ("address[line2]", text("line2")),
703 ("address[city]", text("city")),
704 ("address[state]", text("state")),
705 ("address[postal_code]", text("postal_code")),
706 ("address[country]", text("country")),
707 ]
708}
709
710/// A refund's tax reversal: a part of the payment, as a negative amount.
711pub(crate) fn reversal_fields(transaction: &str, reference: &str, refunded_cents: i64) -> Vec<(&'static str, String)> {
712 vec![
713 ("mode", "partial".to_owned()),
714 ("original_transaction", transaction.to_owned()),
715 ("reference", reference.to_owned()),
716 ("flat_amount", (-refunded_cents.abs()).to_string()),
717 ]
718}
719
720/// A saved way to pay, as far as it is safe to show.
721#[derive(Clone, Debug, PartialEq)]
722pub struct SavedMethod {
723 pub id: String,
724 pub kind: String,
725 pub brand: Option<String>,
726 pub last4: Option<String>,
727 pub exp_month: Option<u32>,
728 pub exp_year: Option<u32>,
729}
730
731impl SavedMethod {
732 fn from_json(method: &serde_json::Value) -> Option<SavedMethod> {
733 let id = method["id"].as_str()?.to_owned();
734 let kind = method["type"].as_str().unwrap_or("card").to_owned();
735 let details = &method[kind.as_str()];
736 Some(SavedMethod {
737 id,
738 brand: details["brand"].as_str().or_else(|| details["bank_name"].as_str()).map(str::to_owned),
739 last4: details["last4"].as_str().map(str::to_owned),
740 exp_month: details["exp_month"].as_u64().map(|m| m as u32),
741 exp_year: details["exp_year"].as_u64().map(|y| y as u32),
742 kind,
743 })
744 }
745}
746
747/// A new customer's fields: the workspace, and the email receipts go to
748/// when there is one.
749pub(crate) fn customer_fields(workspace: &str, email: Option<&str>) -> Vec<(&'static str, String)> {
750 let mut fields = vec![("name", workspace.to_owned()), ("metadata[workspace]", workspace.to_owned())];
751 if let Some(email) = email.map(str::trim).filter(|e| e.contains('@')) {
752 fields.push(("email", email.to_owned()));
753 }
754 fields
755}
756
757/// The idempotency key for a workspace's customer: one per workspace in ten
758/// minutes, however many pages ask at once. Ten minutes, not for ever: a
759/// customer deleted at Stripe is forgotten (`forget_customer`), and the
760/// next must be new. The email is part of it, as Stripe refuses a key
761/// reused with other fields.
762pub(crate) fn customer_key(workspace: &str, email: Option<&str>, now_ms: u64) -> String {
763 format!("customer/{workspace}/{}/{}", email.map_or("-", str::trim), now_ms / 600_000)
764}
765
766/// The idempotency key for a payment page: the same workspace, purpose and
767/// details within ten minutes is one page, however often it is asked for (a
768/// double click, two tabs).
769pub(crate) fn page_key(purpose: &str, workspace: &str, details: &str, now_ms: u64) -> String {
770 format!("page/{purpose}/{workspace}/{details}/{}", now_ms / 600_000)
771}
772
773/// Where Stripe sends the person back, with the page's id under `name`.
774fn back_to(return_url: &str, name: &str) -> String {
775 let separator = if return_url.contains('?') { '&' } else { '?' };
776 // Stripe fills in the page's id.
777 format!("{return_url}{separator}{name}={{CHECKOUT_SESSION_ID}}")
778}
779
780/// The name of the card fee's line on payments from before the fee was
781/// folded into g1t's prices. Nothing new carries it; paid invoices that do
782/// still have it counted apart by this name (`invoice_split`).
783pub(crate) const CARD_FEE_LINE: &str = "Card processing fee";
784
785/// The form keys of the one line on a payment page: what is bought.
786const LINE_KEYS: [&str; 8] = [
787 "line_items[0][quantity]",
788 "line_items[0][price_data][currency]",
789 "line_items[0][price_data][unit_amount]",
790 "line_items[0][price_data][tax_behavior]",
791 "line_items[0][price_data][product_data][name]",
792 "line_items[0][price_data][product_data][tax_code]",
793 "line_items[0][price_data][product_data][description]",
794 "line_items[0][price_data][recurring][interval]",
795];
796
797/// The one line on a payment page at g1t's tax code, its price excluding
798/// tax; monthly when `monthly`. g1t's prices include Stripe's fee, so there
799/// is never a second line for it.
800fn page_line(cents: u32, name: String, description: Option<String>, monthly: bool) -> Vec<(&'static str, String)> {
801 let keys = LINE_KEYS;
802 let mut fields = vec![
803 (keys[0], "1".to_owned()),
804 (keys[1], "usd".to_owned()),
805 (keys[2], cents.to_string()),
806 (keys[3], "exclusive".to_owned()),
807 (keys[4], name),
808 (keys[5], TAX_CODE.to_owned()),
809 ];
810 if let Some(description) = description {
811 fields.push((keys[6], description));
812 }
813 if monthly {
814 fields.push((keys[7], "month".to_owned()));
815 }
816 fields
817}
818
819/// A prepayment page's fields: the amount prepaid as the one line, by card
820/// or by bank transfer alike, tax added where it applies.
821pub(crate) fn prepay_fields(
822 workspace: &str,
823 amount_cents: u32,
824 customer: Option<&str>,
825 return_url: &str,
826 bank_transfer: bool,
827) -> Vec<(&'static str, String)> {
828 let mut fields = vec![("mode", "payment".to_owned())];
829 if bank_transfer {
830 fields.extend([
831 ("payment_method_types[0]", "customer_balance".to_owned()),
832 ("payment_method_options[customer_balance][funding_type]", "bank_transfer".to_owned()),
833 ("payment_method_options[customer_balance][bank_transfer][type]", "us_bank_transfer".to_owned()),
834 ]);
835 } else {
836 fields.extend([
837 ("payment_method_types[0]", "card".to_owned()),
838 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
839 ("payment_intent_data[setup_future_usage]", "off_session".to_owned()),
840 ]);
841 }
842 fields.extend([
843 ("success_url", back_to(return_url, "session")),
844 ("cancel_url", return_url.to_owned()),
845 ("client_reference_id", workspace.to_owned()),
846 ("metadata[workspace]", workspace.to_owned()),
847 ]);
848 fields.extend(page_line(amount_cents, format!("g1t usage paid in advance for {workspace}"), None, false));
849 fields.extend(checkout_tax_fields(customer));
850 match customer {
851 Some(customer) => fields.push(("customer", customer.to_owned())),
852 None => fields.push(("customer_creation", "always".to_owned())),
853 }
854 fields
855}
856
857/// A plan's page's fields: the plan at its price, as its only line. In
858/// subscription mode Stripe makes the customer itself when
859/// there is none; `customer_creation` is for payment mode only. The
860/// subscription it starts keeps `automatic_tax`, so every renewal is taxed.
861pub(crate) fn subscription_fields(
862 workspace: &str,
863 feature: &str,
864 title: &str,
865 monthly_cents: u32,
866 customer: Option<&str>,
867 return_url: &str,
868) -> Vec<(&'static str, String)> {
869 let mut fields = vec![
870 ("mode", "subscription".to_owned()),
871 ("payment_method_types[0]", "card".to_owned()),
872 ("success_url", back_to(return_url, "session")),
873 ("cancel_url", return_url.to_owned()),
874 ("client_reference_id", workspace.to_owned()),
875 ("metadata[workspace]", workspace.to_owned()),
876 ("metadata[feature]", feature.to_owned()),
877 ("subscription_data[metadata][workspace]", workspace.to_owned()),
878 ("subscription_data[metadata][feature]", feature.to_owned()),
879 ];
880 fields.extend(page_line(monthly_cents, format!("g1t {title} for {workspace}"), None, true));
881 fields.extend(checkout_tax_fields(customer));
882 if let Some(customer) = customer {
883 fields.push(("customer", customer.to_owned()));
884 }
885 fields
886}
887
888/// A card check's page's fields: setup mode, nothing charged, so nothing
889/// to tax. Setup mode takes no line items and no amount. The billing
890/// address is asked for all the same, and copied onto the customer once
891/// the card is checked (`fill_address`), so the plan and invoices that
892/// follow can be taxed.
893pub(crate) fn card_check_fields(workspace: &str, customer: &str, return_url: &str) -> Vec<(&'static str, String)> {
894 vec![
895 ("mode", "setup".to_owned()),
896 ("customer", customer.to_owned()),
897 ("payment_method_types[0]", "card".to_owned()),
898 ("payment_method_options[card][request_three_d_secure]", "any".to_owned()),
899 ("billing_address_collection", "required".to_owned()),
900 ("success_url", back_to(return_url, "card_check")),
901 ("cancel_url", return_url.to_owned()),
902 ("client_reference_id", workspace.to_owned()),
903 ("metadata[workspace]", workspace.to_owned()),
904 ("metadata[purpose]", "card_check".to_owned()),
905 ("setup_intent_data[metadata][workspace]", workspace.to_owned()),
906 ("setup_intent_data[description]", format!("Card check for g1t workspace {workspace}; never charged")),
907 ]
908}
909
910/// A Stripe invoice's tax settings, for every invoice g1t makes: worked out
911/// by Stripe Tax.
912pub(crate) fn invoice_tax_fields() -> Vec<(&'static str, String)> {
913 vec![("automatic_tax[enabled]", "true".to_owned())]
914}
915
916/// An invoice item's tax settings: g1t's tax code, the amount excluding tax.
917pub(crate) fn item_tax_fields() -> Vec<(&'static str, String)> {
918 vec![("tax_behavior", "exclusive".to_owned()), ("tax_code", TAX_CODE.to_owned())]
919}
920
921/// What a paid Stripe invoice comes to, as billing counts it: the tax
922/// (`tax`, in this API version), any card fee (its lines, by name, on
923/// invoices from before the fee was folded into prices), and what is left
924/// for what was sold, all in cents.
925#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
926pub(crate) struct InvoiceSplit {
927 pub tax_cents: i64,
928 pub fee_cents: i64,
929 pub net_cents: i64,
930}
931
932/// A plan started on a saved card, as its subscription needs it.
933pub(crate) struct SavedPlan<'a> {
934 pub workspace: &'a str,
935 pub feature: &'a str,
936 pub title: &'a str,
937 pub monthly_cents: u32,
938 pub customer: &'a str,
939 pub payment_method: &'a str,
940}
941
942/// A subscription's fields, started on a saved card: the plan as its only
943/// item, excluding tax, and Stripe Tax on.
944pub(crate) fn saved_subscription_fields(p: &SavedPlan<'_>, product: &str) -> Vec<(&'static str, String)> {
945 vec![
946 ("customer", p.customer.to_owned()),
947 ("default_payment_method", p.payment_method.to_owned()),
948 ("payment_behavior", "error_if_incomplete".to_owned()),
949 ("automatic_tax[enabled]", "true".to_owned()),
950 ("items[0][price_data][currency]", "usd".to_owned()),
951 ("items[0][price_data][product]", product.to_owned()),
952 ("items[0][price_data][unit_amount]", p.monthly_cents.to_string()),
953 ("items[0][price_data][recurring][interval]", "month".to_owned()),
954 ("items[0][price_data][tax_behavior]", "exclusive".to_owned()),
955 ("metadata[workspace]", p.workspace.to_owned()),
956 ("metadata[feature]", p.feature.to_owned()),
957 ("description", format!("{} plan for {}", p.title, p.workspace)),
958 ]
959}
960
961pub(crate) fn invoice_split(invoice: &serde_json::Value, amount_paid: i64) -> InvoiceSplit {
962 let tax_cents = invoice["tax"].as_i64().unwrap_or(0).max(0);
963 let fee_cents: i64 = invoice["lines"]["data"]
964 .as_array()
965 .map(|lines| {
966 lines
967 .iter()
968 .filter(|line| line["description"].as_str().is_some_and(|d| d.contains(CARD_FEE_LINE)))
969 .map(|line| line["amount"].as_i64().unwrap_or(0))
970 .sum()
971 })
972 .unwrap_or(0);
973 let fee_cents = fee_cents.max(0);
974 InvoiceSplit { tax_cents, fee_cents, net_cents: (amount_paid - tax_cents - fee_cents).max(0) }
975}
976
977impl Stripe {
978 /// What a card check's setup found, once it succeeded.
979 pub async fn checked_card(&self, setup_intent: &str) -> Result<Option<CheckedCard>> {
980 #[derive(Deserialize)]
981 struct Setup {
982 status: String,
983 payment_method: Option<String>,
984 }
985 #[derive(Deserialize)]
986 struct Card {
987 fingerprint: Option<String>,
988 brand: Option<String>,
989 last4: Option<String>,
990 funding: Option<String>,
991 country: Option<String>,
992 }
993 #[derive(Deserialize)]
994 struct Billing {
995 #[serde(default)]
996 address: Option<serde_json::Value>,
997 }
998 #[derive(Deserialize)]
999 struct PaymentMethod {
1000 card: Option<Card>,
1001 #[serde(default)]
1002 billing_details: Option<Billing>,
1003 }
1004 let setup: Setup = self.call(Method::Get, &format!("/setup_intents/{}", encode(setup_intent)), None).await?;
1005 let (true, Some(method)) = (setup.status == "succeeded", setup.payment_method) else { return Ok(None) };
1006 let found: PaymentMethod = self.call(Method::Get, &format!("/payment_methods/{}", encode(&method)), None).await?;
1007 let card = found.card;
1008 let address = found.billing_details.and_then(|b| b.address).filter(|a| a.is_object());
1009 Ok(Some(CheckedCard {
1010 address,
1011 payment_method: method,
1012 fingerprint: card.as_ref().and_then(|c| c.fingerprint.clone()),
1013 brand: card.as_ref().and_then(|c| c.brand.clone()),
1014 last4: card.as_ref().and_then(|c| c.last4.clone()),
1015 funding: card.as_ref().and_then(|c| c.funding.clone()),
1016 country: card.as_ref().and_then(|c| c.country.clone()),
1017 }))
1018 }
1019
1020 /// Makes `payment_method` the card the customer's invoices are charged to.
1021 pub async fn set_default_card(&self, customer: &str, payment_method: &str) -> Result<()> {
1022 let _: serde_json::Value = self
1023 .call(
1024 Method::Post,
1025 &format!("/customers/{}", encode(customer)),
1026 Some(form(&[("invoice_settings[default_payment_method]", payment_method.to_owned())])),
1027 )
1028 .await?;
1029 Ok(())
1030 }
1031
1032 /// One of g1t's products at Stripe, tagged `metadata[g1t]` (the plan's
1033 /// is `plan`), made the first time it is
1034 /// needed, with g1t's tax code. One made before Stripe Tax was on is
1035 /// given the code when it is found.
1036 async fn product(&self, tag: &str, name: &str) -> Result<String> {
1037 #[derive(Deserialize)]
1038 struct Product {
1039 id: String,
1040 #[serde(default)]
1041 metadata: Option<std::collections::HashMap<String, String>>,
1042 #[serde(default)]
1043 tax_code: Option<serde_json::Value>,
1044 }
1045 #[derive(Deserialize)]
1046 struct List {
1047 data: Vec<Product>,
1048 }
1049 let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?;
1050 let ours = |p: &Product| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag);
1051 if let Some(found) = list.data.into_iter().find(ours) {
1052 let coded = found.tax_code.as_ref().is_some_and(|code| code.as_str() == Some(TAX_CODE) || code["id"].as_str() == Some(TAX_CODE));
1053 if !coded {
1054 let _: serde_json::Value = self
1055 .call(Method::Post, &format!("/products/{}", encode(&found.id)), Some(form(&[("tax_code", TAX_CODE.to_owned())])))
1056 .await?;
1057 }
1058 return Ok(found.id);
1059 }
1060 let created: Product = self
1061 .call(
1062 Method::Post,
1063 "/products",
1064 Some(form(&[("name", name.to_owned()), ("metadata[g1t]", tag.to_owned()), ("tax_code", TAX_CODE.to_owned())])),
1065 )
1066 .await?;
1067 Ok(created.id)
1068 }
1069
1070 /// Archives one of g1t's products (by its `metadata[g1t]` tag), so it
1071 /// is never sold again; past invoices keep pointing at it. Nothing to
1072 /// do when there is no such active product.
1073 pub async fn archive_product(&self, tag: &str) -> Result<()> {
1074 #[derive(Deserialize)]
1075 struct Product {
1076 id: String,
1077 #[serde(default)]
1078 metadata: Option<std::collections::HashMap<String, String>>,
1079 }
1080 #[derive(Deserialize)]
1081 struct List {
1082 data: Vec<Product>,
1083 }
1084 let list: List = self.call(Method::Get, "/products?active=true&limit=100", None).await?;
1085 for product in list.data.into_iter().filter(|p| p.metadata.as_ref().and_then(|m| m.get("g1t")).map(String::as_str) == Some(tag)) {
1086 let _: serde_json::Value = self
1087 .call(Method::Post, &format!("/products/{}", encode(&product.id)), Some(form(&[("active", "false".to_owned())])))
1088 .await?;
1089 }
1090 Ok(())
1091 }
1092
1093 /// Starts the monthly plan on a saved card, at once, at its price with
1094 /// tax worked out by Stripe Tax on every invoice. Fails rather than leaving it half-started when the card's
1095 /// bank wants the person again, or when Stripe Tax cannot place the
1096 /// customer (no billing address yet); the caller then sends them to
1097 /// Stripe's page, which asks for the address.
1098 #[allow(clippy::too_many_arguments)]
1099 pub async fn subscribe_with_card(
1100 &self,
1101 workspace: &str,
1102 feature: &str,
1103 title: &str,
1104 monthly_cents: u32,
1105 customer: &str,
1106 payment_method: &str,
1107 ) -> Result<StripeSubscription> {
1108 let product = self.product(feature, &format!("{title} plan")).await?;
1109 let plan = SavedPlan { workspace, feature, title, monthly_cents, customer, payment_method };
1110 let fields = saved_subscription_fields(&plan, &product);
1111 let key = plan_key(workspace, feature, &format!("{payment_method}/{monthly_cents}"), g1t_kit::now_ms());
1112 self.send(Method::Post, "/subscriptions", Some(form(&fields)), Some(&key)).await
1113 }
1114
1115
1116 /// Ends a subscription now: one that never started properly.
1117 pub async fn cancel_now(&self, id: &str) -> Result<StripeSubscription> {
1118 self.call(Method::Delete, &format!("/subscriptions/{}", encode(id)), None).await
1119 }
1120
1121 pub async fn subscription(&self, id: &str) -> Result<StripeSubscription> {
1122 self.call(Method::Get, &format!("/subscriptions/{}", encode(id)), None)
1123 .await
1124 }
1125
1126 /// Ends a plan when its period does (`cancel` true), or takes that back.
1127 pub async fn cancel_at_period_end(&self, id: &str, cancel: bool) -> Result<StripeSubscription> {
1128 self.call(
1129 Method::Post,
1130 &format!("/subscriptions/{}", encode(id)),
1131 Some(form(&[("cancel_at_period_end", cancel.to_string())])),
1132 )
1133 .await
1134 }
1135
1136 pub async fn session(&self, id: &str) -> Result<Session> {
1137 self.call(
1138 Method::Get,
1139 &format!("/checkout/sessions/{}", encode(id)),
1140 None,
1141 )
1142 .await
1143 }
1144}
1145
1146/// Whether the processor said an id it was given does not exist, as when
1147/// g1t moves to another Stripe account and ids saved from the old one stay
1148/// behind, or the customer was deleted there.
1149pub(crate) fn is_missing(error: &Error) -> bool {
1150 error.to_string().contains("resource_missing")
1151}
1152
1153/// What reading a deleted customer comes to: Stripe's own shape for an id
1154/// it does not have, so `is_missing` and `friendly` read it as one.
1155const DELETED_CUSTOMER: &str = r#"the card processor answered 404: {"error": {"type": "invalid_request_error", "code": "resource_missing", "message": "The customer was deleted at Stripe."}}"#;
1156
1157/// Whether Stripe answered with a deleted customer (`{"id": "cus_…",
1158/// "object": "customer", "deleted": true}`), which it does with a 200.
1159pub(crate) fn is_deleted_customer(found: &serde_json::Value) -> bool {
1160 found["deleted"].as_bool() == Some(true) && found["object"].as_str() == Some("customer")
1161}
1162
1163pub(crate) fn is_live(key: &str) -> bool {
1164 key.starts_with("sk_live_") || key.starts_with("rk_live_")
1165}
1166
1167#[cfg(test)]
1168mod tax_mode_tests {
1169 use super::*;
1170
1171 #[test]
1172 fn untaxed_requests_lose_only_automatic_tax() {
1173 let body = form(&[("mode", "payment".to_owned()), ("automatic_tax[enabled]", "true".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]);
1174 assert_eq!(without_automatic_tax(&body), form(&[("mode", "payment".to_owned()), ("tax_id_collection[enabled]", "true".to_owned())]));
1175 assert!(taxed_path("/checkout/sessions") && taxed_path("/invoices") && taxed_path("/subscriptions"));
1176 assert!(!taxed_path("/invoices/in_1/finalize") && !taxed_path("/payment_intents"));
1177 }
1178
1179 #[test]
1180 fn without_stripe_tax_a_live_key_charges_nothing_and_test_mode_goes_untaxed() {
1181 let body = form(&[("mode", "payment".to_owned()), ("automatic_tax[enabled]", "true".to_owned())]);
1182 assert_eq!(untaxed_body(false, &body).unwrap(), form(&[("mode", "payment".to_owned())]));
1183 let refused = untaxed_body(true, &body).unwrap_err();
1184 // Refused as Stripe would, never a decline, with a sentence for the page.
1185 assert!(friendly(&refused).contains("sales tax"));
1186 assert!(!crate::invoices::is_decline(&refused.to_string()));
1187 }
1188
1189 #[test]
1190 fn a_workspace_gets_one_customer_with_its_owners_email() {
1191 let fields = customer_fields("acme", Some(" ana@acme.test "));
1192 assert!(fields.contains(&("email", "ana@acme.test".to_owned())));
1193 assert!(customer_fields("acme", None).iter().all(|(name, _)| *name != "email"));
1194 assert!(customer_fields("acme", Some("not an email")).iter().all(|(name, _)| *name != "email"));
1195 let at = 1_791_000_000_000;
1196 // Two asking at once make one; another workspace, or later, another.
1197 assert_eq!(customer_key("acme", Some("a@b.c"), at), customer_key("acme", Some("a@b.c"), at + 1_000));
1198 assert_ne!(customer_key("acme", Some("a@b.c"), at), customer_key("other", Some("a@b.c"), at));
1199 assert_ne!(customer_key("acme", Some("a@b.c"), at), customer_key("acme", Some("a@b.c"), at + 600_000));
1200 }
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205 use super::*;
1206
1207 #[test]
1208 fn asking_twice_for_a_plan_starts_one() {
1209 let at = 1_791_000_000_000;
1210 assert_eq!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_1", at + 1_000));
1211 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("acme", "plan", "pm_2", at));
1212 assert_ne!(plan_key("acme", "plan", "pm_1", at), plan_key("other", "plan", "pm_1", at));
1213 }
1214
1215 #[test]
1216 fn form_values_are_percent_encoded() {
1217 assert_eq!(
1218 form(&[
1219 (
1220 "success_url",
1221 "https://g1t.sh/a/-/billing?session={ID}".to_owned()
1222 ),
1223 ("line_items[0][quantity]", "1".to_owned()),
1224 ]),
1225 "success_url=https%3A%2F%2Fg1t.sh%2Fa%2F-%2Fbilling%3Fsession%3D%7BID%7D&line_items%5B0%5D%5Bquantity%5D=1"
1226 );
1227 }
1228
1229 #[test]
1230 fn test_keys_are_not_live() {
1231 assert!(is_live("sk_live_abc"));
1232 assert!(!is_live("sk_test_abc"));
1233 assert!(!is_live(""));
1234 }
1235
1236 fn has(fields: &[(&str, String)], name: &str) -> Option<String> {
1237 fields.iter().find(|(n, _)| *n == name).map(|(_, v)| v.clone())
1238 }
1239
1240 #[test]
1241 fn every_request_names_the_api_version_it_is_written_for() {
1242 // Without it a new Stripe account answers at its newest version, and
1243 // invoices, charges and pages read differently from what billing
1244 // expects.
1245 assert!(STRIPE_VERSION.starts_with("2025-02-24"));
1246 let source = include_str!("stripe.rs");
1247 assert!(source.contains(concat!("headers.set(\"stripe-", "version\", STRIPE_VERSION)")));
1248 }
1249
1250 #[test]
1251 fn the_plans_page_is_a_subscription_without_payment_mode_fields() {
1252 let url = "https://g1t.sh/acme/-/billing?plan=plan";
1253 for customer in [None, Some("cus_1")] {
1254 let fields = subscription_fields("acme", "plan", "g1t", 2_100, customer, url);
1255 assert_eq!(has(&fields, "mode").as_deref(), Some("subscription"));
1256 // customer_creation is for payment mode; Stripe refuses it here.
1257 assert!(has(&fields, "customer_creation").is_none());
1258 assert!(has(&fields, "payment_intent_data[setup_future_usage]").is_none());
1259 assert_eq!(has(&fields, "customer").as_deref(), customer);
1260 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?plan=plan&session={CHECKOUT_SESSION_ID}");
1261 assert_eq!(has(&fields, "line_items[0][price_data][recurring][interval]").as_deref(), Some("month"));
1262 // The plan at its price is the only line: no card fee.
1263 assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("2100"));
1264 assert!(has(&fields, "line_items[1][quantity]").is_none());
1265 }
1266 }
1267
1268 /// Every field a page must carry for Stripe Tax: tax on top of the
1269 /// price, an address always asked for, the buyer's tax ID, and each
1270 /// line at g1t's tax code, excluding tax. With a customer, what is
1271 /// entered is saved on it (Checkout refuses `automatic_tax` and
1272 /// `tax_id_collection` for a customer otherwise).
1273 fn assert_taxed_page(fields: &[(&str, String)], customer: Option<&str>) {
1274 assert_eq!(has(fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1275 assert_eq!(has(fields, "billing_address_collection").as_deref(), Some("required"));
1276 assert_eq!(has(fields, "tax_id_collection[enabled]").as_deref(), Some("true"));
1277 let saved = if customer.is_some() { Some("auto") } else { None };
1278 assert_eq!(has(fields, "customer_update[address]").as_deref(), saved);
1279 assert_eq!(has(fields, "customer_update[name]").as_deref(), saved);
1280 assert_eq!(has(fields, LINE_KEYS[3]).as_deref(), Some("exclusive"));
1281 assert_eq!(has(fields, LINE_KEYS[5]).as_deref(), Some(TAX_CODE));
1282 // One line, never a second for a card fee.
1283 assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items[1]")));
1284 // No key twice: Stripe takes the last, silently.
1285 let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
1286 names.sort_unstable();
1287 let count = names.len();
1288 names.dedup();
1289 assert_eq!(names.len(), count);
1290 }
1291
1292 #[test]
1293 fn every_payment_page_is_taxed_by_stripe_tax() {
1294 let url = "https://g1t.sh/acme/-/billing";
1295 for customer in [None, Some("cus_1")] {
1296 // The plan and Security and quality.
1297 assert_taxed_page(&subscription_fields("acme", "plan", "g1t", 2_100, customer, url), customer);
1298 assert_taxed_page(&subscription_fields("acme", "security", "Security and quality", 1_000, customer, url), customer);
1299 // Prepaying by card and by bank transfer alike.
1300 assert_taxed_page(&prepay_fields("acme", 5_000, customer, url, false), customer);
1301 assert_taxed_page(&prepay_fields("acme", 100_000, customer, url, true), customer);
1302 }
1303 // tax_id_collection and customer_update are for payment and
1304 // subscription mode; a card check charges nothing, so it is not
1305 // taxed, but it asks for the address the plan will be taxed at.
1306 let check = card_check_fields("acme", "cus_1", url);
1307 assert!(has(&check, "automatic_tax[enabled]").is_none());
1308 assert_eq!(has(&check, "billing_address_collection").as_deref(), Some("required"));
1309 }
1310
1311 #[test]
1312 fn the_portal_manages_details_cards_invoices_and_ending_the_plan() {
1313 let fields = portal_fields();
1314 let updates: Vec<&str> =
1315 fields.iter().filter(|(n, _)| n.starts_with("features[customer_update][allowed_updates]")).map(|(_, v)| v.as_str()).collect();
1316 assert_eq!(updates, ["email", "address", "name", "tax_id", "phone"]);
1317 for (name, value) in [
1318 ("features[customer_update][enabled]", "true"),
1319 ("features[payment_method_update][enabled]", "true"),
1320 ("features[invoice_history][enabled]", "true"),
1321 ("features[subscription_cancel][enabled]", "true"),
1322 ("features[subscription_cancel][mode]", "at_period_end"),
1323 ("features[subscription_cancel][cancellation_reason][enabled]", "true"),
1324 ("features[subscription_update][enabled]", "false"),
1325 ("business_profile[privacy_policy_url]", "https://g1t.sh/policies/privacy"),
1326 ("business_profile[terms_of_service_url]", "https://g1t.sh/policies/terms"),
1327 ("metadata[g1t]", "billing"),
1328 ] {
1329 assert_eq!(has(&fields, name).as_deref(), Some(value), "{name}");
1330 }
1331 assert!(has(&fields, "business_profile[headline]").is_some());
1332 // Stripe wants the reasons whenever it asks for one.
1333 assert_eq!(has(&fields, "features[subscription_cancel][cancellation_reason][options][7]").as_deref(), Some("other"));
1334 let mut names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
1335 names.sort_unstable();
1336 let count = names.len();
1337 names.dedup();
1338 assert_eq!(names.len(), count);
1339 }
1340
1341 #[test]
1342 fn our_portal_configuration_is_found_by_its_tag_not_made_twice() {
1343 let config = |id: &str, active: bool, tag: Option<&str>| PortalConfiguration {
1344 id: id.to_owned(),
1345 active,
1346 login_page: None,
1347 metadata: tag.map(|t| std::collections::HashMap::from([("g1t".to_owned(), t.to_owned())])),
1348 };
1349 assert_eq!(ours(vec![config("a", true, None), config("b", false, Some("billing")), config("c", true, Some("billing"))]).map(|c| c.id).as_deref(), Some("c"));
1350 assert_eq!(ours(vec![config("b", false, Some("billing"))]).map(|c| c.id).as_deref(), Some("b"));
1351 assert!(ours(vec![config("a", true, None), config("d", true, Some("other"))]).is_none());
1352 }
1353
1354 #[test]
1355 fn stripe_taxs_settings_say_what_is_missing() {
1356 let settings: TaxSettings =
1357 serde_json::from_value(serde_json::json!({ "status": "pending", "status_details": { "pending": { "missing_fields": ["head_office"] } } })).unwrap();
1358 assert_eq!(settings.status, "pending");
1359 assert_eq!(settings.status_details.pending.and_then(|p| p.missing_fields), Some(vec!["head_office".to_owned()]));
1360 let active: TaxSettings = serde_json::from_value(serde_json::json!({ "status": "active", "status_details": { "active": {} } })).unwrap();
1361 assert!(active.status_details.pending.is_none());
1362 }
1363
1364 #[test]
1365 fn a_deleted_customer_reads_as_missing() {
1366 let deleted = serde_json::json!({ "id": "cus_1", "object": "customer", "deleted": true });
1367 assert!(is_deleted_customer(&deleted));
1368 assert!(is_missing(&Error::RustError(DELETED_CUSTOMER.to_owned())));
1369 assert_eq!(friendly(&Error::RustError(DELETED_CUSTOMER.to_owned())), "Stripe refused it: The customer was deleted at Stripe.");
1370 // A customer as usual, and a deleted thing that is not a customer.
1371 assert!(!is_deleted_customer(&serde_json::json!({ "id": "cus_1", "object": "customer", "email": null })));
1372 assert!(!is_deleted_customer(&serde_json::json!({ "id": "txi_1", "object": "tax_id", "deleted": true })));
1373 }
1374
1375 #[test]
1376 fn no_prepayment_has_a_card_fee_line() {
1377 for bank_transfer in [true, false] {
1378 let fields = prepay_fields("acme", 5_000, Some("cus_1"), "https://g1t.sh/acme/-/billing", bank_transfer);
1379 assert_eq!(has(&fields, "line_items[0][price_data][unit_amount]").as_deref(), Some("5000"));
1380 assert!(has(&fields, "line_items[1][quantity]").is_none());
1381 assert!(fields.iter().all(|(_, v)| !v.contains(CARD_FEE_LINE)));
1382 }
1383 }
1384
1385 #[test]
1386 fn a_plan_on_a_saved_card_is_taxed_at_its_price_alone() {
1387 let plan = SavedPlan { workspace: "acme", feature: "plan", title: "g1t", monthly_cents: 2_100, customer: "cus_1", payment_method: "pm_1" };
1388 let fields = saved_subscription_fields(&plan, "prod_plan");
1389 assert_eq!(has(&fields, "automatic_tax[enabled]").as_deref(), Some("true"));
1390 assert_eq!(has(&fields, "items[0][price_data][tax_behavior]").as_deref(), Some("exclusive"));
1391 assert_eq!(has(&fields, "items[0][price_data][unit_amount]").as_deref(), Some("2100"));
1392 assert!(fields.iter().all(|(n, _)| !n.starts_with("items[1]")));
1393 }
1394
1395 #[test]
1396 fn invoices_and_their_lines_are_taxed() {
1397 assert_eq!(has(&invoice_tax_fields(), "automatic_tax[enabled]").as_deref(), Some("true"));
1398 let item = item_tax_fields();
1399 assert_eq!(has(&item, "tax_behavior").as_deref(), Some("exclusive"));
1400 assert_eq!(has(&item, "tax_code").as_deref(), Some(TAX_CODE));
1401 }
1402
1403 #[test]
1404 fn a_refund_reverses_part_of_its_tax() {
1405 let reversal = reversal_fields("tax_1", "pi_1/re_1", 500);
1406 assert_eq!(has(&reversal, "flat_amount").as_deref(), Some("-500"));
1407 assert_eq!(has(&reversal, "mode").as_deref(), Some("partial"));
1408 }
1409
1410 #[test]
1411 fn a_paid_invoice_splits_into_tax_card_fee_and_what_was_sold() {
1412 let invoice = serde_json::json!({
1413 "tax": 180,
1414 "lines": { "data": [
1415 { "description": "1 × g1t plan (at $20.00 / month)", "amount": 2000 },
1416 { "description": "1 × Card processing fee (at $0.92 / month)", "amount": 92 },
1417 ] }
1418 });
1419 assert_eq!(invoice_split(&invoice, 2_272), InvoiceSplit { tax_cents: 180, fee_cents: 92, net_cents: 2_000 });
1420 // Before Stripe Tax: no tax, no fee, all of it sold.
1421 assert_eq!(invoice_split(&serde_json::json!({ "tax": null }), 2_000).net_cents, 2_000);
1422 // A page's tax and what came before it.
1423 let session: Session = serde_json::from_value(serde_json::json!({
1424 "id": "cs_1", "payment_status": "paid", "amount_total": 5_585, "amount_subtotal": 5_185,
1425 "total_details": { "amount_tax": 400 }, "customer": "cus_1", "payment_intent": "pi_1"
1426 }))
1427 .unwrap();
1428 assert_eq!((session.tax_cents(), session.before_tax_cents()), (400, 5_185));
1429 }
1430
1431 #[test]
1432 fn an_address_places_a_customer_for_tax() {
1433 use serde_json::json;
1434 assert!(address_places_customer(&json!({ "country": "DE" })));
1435 assert!(address_places_customer(&json!({ "country": "US", "postal_code": "94107" })));
1436 assert!(!address_places_customer(&json!({ "country": "US", "postal_code": "" })));
1437 assert!(address_places_customer(&json!({ "country": "CA", "state": "ON" })));
1438 assert!(!address_places_customer(&json!({ "country": "" })));
1439 assert!(!address_places_customer(&serde_json::Value::Null));
1440 let error = Error::RustError(r#"the card processor answered 400: {"error":{"code":"customer_tax_location_invalid","message":"x"}}"#.into());
1441 assert!(is_tax_location_error(&error));
1442 }
1443
1444 #[test]
1445 fn a_card_check_is_a_setup_page_with_no_amount() {
1446 let fields = card_check_fields("acme", "cus_1", "https://g1t.sh/acme/-/billing");
1447 assert_eq!(has(&fields, "mode").as_deref(), Some("setup"));
1448 assert!(fields.iter().all(|(n, _)| !n.starts_with("line_items")));
1449 assert_eq!(has(&fields, "success_url").unwrap(), "https://g1t.sh/acme/-/billing?card_check={CHECKOUT_SESSION_ID}");
1450 assert_eq!(has(&fields, "customer").as_deref(), Some("cus_1"));
1451 }
1452
1453 #[test]
1454 fn a_page_asked_for_twice_is_one_page() {
1455 let at = 1_791_000_000_000;
1456 assert_eq!(page_key("plan", "acme", "plan/2000", at), page_key("plan", "acme", "plan/2000", at + 60_000));
1457 assert_ne!(page_key("plan", "acme", "plan/2000", at), page_key("prepay", "acme", "plan/2000", at));
1458 }
1459
1460 #[test]
1461 fn a_stripe_failure_reads_as_a_sentence_never_raw() {
1462 let refused = Error::RustError(
1463 r#"the card processor answered 400: {"error":{"message":"You may only specify one of these parameters: customer, customer_creation.","type":"invalid_request_error"}}"#.into(),
1464 );
1465 assert_eq!(friendly(&refused), "Stripe refused it: You may only specify one of these parameters: customer, customer_creation.");
1466 assert!(!friendly(&refused).contains("invalid_request_error"));
1467 let odd = Error::RustError("the card processor answered 502: <html>".into());
1468 assert!(friendly(&odd).starts_with("Stripe refused it. Try again"));
1469 let down = Error::RustError("network connection lost".into());
1470 assert_eq!(friendly(&down), "Stripe could not be reached. Try again in a minute.");
1471 }
1472}