feat(billing): B-2.7 Stripe Checkout 3 plans CAD/TVQ + Apple/Google Pay

Adds the customer-facing checkout flow under /checkout/<plan>:
- src/billing/plans.py — Plan dataclass + 3 plans (DictIA 8 / 16 / Cloud),
  monthly + yearly Price IDs resolved from STRIPE_DICTIA_*_{SETUP,MONTHLY,YEARLY} env.
- src/billing/stripe_client.py — lazy stripe.api_key init, get_or_create_customer
  (persists user.stripe_customer_id), create_checkout_session with mode=subscription,
  currency=cad, automatic_tax=true (TPS 5% + TVQ 9.975%), billing_address_collection,
  metadata on both Session and Subscription for the B-2.8 webhook.
- src/billing/routes.py — GET /checkout/<plan>?period=monthly|yearly returns 303
  redirect to Stripe-hosted Checkout. Friendly French flash + redirect to /tarifs
  on unknown plan, missing STRIPE_SECRET_KEY, missing Price IDs, or Stripe API error.
  GET /checkout/success and /checkout/cancel render brand-tokenized templates that
  extend marketing/base.html.
- templates/billing/{success,cancel}.html — explicit "activé sous quelques minutes"
  note (webhook is async), aucun montant prélevé reassurance on cancel.
- config/env.stripe.example — env vars + Stripe Dashboard setup checklist
  (CAD activation, Stripe Tax registrations, Apple/Google Pay enable, webhook).
- tests/test_stripe_checkout.py — 25 tests covering plans, stripe_client, routes,
  and the _PUBLIC_INDEXABLE_ENDPOINTS integration. Stripe SDK mocked via
  unittest.mock.patch (no network). Windows manual driver included.

Webhook (B-2.8) will be the source of truth for user.subscription_status.
This task only mutates user.stripe_customer_id (identity, not state).
Existing pricing CTAs in templates/marketing/_partials/_pricing_tiers.html
already link to /checkout/<slug> (verified) — no marketing template touched.

Tests: 25/25 new + 89/89 prior pass on Windows manual driver.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Allison
2026-04-28 08:26:13 -04:00
parent b8fa321edd
commit f1a5ad565f
9 changed files with 1239 additions and 1 deletions

View File

