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.

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