package main // πŸ€– enterprise.go β€” checkout for the Eleven Enterprise Edition page // (elevenmessenger.com/enterprise/): the satirical-but-real €1,100,000/year // invoice. A public, CORS-scoped endpoint that mints a Stripe Checkout // Session for year one; the page redirects the buyer to Stripe's hosted // payment page and celebrates on return. // // Deliberate shape: // - Its Stripe key is LCHAT_STRIPE_ENTERPRISE_KEY, separate from the space // billing key and with NO fallback to it β€” so the page runs against the // sandbox while real billing stays live, and going live is an explicit // operator act (swapping that one value), never a config accident. // - The browser calls this directly (the marketing site is static GitHub // Pages with no backend), so unlike every other billing route this one is // public: CORS pinned to the marketing origin, fixed server-side redirect // URLs (the client picks nothing), and a global mint rate limit. // - Amounts are compiled in, not client-supplied: the client sends only a // seat count, the intern flag, and a currency. The numerals are identical // in every currency β€” the elevens are load-bearing, we don't do exchange // rates. // - mode=payment (year one, one invoice). The +11%/year escalator stays // contractual comedy until a subscription-schedule slice earns its keep. import ( "encoding/json" "fmt" "io" "log" "net/http" "net/url" "strconv" "strings" "sync" "time" ) // The price list, in minor units (cents/pence β€” EUR, USD and GBP all Γ—100). // Base €1,100,000 minus the €121,000 only-for-you offer (11% of base, 11Β² // thousand); €11 a seat; the intern β€” one eleventh of an employee β€” exactly 1. const ( enterpriseBaseMinor = (1_100_000 - 121_000) * 100 enterpriseSeatMinor = 11 * 100 enterpriseInternMinor = 1 * 100 // The intern is only ever the .09 of the blessed 1010.09 headcount. enterpriseInternSeats = 1010 // Stripe caps a single payment at 8 digits of the minor unit // (99,999,999 β‰ˆ €999,999.99). The only-for-you offer is what carries the // invoice under that cap at all; past this many seats even the offer // can't save it, and Sales will call you. enterpriseMaxSeats = (99_999_999 - enterpriseBaseMinor) / enterpriseSeatMinor ) var enterpriseCurrencies = map[string]bool{"eur": true, "usd": true, "gbp": true} // enterpriseCheckout holds the page's Stripe config. nil on cloudServer = // the feature is off and the endpoint answers 501. type enterpriseCheckout struct { key string // LCHAT_STRIPE_ENTERPRISE_KEY β€” sandbox until the deliberate live flip apiBase string // https://api.stripe.com; tests point it at a fake origin string // the marketing origin: CORS allow + redirect base client *http.Client limiter mintLimiter } func newEnterpriseCheckout(key, apiBase, origin string) *enterpriseCheckout { key = strings.TrimSpace(key) if key == "" { return nil } return &enterpriseCheckout{ key: key, apiBase: apiBase, origin: strings.TrimRight(origin, "/"), client: &http.Client{Timeout: 20 * time.Second}, limiter: mintLimiter{max: 30, window: time.Minute}, } } // mintLimiter is a global rolling-window cap on session mints β€” this endpoint // is public, and each hit costs a Stripe API call. Per-IP bookkeeping isn't // worth carrying for a page whose realistic traffic is one CFO at a time. type mintLimiter struct { mu sync.Mutex stamps []time.Time max int window time.Duration } func (l *mintLimiter) allow(now time.Time) bool { l.mu.Lock() defer l.mu.Unlock() keep := l.stamps[:0] for _, t := range l.stamps { if now.Sub(t) < l.window { keep = append(keep, t) } } l.stamps = keep if len(l.stamps) >= l.max { return false } l.stamps = append(l.stamps, now) return true } // enterpriseCORS stamps the CORS headers on every response from the endpoint. // The allow-origin is the single marketing origin, never *: the page is the // only legitimate caller, and scoping it keeps random sites from spending our // Stripe rate limit from their visitors' browsers. func (s *cloudServer) enterpriseCORS(w http.ResponseWriter) bool { if s.enterprise == nil { return false } h := w.Header() h.Set("Access-Control-Allow-Origin", s.enterprise.origin) h.Set("Vary", "Origin") return true } // enterprisePreflightHandler: OPTIONS /api/enterprise/checkout β€” the CORS // preflight for the cross-origin JSON POST below. func (s *cloudServer) enterprisePreflightHandler(w http.ResponseWriter, r *http.Request) { if !s.enterpriseCORS(w) { w.WriteHeader(http.StatusNotImplemented) return } h := w.Header() h.Set("Access-Control-Allow-Methods", "POST") h.Set("Access-Control-Allow-Headers", "Content-Type") h.Set("Access-Control-Max-Age", "86400") w.WriteHeader(http.StatusNoContent) } // enterpriseCheckoutHandler: POST /api/enterprise/checkout β€” mint the year-one // Checkout Session. Body: {"seats": n, "intern": bool, "currency": "eur"}. func (s *cloudServer) enterpriseCheckoutHandler(w http.ResponseWriter, r *http.Request) { if !s.enterpriseCORS(w) { writeControlErr(w, http.StatusNotImplemented, "unavailable", "enterprise checkout is not configured") return } e := s.enterprise if !e.limiter.allow(time.Now()) { writeControlErr(w, http.StatusTooManyRequests, "slow_down", "the till is busy β€” try again in a minute") return } var req struct { Seats int `json:"seats"` Intern bool `json:"intern"` Currency string `json:"currency"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4<<10)).Decode(&req); err != nil { writeControlErr(w, http.StatusBadRequest, "bad_request", "invalid JSON body") return } cur := strings.ToLower(strings.TrimSpace(req.Currency)) if !enterpriseCurrencies[cur] { writeControlErr(w, http.StatusBadRequest, "bad_request", "currency must be eur, usd or gbp") return } if req.Seats < 1 { writeControlErr(w, http.StatusBadRequest, "bad_request", "at least one employee required") return } // The intern is exactly the .09 of 1010.09 β€” any other fractional // headcount was already rounded to a person by the page. if req.Intern && req.Seats != enterpriseInternSeats { writeControlErr(w, http.StatusBadRequest, "bad_request", "the intern only joins a 1,010-person team") return } if req.Seats > enterpriseMaxSeats { writeControlErr(w, http.StatusBadRequest, "over_stripe_cap", fmt.Sprintf("Stripe cannot carry this much money in one payment β€” %s employees is the most it can hold. Sales will call you.", formatCount(enterpriseMaxSeats))) return } checkoutURL, err := e.createSession(cur, req.Seats, req.Intern) if err != nil { log.Printf("cloud: enterprise checkout (%s, %d seats, intern=%v): %v", cur, req.Seats, req.Intern, err) writeControlErr(w, http.StatusBadGateway, "checkout_failed", "couldn't start the checkout β€” please try again") return } writeJSON(w, http.StatusOK, map[string]any{"url": checkoutURL}) } // createSession builds the hosted Checkout page: three price_data line items // (no dashboard Prices to manage), fixed redirect URLs on the marketing // origin, and no customer identity β€” Stripe collects what it needs. func (e *enterpriseCheckout) createSession(currency string, seats int, intern bool) (string, error) { form := url.Values{} form.Set("mode", "payment") form.Set("line_items[0][price_data][currency]", currency) form.Set("line_items[0][price_data][product_data][name]", "Eleven Enterprise Edition β€” year one (only-for-you offer applied)") form.Set("line_items[0][price_data][unit_amount]", strconv.Itoa(enterpriseBaseMinor)) form.Set("line_items[0][quantity]", "1") form.Set("line_items[1][price_data][currency]", currency) form.Set("line_items[1][price_data][product_data][name]", "Seat β€” one employee, one year") form.Set("line_items[1][price_data][unit_amount]", strconv.Itoa(enterpriseSeatMinor)) form.Set("line_items[1][quantity]", strconv.Itoa(seats)) if intern { form.Set("line_items[2][price_data][currency]", currency) form.Set("line_items[2][price_data][product_data][name]", "The intern (one eleventh of an employee)") form.Set("line_items[2][price_data][unit_amount]", strconv.Itoa(enterpriseInternMinor)) form.Set("line_items[2][quantity]", "1") } form.Set("metadata[enterprise]", "1") form.Set("metadata[seats]", strconv.Itoa(seats)) form.Set("metadata[intern]", strconv.FormatBool(intern)) form.Set("success_url", e.origin+"/enterprise/?paid=1") form.Set("cancel_url", e.origin+"/enterprise/") req, err := http.NewRequest("POST", e.apiBase+"/v1/checkout/sessions", strings.NewReader(form.Encode())) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+e.key) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") resp, err := e.client.Do(req) if err != nil { return "", err } defer resp.Body.Close() var body struct { URL string `json:"url"` Error struct { Message string `json:"message"` } `json:"error"` } if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil { return "", fmt.Errorf("stripe: HTTP %d (unparseable body)", resp.StatusCode) } if resp.StatusCode != http.StatusOK || body.URL == "" { return "", fmt.Errorf("stripe: HTTP %d: %s", resp.StatusCode, body.Error.Message) } return body.URL, nil } // formatCount renders a count with locale-style thousands separators for the // one English error message that carries a number ("1,909 employees…"). func formatCount(n int) string { s := strconv.Itoa(n) for i := len(s) - 3; i > 0; i -= 3 { s = s[:i] + "," + s[i:] } return s }