@@ -8,10 +8,17 @@ Routes added in Tasks B-2.7 (checkout) and B-2.8 (webhook).
"""
from flask import Blueprint
# template_folder points at the project-level `templates/` so render_template
# can resolve names like 'billing/success.html' the same way the marketing
# and legal blueprints resolve 'marketing/...' / 'legal/...'.
billing_bp = Blueprint(
'billing',
__name__,
url_prefix='/checkout',
template_folder='../../templates/billing',
template_folder='../../templates',
static_folder=None,
)
# Import routes to register them on billing_bp. Must come after blueprint
# instantiation. Keep the # noqa comments — these guards exist for ruff/flake8.
from src.billing import routes # noqa: E402, F401

97
src/billing/plans.py Normal file
View File

@@ -0,0 +1,97 @@
"""DictIA pricing plans (B-2.7).
Centralized plan registry. Stripe Price IDs are resolved from environment
variables — set STRIPE_<PLAN>_<PERIOD> env vars in production. The slug
(`dictia-8`, `dictia-16`, `dictia-cloud`) is the canonical identifier
used throughout the codebase (URL params, webhook metadata, audit logs).
Pricing reference (CAD, pre-tax — TPS/TVQ added by Stripe automatic_tax):
- DictIA 8: 3 450$ setup (one-time) + 173$/mo recurring (or yearly = 173 × 12 × 0.85)
- DictIA 16: 5 750$ setup (one-time) + 201$/mo recurring (or yearly = 201 × 12 × 0.85)
- DictIA Cloud: 369$/mo recurring (or yearly = 369 × 12 × 0.85)
"""
import os
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass(frozen=True)
class Plan:
"""A DictIA subscription plan.
Stripe Price IDs are resolved lazily from environment variables — the
Plan instance itself only stores the variable names. This lets the
application boot without Stripe credentials (CI, dev branches) and
keeps secrets out of source control.
"""
slug: str
name: str
description_fr: str
has_setup_fee: bool
monthly_env: str
yearly_env: str
setup_env: Optional[str] = None # only set for plans with a setup fee
def setup_price_id(self) -> Optional[str]:
if not self.has_setup_fee or not self.setup_env:
return None
return os.environ.get(self.setup_env)
def monthly_price_id(self) -> Optional[str]:
return os.environ.get(self.monthly_env)
def yearly_price_id(self) -> Optional[str]:
return os.environ.get(self.yearly_env)
def is_configured(self) -> bool:
"""True when all required Stripe Price IDs are set in the environment."""
if self.has_setup_fee and not self.setup_price_id():
return False
return bool(self.monthly_price_id() and self.yearly_price_id())
def price_id_for_period(self, period: str) -> Optional[str]:
return self.yearly_price_id() if period == 'yearly' else self.monthly_price_id()
PLANS: Dict[str, Plan] = {
'dictia-8': Plan(
slug='dictia-8',
name='DictIA 8',
description_fr='Boîtier 8 canaux + transcription IA locale (poste de travail).',
has_setup_fee=True,
setup_env='STRIPE_DICTIA_8_SETUP',
monthly_env='STRIPE_DICTIA_8_MONTHLY',
yearly_env='STRIPE_DICTIA_8_YEARLY',
),
'dictia-16': Plan(
slug='dictia-16',
name='DictIA 16',
description_fr='Boîtier 16 canaux + transcription IA locale (salle de réunion).',
has_setup_fee=True,
setup_env='STRIPE_DICTIA_16_SETUP',
monthly_env='STRIPE_DICTIA_16_MONTHLY',
yearly_env='STRIPE_DICTIA_16_YEARLY',
),
'dictia-cloud': Plan(
slug='dictia-cloud',
name='DictIA Cloud',
description_fr='Transcription IA hébergée au Québec, 100% conforme Loi 25.',
has_setup_fee=False,
monthly_env='STRIPE_DICTIA_CLOUD_MONTHLY',
yearly_env='STRIPE_DICTIA_CLOUD_YEARLY',
),
}
VALID_PERIODS = ('monthly', 'yearly')
def get_plan(slug: str) -> Optional[Plan]:
"""Return the Plan for `slug`, or None if unknown."""
if not slug:
return None
return PLANS.get(slug)
def list_plans() -> List[Plan]:
"""Return all registered plans in registration order."""
return list(PLANS.values())

126
src/billing/routes.py Normal file
View File

@@ -0,0 +1,126 @@
"""Billing routes — Stripe Checkout (B-2.7).
URL space (prefix `/checkout`, set on billing_bp):
- GET /checkout/<plan>?period=monthly|yearly → 303 redirect to Stripe-hosted Checkout
- GET /checkout/success?session_id=... → confirmation page (async activation note)
- GET /checkout/cancel → friendly "no charge made" page
The webhook route (B-2.8) is registered separately at /webhooks/stripe outside
the /checkout prefix and is CSRF-exempt.
"""
import logging
from flask import (
Blueprint, current_app, flash, redirect, render_template,
request, url_for,
)
from flask_login import current_user, login_required
from src.billing import billing_bp
from src.billing.plans import VALID_PERIODS, get_plan
from src.billing.stripe_client import (
StripeNotConfiguredError,
create_checkout_session,
is_stripe_configured,
)
logger = logging.getLogger(__name__)
@billing_bp.route('/<plan>')
@login_required
def checkout(plan):
"""Initiate Stripe Checkout for the given plan + period.
Redirects to /tarifs with a French flash on any error (unknown plan,
Stripe not configured, plan Price IDs missing, Stripe API failure).
Returns a 303 See Other redirect to the Stripe-hosted Checkout on success
(303 is what Stripe documents for HTTP redirects to checkout.stripe.com).
"""
plan_obj = get_plan(plan)
if plan_obj is None:
flash('Forfait inconnu.', 'danger')
return redirect(url_for('marketing.tarifs'))
period = request.args.get('period', 'monthly')
if period not in VALID_PERIODS:
period = 'monthly'
if not is_stripe_configured():
flash(
"Le paiement en ligne n'est pas disponible pour le moment. "
"Contactez info@dictia.ca pour finaliser votre abonnement.",
'warning',
)
return redirect(url_for('marketing.tarifs'))
if not plan_obj.is_configured():
flash(
"Ce forfait n'est pas encore configuré. Contactez info@dictia.ca.",
'warning',
)
return redirect(url_for('marketing.tarifs'))
success_url = url_for('billing.success', _external=True)
cancel_url = url_for('billing.cancel', _external=True)
try:
session = create_checkout_session(
plan_slug=plan,
period=period,
user=current_user,
success_url=success_url,
cancel_url=cancel_url,
)
except StripeNotConfiguredError as e:
logger.error('Stripe not configured at checkout: %s', e)
flash(
"Le paiement en ligne n'est pas disponible. "
"Contactez info@dictia.ca.",
'warning',
)
return redirect(url_for('marketing.tarifs'))
except ValueError as e:
logger.warning('Invalid checkout request: %s', e)
flash('Demande de paiement invalide.', 'danger')
return redirect(url_for('marketing.tarifs'))
except Exception as e: # noqa: BLE001
logger.exception(
'Stripe Checkout creation failed for user %s plan %s: %s',
getattr(current_user, 'id', '?'), plan, e,
)
flash(
"Une erreur est survenue lors de l'ouverture du paiement. "
"Réessayez ou contactez info@dictia.ca.",
'danger',
)
return redirect(url_for('marketing.tarifs'))
# Stripe documents 303 See Other for hosted-Checkout redirects.
return redirect(session.url, code=303)
@billing_bp.route('/success')
def success():
"""Post-payment confirmation page.
The session_id query param is preserved for optional client-side analytics
but is NOT trusted server-side — Stripe's webhook (B-2.8) is the source of
truth for subscription state. This page makes that asynchrony explicit
("Votre abonnement sera activé sous quelques minutes.").
"""
session_id = request.args.get('session_id')
return render_template(
'billing/success.html',
title='Paiement confirmé — DictIA',
session_id=session_id,
)
@billing_bp.route('/cancel')
def cancel():
"""User cancelled the Stripe Checkout. No state to revert; no charge made."""
return render_template(
'billing/cancel.html',
title='Paiement annulé — DictIA',
)

View File

@@ -0,0 +1,139 @@
"""Stripe SDK client wrapper (B-2.7).
Lazy-initializes stripe.api_key from STRIPE_SECRET_KEY at first use, so the
app can boot without Stripe credentials (CI, dev, contributor branches).
Raises StripeNotConfiguredError if a Stripe API call is attempted without
the key set.
This module is intentionally thin: it owns the stripe.* call surface used by
B-2.7 (Checkout) and is reused by B-2.8 (webhook signature verification).
No subscription state is persisted here — the webhook is the source of truth
for `user.subscription_status`. The only User mutation is `stripe_customer_id`
(identity, not state).
"""
import os
from typing import List
import stripe
class StripeNotConfiguredError(RuntimeError):
"""Raised when STRIPE_SECRET_KEY (or a plan Price ID) is missing at call time."""
def is_stripe_configured() -> bool:
"""Return True if STRIPE_SECRET_KEY is set in the environment."""
return bool(os.environ.get('STRIPE_SECRET_KEY'))
def _ensure_configured() -> None:
"""Lazy-initialize stripe.api_key. Raises if STRIPE_SECRET_KEY is missing."""
if not is_stripe_configured():
raise StripeNotConfiguredError(
'STRIPE_SECRET_KEY is not set. Configure it before using billing.'
)
if not stripe.api_key:
stripe.api_key = os.environ['STRIPE_SECRET_KEY']
def get_or_create_customer(user) -> str:
"""Return the Stripe customer ID for `user`, creating one if needed.
Persists the Stripe customer ID on user.stripe_customer_id so subsequent
checkouts (and the webhook) can correlate Stripe events back to the user.
"""
from src.database import db
_ensure_configured()
if user.stripe_customer_id:
return user.stripe_customer_id
customer = stripe.Customer.create(
email=user.email,
name=(user.name or user.username),
metadata={
'dictia_user_id': str(user.id),
'dictia_username': user.username,
},
)
user.stripe_customer_id = customer.id
db.session.commit()
return customer.id
def create_checkout_session(
plan_slug: str,
period: str,
user,
success_url: str,
cancel_url: str,
):
"""Create a Stripe Checkout Session for the given plan + period.
Configuration applied:
- mode='subscription' (recurring)
- currency='cad'
- automatic_tax.enabled=true (Stripe applies TPS 5% + TVQ 9.975%)
- billing_address_collection='required' (needed for Tax)
- allow_promotion_codes=true
- Apple/Google Pay are auto-enabled for card payments in Stripe Dashboard
- Hardware plans (8/16) include a one-time setup line item AND the
recurring subscription line item.
The success_url is decorated with `?session_id={CHECKOUT_SESSION_ID}` so
the success page can optionally surface the session id (analytics).
"""
from src.billing.plans import VALID_PERIODS, get_plan
_ensure_configured()
plan = get_plan(plan_slug)
if plan is None:
raise ValueError(f'Unknown plan: {plan_slug!r}')
if period not in VALID_PERIODS:
raise ValueError(
f'Invalid period: {period!r} (expected one of {VALID_PERIODS})'
)
if not plan.is_configured():
raise StripeNotConfiguredError(
f'Stripe Price IDs for {plan_slug!r} are not set in environment.'
)
customer_id = get_or_create_customer(user)
line_items: List[dict] = []
# One-time setup fee for hardware plans (DictIA 8 / DictIA 16)
if plan.has_setup_fee:
setup_id = plan.setup_price_id()
if setup_id:
line_items.append({'price': setup_id, 'quantity': 1})
# Recurring subscription
line_items.append({
'price': plan.price_id_for_period(period),
'quantity': 1,
})
# Inject CHECKOUT_SESSION_ID placeholder while preserving any existing query string
decorated_success_url = success_url + (
'&' if '?' in success_url else '?'
) + 'session_id={CHECKOUT_SESSION_ID}'
metadata = {
'dictia_user_id': str(user.id),
'dictia_plan_slug': plan_slug,
'dictia_period': period,
}
return stripe.checkout.Session.create(
mode='subscription',
customer=customer_id,
line_items=line_items,
success_url=decorated_success_url,
cancel_url=cancel_url,
automatic_tax={'enabled': True},
currency='cad',
billing_address_collection='required',
customer_update={'address': 'auto', 'name': 'auto'},
allow_promotion_codes=True,
metadata=metadata,
# Webhook (B-2.8) reads metadata off the subscription, not the session
subscription_data={'metadata': metadata},
)