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:
68
config/env.stripe.example
Normal file
68
config/env.stripe.example
Normal file
@@ -0,0 +1,68 @@
|
||||
###############################################################################
|
||||
# Stripe — Checkout + Subscriptions (B-2.7 / B-2.8)
|
||||
###############################################################################
|
||||
#
|
||||
# Required for the /checkout/<plan> flow and the /webhooks/stripe receiver.
|
||||
# The application will boot without these — billing routes will redirect to
|
||||
# /tarifs with a "contact info@dictia.ca" message until the keys are set.
|
||||
#
|
||||
# Get these from https://dashboard.stripe.com (CAD account)
|
||||
# - Use sk_test_/pk_test_/whsec_test_ keys against the Stripe test mode for
|
||||
# pre-prod. Switch to live keys ONLY after end-to-end CAD/TVQ rehearsal.
|
||||
|
||||
# STRIPE_SECRET_KEY=sk_test_... # or sk_live_...
|
||||
# STRIPE_PUBLISHABLE_KEY=pk_test_... # used client-side; not strictly needed for hosted Checkout
|
||||
# STRIPE_WEBHOOK_SECRET=whsec_... # for B-2.8 webhook signature verification
|
||||
|
||||
###############################################################################
|
||||
# Price IDs — one per plan, period, and (for hardware plans) setup fee.
|
||||
###############################################################################
|
||||
#
|
||||
# Format: price_xxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
# Naming convention in this codebase: STRIPE_<PLAN>_<TYPE>
|
||||
# PLAN = DICTIA_8 | DICTIA_16 | DICTIA_CLOUD
|
||||
# TYPE = SETUP (one-time, hardware only) | MONTHLY | YEARLY
|
||||
#
|
||||
# Yearly Price = Monthly Price × 12 × 0.85 (15 % discount). Configure both
|
||||
# Prices in the Stripe Dashboard for each plan.
|
||||
|
||||
# DictIA 8 (8-channel hardware bundle): 3 450 $ setup + 173 $/mo
|
||||
# STRIPE_DICTIA_8_SETUP=price_xxx
|
||||
# STRIPE_DICTIA_8_MONTHLY=price_xxx
|
||||
# STRIPE_DICTIA_8_YEARLY=price_xxx
|
||||
|
||||
# DictIA 16 (16-channel hardware bundle): 5 750 $ setup + 201 $/mo
|
||||
# STRIPE_DICTIA_16_SETUP=price_xxx
|
||||
# STRIPE_DICTIA_16_MONTHLY=price_xxx
|
||||
# STRIPE_DICTIA_16_YEARLY=price_xxx
|
||||
|
||||
# DictIA Cloud (SaaS-only, no hardware): 369 $/mo
|
||||
# STRIPE_DICTIA_CLOUD_MONTHLY=price_xxx
|
||||
# STRIPE_DICTIA_CLOUD_YEARLY=price_xxx
|
||||
|
||||
###############################################################################
|
||||
# Required Stripe Dashboard configuration
|
||||
###############################################################################
|
||||
#
|
||||
# 1. Activate CAD currency on the account (Settings → Account → Currencies).
|
||||
#
|
||||
# 2. Enable Stripe Tax with TPS (5 %) and TVQ (9.975 %) for Quebec
|
||||
# (Tax → Settings → Tax registrations → Canada → Quebec).
|
||||
# All Checkout Sessions are created with `automatic_tax: { enabled: true }`
|
||||
# and `billing_address_collection: required` so Stripe computes taxes.
|
||||
#
|
||||
# 3. Enable Apple Pay + Google Pay
|
||||
# (Settings → Payment methods → Apple Pay, Google Pay).
|
||||
# Apple Pay requires verifying the dictia.ca domain via the Stripe-hosted
|
||||
# `.well-known/apple-developer-merchantid-domain-association` file.
|
||||
#
|
||||
# 4. For each plan, create:
|
||||
# - One recurring monthly Price (CAD, billing_scheme=per_unit)
|
||||
# - One recurring yearly Price (CAD, = monthly × 12 × 0.85)
|
||||
# For DictIA 8 and DictIA 16, also create a one-time Price for the setup fee.
|
||||
#
|
||||
# 5. Create a webhook endpoint (B-2.8) pointing at https://dictia.ca/webhooks/stripe
|
||||
# with at least the events: checkout.session.completed,
|
||||
# customer.subscription.created, customer.subscription.updated,
|
||||
# customer.subscription.deleted, invoice.payment_failed.
|
||||
# Copy the signing secret into STRIPE_WEBHOOK_SECRET above.
|
||||
@@ -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
97
src/billing/plans.py
Normal 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
126
src/billing/routes.py
Normal 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',
|
||||
)
|
||||
139
src/billing/stripe_client.py
Normal file
139
src/billing/stripe_client.py
Normal 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},
|
||||
)
|
||||
47
templates/billing/cancel.html
Normal file
47
templates/billing/cancel.html
Normal file
@@ -0,0 +1,47 @@
|
||||
{% extends 'marketing/base.html' %}
|
||||
|
||||
{% block title %}{{ title or 'Paiement annulé — DictIA' }}{% endblock %}
|
||||
{% block description %}Paiement annulé. Aucun montant n'a été prélevé. Vous pouvez reprendre votre inscription à tout moment.{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{# ===== HERO ===== #}
|
||||
<section class="bg-brand-navy text-white py-20" aria-labelledby="page-title">
|
||||
<div class="max-w-[820px] mx-auto px-6 text-center">
|
||||
<div class="w-20 h-20 bg-white/[0.06] border border-white/[0.12] rounded-full mx-auto mb-6 flex items-center justify-center text-3xl" aria-hidden="true">↺</div>
|
||||
<p class="eyebrow grad-text mb-4">PAIEMENT ANNULÉ</p>
|
||||
<h1 id="page-title" class="text-[clamp(2.25rem,4vw,3.5rem)] font-black mb-4">
|
||||
Aucun problème — <span class="grad-text">aucun montant prélevé</span>.
|
||||
</h1>
|
||||
<p class="text-lg text-white/80">
|
||||
Vous avez fermé la page de paiement avant de finaliser. Aucune carte n'a été débitée. Vous pouvez reprendre votre inscription à tout moment.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{# ===== INFO + NEXT STEPS ===== #}
|
||||
<section class="bg-brand-bg py-20" aria-labelledby="info-title">
|
||||
<div class="max-w-[820px] mx-auto px-6">
|
||||
<h2 id="info-title" class="sr-only">Que faire ensuite</h2>
|
||||
|
||||
<div class="bg-white p-8 rounded-[18px] border border-brand-border mb-8">
|
||||
<h3 class="text-lg font-bold mb-3 text-brand-navy">Pourquoi avoir hésité ?</h3>
|
||||
<p class="text-sm text-brand-navy/80 leading-relaxed mb-4">
|
||||
Si vous avez une question sur les forfaits, la conformité Loi 25 ou la mise en service, notre équipe peut vous accompagner sans pression commerciale.
|
||||
</p>
|
||||
<p class="text-sm text-brand-navy/80 leading-relaxed">
|
||||
Écrivez-nous à <a href="mailto:info@dictia.ca" class="grad-text font-semibold hover:underline">info@dictia.ca</a> ou appelez le <a href="tel:+15819968471" class="grad-text font-semibold hover:underline">(581) 996-8471</a>. Réponse sous 2 jours ouvrables.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="text-center">
|
||||
<div class="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
{% from 'macros/button.html' import button %}
|
||||
{{ button('Revoir les tarifs', href='/tarifs', variant='primary', size='lg') }}
|
||||
{{ button('Retour à l\'accueil', href='/', variant='ghost', size='lg') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% endblock %}
|
||||
87
templates/billing/success.html
Normal file
87
templates/billing/success.html
Normal file
@@ -0,0 +1,87 @@
|
||||
{% extends 'marketing/base.html' %}
|
||||
|
||||
{% block title %}{{ title or 'Paiement confirmé — DictIA' }}{% endblock %}
|
||||
{% block description %}Paiement confirmé. Votre abonnement DictIA sera activé sous quelques minutes. Vous recevrez un courriel de confirmation.{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
{# ===== HERO ===== #}
|
||||
<section class="bg-brand-navy text-white py-20" aria-labelledby="page-title">
|
||||
<div class="max-w-[820px] mx-auto px-6 text-center">
|
||||
<div class="w-20 h-20 grad-bg rounded-full mx-auto mb-6 flex items-center justify-center text-4xl shadow-cta" aria-hidden="true">✓</div>
|
||||
<p class="eyebrow grad-text mb-4">PAIEMENT CONFIRMÉ</p>
|
||||
<h1 id="page-title" class="text-[clamp(2.25rem,4vw,3.5rem)] font-black mb-4">
|
||||
Merci ! Votre <span class="grad-text">paiement est confirmé</span>.
|
||||
</h1>
|
||||
<p class="text-lg text-white/80">
|
||||
Votre abonnement sera activé sous quelques minutes. Vous recevrez un courriel de confirmation à l'adresse associée à votre compte.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{# ===== NEXT STEPS ===== #}
|
||||
<section class="bg-brand-bg py-20" aria-labelledby="next-steps-title">
|
||||
<div class="max-w-[820px] mx-auto px-6">
|
||||
<h2 id="next-steps-title" class="text-[clamp(1.75rem,2.5vw,2.25rem)] font-black mb-8 text-brand-navy text-center">
|
||||
Prochaines étapes.
|
||||
</h2>
|
||||
|
||||
<ol class="space-y-6">
|
||||
<li class="bg-white p-6 rounded-[18px] border border-brand-border flex gap-4">
|
||||
<span class="grad-bg text-white font-black w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 shadow-cta" aria-hidden="true">1</span>
|
||||
<div>
|
||||
<h3 class="font-bold text-brand-navy mb-1">Confirmation par courriel</h3>
|
||||
<p class="text-sm text-brand-navy/80 leading-relaxed">
|
||||
Vous recevrez un reçu détaillé (avec TPS et TVQ ventilées) dans les prochaines minutes. Vérifiez vos pourriels si rien n'arrive après 10 minutes.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<li class="bg-white p-6 rounded-[18px] border border-brand-border flex gap-4">
|
||||
<span class="grad-bg text-white font-black w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 shadow-cta" aria-hidden="true">2</span>
|
||||
<div>
|
||||
<h3 class="font-bold text-brand-navy mb-1">Activation de votre abonnement</h3>
|
||||
<p class="text-sm text-brand-navy/80 leading-relaxed">
|
||||
Votre statut d'abonnement sera mis à jour automatiquement dès que Stripe confirme la transaction (généralement sous 2 minutes). Aucune action requise de votre part.
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<li class="bg-white p-6 rounded-[18px] border border-brand-border flex gap-4">
|
||||
<span class="grad-bg text-white font-black w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 shadow-cta" aria-hidden="true">3</span>
|
||||
<div>
|
||||
<h3 class="font-bold text-brand-navy mb-1">Mise en service</h3>
|
||||
<p class="text-sm text-brand-navy/80 leading-relaxed">
|
||||
Pour les forfaits <strong>DictIA Cloud</strong> : accès immédiat depuis votre tableau de bord.<br>
|
||||
Pour les forfaits <strong>DictIA 8</strong> et <strong>DictIA 16</strong> (on-premise) : notre équipe vous contactera sous 1 jour ouvrable pour planifier l'installation (~2 semaines).
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
{% if session_id %}
|
||||
<p class="text-xs text-brand-navy/60 mt-8 text-center font-mono break-all">
|
||||
Référence : {{ session_id }}
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{# ===== CTA ===== #}
|
||||
<section class="bg-white py-16" aria-labelledby="cta-title">
|
||||
<div class="max-w-[820px] mx-auto px-6 text-center">
|
||||
<h2 id="cta-title" class="text-[clamp(1.5rem,2vw,2rem)] font-black mb-4 text-brand-navy">
|
||||
Une question ?
|
||||
</h2>
|
||||
<p class="text-base text-brand-navy/80 mb-6">
|
||||
Notre équipe est joignable à <a href="mailto:info@dictia.ca" class="grad-text font-semibold hover:underline">info@dictia.ca</a> ou au <a href="tel:+15819968471" class="grad-text font-semibold hover:underline">(581) 996-8471</a>.
|
||||
</p>
|
||||
<div class="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
{% from 'macros/button.html' import button %}
|
||||
{{ button('Retour à l\'accueil', href='/', variant='ghost', size='lg') }}
|
||||
{{ button('Voir les tarifs', href='/tarifs', variant='secondary', size='lg') }}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% endblock %}
|
||||
74
tests/_run_stripe_checkout_windows.py
Normal file
74
tests/_run_stripe_checkout_windows.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""Windows manual driver for tests/test_stripe_checkout.py.
|
||||
|
||||
src/init_db.py imports `fcntl`, which is POSIX-only. On Windows we stub it
|
||||
before src.app gets imported, then run each test_* function and report.
|
||||
|
||||
Run from the repo root:
|
||||
py -3 tests/_run_stripe_checkout_windows.py
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
import traceback
|
||||
|
||||
# 1) Stub fcntl BEFORE any import of src.* happens.
|
||||
if 'fcntl' not in sys.modules:
|
||||
fcntl_stub = types.ModuleType('fcntl')
|
||||
fcntl_stub.LOCK_EX = 2
|
||||
fcntl_stub.LOCK_NB = 4
|
||||
fcntl_stub.LOCK_UN = 8
|
||||
fcntl_stub.LOCK_SH = 1
|
||||
fcntl_stub.flock = lambda *_args, **_kw: None
|
||||
fcntl_stub.fcntl = lambda *_args, **_kw: 0
|
||||
sys.modules['fcntl'] = fcntl_stub
|
||||
|
||||
# 2) Make repo root importable
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO = os.path.dirname(HERE)
|
||||
sys.path.insert(0, REPO)
|
||||
|
||||
# 3) Test-friendly env defaults
|
||||
os.environ.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
|
||||
os.environ.setdefault('SECRET_KEY', 'test-secret-key-stripe')
|
||||
os.environ.setdefault('ENABLE_EMAIL_VERIFICATION', 'false')
|
||||
os.environ.setdefault('REQUIRE_EMAIL_VERIFICATION', 'false')
|
||||
os.environ.setdefault('TRANSCRIPTION_BASE_URL', 'http://test-stub')
|
||||
os.environ.setdefault('TRANSCRIPTION_API_KEY', 'test-stub')
|
||||
os.environ.setdefault('RATELIMIT_ENABLED', 'false')
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 4) Import the test module and run every test_* function
|
||||
import importlib.util # noqa: E402
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'test_stripe_checkout',
|
||||
os.path.join(HERE, 'test_stripe_checkout.py'),
|
||||
)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
tests = [(name, fn) for name, fn in vars(mod).items()
|
||||
if name.startswith('test_') and callable(fn)]
|
||||
|
||||
passed = 0
|
||||
failed = []
|
||||
for name, fn in tests:
|
||||
try:
|
||||
fn()
|
||||
print(f' PASS {name}')
|
||||
passed += 1
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f' FAIL {name}: {type(e).__name__}: {e}')
|
||||
failed.append((name, traceback.format_exc()))
|
||||
|
||||
total = len(tests)
|
||||
print()
|
||||
print(f'Result: {passed}/{total} passed, {len(failed)} failed')
|
||||
if failed:
|
||||
print('\n--- Failures ---\n')
|
||||
for name, tb in failed:
|
||||
print(f'### {name}\n{tb}\n')
|
||||
sys.exit(0 if not failed else 1)
|
||||
593
tests/test_stripe_checkout.py
Normal file
593
tests/test_stripe_checkout.py
Normal file
@@ -0,0 +1,593 @@
|
||||
"""Tests for B-2.7 — Stripe Checkout (3 plans CAD + TPS/TVQ + Apple/Google Pay).
|
||||
|
||||
Covers:
|
||||
- plans.py: Plan dataclass, env-resolved Price IDs, helpers, is_configured.
|
||||
- stripe_client.py: lazy api_key init, get_or_create_customer, create_checkout_session.
|
||||
- routes.py: GET /checkout/<plan>, /checkout/success, /checkout/cancel.
|
||||
- Integration: app.py _PUBLIC_INDEXABLE_ENDPOINTS includes 'billing.success'.
|
||||
|
||||
Mocks the stripe library functions (stripe.Customer.create, stripe.checkout.Session.create)
|
||||
via unittest.mock.patch — no real Stripe API calls.
|
||||
|
||||
Note: pytest cannot collect this file on Windows native because src/init_db.py
|
||||
imports `fcntl` (POSIX-only). Use tests/_run_stripe_checkout_windows.py.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
os.environ.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
|
||||
os.environ.setdefault('SECRET_KEY', 'test-secret-key-stripe')
|
||||
os.environ.setdefault('ENABLE_EMAIL_VERIFICATION', 'false')
|
||||
os.environ.setdefault('REQUIRE_EMAIL_VERIFICATION', 'false')
|
||||
os.environ.setdefault('RATELIMIT_ENABLED', 'false')
|
||||
|
||||
from src.app import app, db, bcrypt # noqa: E402
|
||||
from src.models.user import User # noqa: E402
|
||||
|
||||
|
||||
_PRICE_ENV_VARS = (
|
||||
'STRIPE_SECRET_KEY',
|
||||
'STRIPE_DICTIA_8_SETUP', 'STRIPE_DICTIA_8_MONTHLY', 'STRIPE_DICTIA_8_YEARLY',
|
||||
'STRIPE_DICTIA_16_SETUP', 'STRIPE_DICTIA_16_MONTHLY', 'STRIPE_DICTIA_16_YEARLY',
|
||||
'STRIPE_DICTIA_CLOUD_MONTHLY', 'STRIPE_DICTIA_CLOUD_YEARLY',
|
||||
)
|
||||
|
||||
|
||||
def _clear_stripe_env():
|
||||
for k in _PRICE_ENV_VARS:
|
||||
os.environ.pop(k, None)
|
||||
# Reset stripe module-level api_key state
|
||||
import stripe
|
||||
stripe.api_key = None
|
||||
|
||||
|
||||
def _disable_csrf():
|
||||
app.config['WTF_CSRF_ENABLED'] = False
|
||||
|
||||
|
||||
def _make_user(email='checkout@example.qc.ca', password='Password!123',
|
||||
username=None, name='Checkout User',
|
||||
stripe_customer_id=None):
|
||||
hashed = bcrypt.generate_password_hash(password).decode('utf-8')
|
||||
u = User(
|
||||
username=username or email.split('@', 1)[0][:20],
|
||||
email=email,
|
||||
password=hashed,
|
||||
email_verified=True,
|
||||
name=name,
|
||||
stripe_customer_id=stripe_customer_id,
|
||||
)
|
||||
db.session.add(u)
|
||||
db.session.commit()
|
||||
return u
|
||||
|
||||
|
||||
def _login_session(client, user):
|
||||
with client.session_transaction() as sess:
|
||||
sess['_user_id'] = str(user.id)
|
||||
sess['_fresh'] = True
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1-2. is_stripe_configured
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_is_stripe_configured_when_env_set():
|
||||
_clear_stripe_env()
|
||||
try:
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
from src.billing.stripe_client import is_stripe_configured
|
||||
assert is_stripe_configured() is True
|
||||
finally:
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_is_stripe_configured_when_env_unset():
|
||||
_clear_stripe_env()
|
||||
try:
|
||||
from src.billing.stripe_client import is_stripe_configured
|
||||
assert is_stripe_configured() is False
|
||||
finally:
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3-4. get_plan
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_get_plan_returns_known_plan():
|
||||
from src.billing.plans import get_plan, Plan
|
||||
plan = get_plan('dictia-cloud')
|
||||
assert plan is not None
|
||||
assert isinstance(plan, Plan)
|
||||
assert plan.slug == 'dictia-cloud'
|
||||
assert plan.has_setup_fee is False
|
||||
|
||||
|
||||
def test_get_plan_returns_none_for_unknown():
|
||||
from src.billing.plans import get_plan
|
||||
assert get_plan('foo') is None
|
||||
assert get_plan('') is None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 5-7. Plan.is_configured
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_plan_is_configured_when_env_set():
|
||||
_clear_stripe_env()
|
||||
try:
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cloud_m'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cloud_y'
|
||||
from src.billing.plans import get_plan
|
||||
assert get_plan('dictia-cloud').is_configured() is True
|
||||
finally:
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_plan_is_not_configured_when_env_missing():
|
||||
_clear_stripe_env()
|
||||
try:
|
||||
from src.billing.plans import get_plan
|
||||
assert get_plan('dictia-cloud').is_configured() is False
|
||||
finally:
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_hardware_plan_requires_setup_env():
|
||||
_clear_stripe_env()
|
||||
try:
|
||||
os.environ['STRIPE_DICTIA_8_MONTHLY'] = 'price_8_m'
|
||||
os.environ['STRIPE_DICTIA_8_YEARLY'] = 'price_8_y'
|
||||
# NO STRIPE_DICTIA_8_SETUP
|
||||
from src.billing.plans import get_plan
|
||||
assert get_plan('dictia-8').is_configured() is False
|
||||
os.environ['STRIPE_DICTIA_8_SETUP'] = 'price_8_setup'
|
||||
assert get_plan('dictia-8').is_configured() is True
|
||||
finally:
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 8-9. get_or_create_customer
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_get_or_create_customer_creates_when_missing():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='newcust@example.qc.ca', name='Alice')
|
||||
assert user.stripe_customer_id is None
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust:
|
||||
mock_cust.return_value = MagicMock(id='cus_fakeNEW')
|
||||
from src.billing.stripe_client import get_or_create_customer
|
||||
cust_id = get_or_create_customer(user)
|
||||
assert cust_id == 'cus_fakeNEW'
|
||||
mock_cust.assert_called_once()
|
||||
kwargs = mock_cust.call_args.kwargs
|
||||
assert kwargs['email'] == 'newcust@example.qc.ca'
|
||||
assert kwargs['name'] == 'Alice'
|
||||
assert kwargs['metadata']['dictia_user_id'] == str(user.id)
|
||||
db.session.refresh(user)
|
||||
assert user.stripe_customer_id == 'cus_fakeNEW'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_get_or_create_customer_reuses_existing():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='oldcust@example.qc.ca',
|
||||
stripe_customer_id='cus_existing')
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust:
|
||||
from src.billing.stripe_client import get_or_create_customer
|
||||
cust_id = get_or_create_customer(user)
|
||||
assert cust_id == 'cus_existing'
|
||||
mock_cust.assert_not_called()
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 10-13. create_checkout_session
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_create_checkout_session_includes_setup_for_hardware_plan():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_8_SETUP'] = 'price_setup'
|
||||
os.environ['STRIPE_DICTIA_8_MONTHLY'] = 'price_8m'
|
||||
os.environ['STRIPE_DICTIA_8_YEARLY'] = 'price_8y'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='hwsetup@example.qc.ca', name='Bob')
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust, \
|
||||
patch('src.billing.stripe_client.stripe.checkout.Session.create') as mock_sess:
|
||||
mock_cust.return_value = MagicMock(id='cus_x')
|
||||
mock_sess.return_value = MagicMock(url='https://checkout.stripe.test/cs_x')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-8', period='monthly', user=user,
|
||||
success_url='https://x.ca/success', cancel_url='https://x.ca/cancel',
|
||||
)
|
||||
kwargs = mock_sess.call_args.kwargs
|
||||
assert len(kwargs['line_items']) == 2
|
||||
assert kwargs['line_items'][0]['price'] == 'price_setup'
|
||||
assert kwargs['line_items'][1]['price'] == 'price_8m'
|
||||
assert kwargs['mode'] == 'subscription'
|
||||
assert kwargs['currency'] == 'cad'
|
||||
assert kwargs['automatic_tax']['enabled'] is True
|
||||
assert kwargs['allow_promotion_codes'] is True
|
||||
assert kwargs['billing_address_collection'] == 'required'
|
||||
# success_url must include CHECKOUT_SESSION_ID placeholder
|
||||
assert '{CHECKOUT_SESSION_ID}' in kwargs['success_url']
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_no_setup_for_cloud_plan():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='cloudplan@example.qc.ca', name='Carol')
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust, \
|
||||
patch('src.billing.stripe_client.stripe.checkout.Session.create') as mock_sess:
|
||||
mock_cust.return_value = MagicMock(id='cus_y')
|
||||
mock_sess.return_value = MagicMock(url='https://x/cs_y')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='monthly', user=user,
|
||||
success_url='https://x.ca/success', cancel_url='https://x.ca/cancel',
|
||||
)
|
||||
kwargs = mock_sess.call_args.kwargs
|
||||
assert len(kwargs['line_items']) == 1
|
||||
assert kwargs['line_items'][0]['price'] == 'price_cm'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_uses_yearly_price_when_period_yearly():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='yearly@example.qc.ca', name='Dan')
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust, \
|
||||
patch('src.billing.stripe_client.stripe.checkout.Session.create') as mock_sess:
|
||||
mock_cust.return_value = MagicMock(id='cus_z')
|
||||
mock_sess.return_value = MagicMock(url='https://x/cs_z')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='yearly', user=user,
|
||||
success_url='https://x.ca/success', cancel_url='https://x.ca/cancel',
|
||||
)
|
||||
kwargs = mock_sess.call_args.kwargs
|
||||
assert kwargs['line_items'][0]['price'] == 'price_cy'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_includes_metadata():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='meta@example.qc.ca', name='Eve')
|
||||
with patch('src.billing.stripe_client.stripe.Customer.create') as mock_cust, \
|
||||
patch('src.billing.stripe_client.stripe.checkout.Session.create') as mock_sess:
|
||||
mock_cust.return_value = MagicMock(id='cus_q')
|
||||
mock_sess.return_value = MagicMock(url='https://x/cs_q')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='monthly', user=user,
|
||||
success_url='https://x.ca/success', cancel_url='https://x.ca/cancel',
|
||||
)
|
||||
kwargs = mock_sess.call_args.kwargs
|
||||
meta = kwargs['metadata']
|
||||
assert meta['dictia_user_id'] == str(user.id)
|
||||
assert meta['dictia_plan_slug'] == 'dictia-cloud'
|
||||
assert meta['dictia_period'] == 'monthly'
|
||||
# Subscription-level metadata too (used by webhook B-2.8)
|
||||
sub_meta = kwargs['subscription_data']['metadata']
|
||||
assert sub_meta['dictia_user_id'] == str(user.id)
|
||||
assert sub_meta['dictia_plan_slug'] == 'dictia-cloud'
|
||||
assert sub_meta['dictia_period'] == 'monthly'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 14-17. create_checkout_session error paths
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_create_checkout_session_raises_on_unknown_plan():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='unkplan@example.qc.ca')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
try:
|
||||
create_checkout_session(
|
||||
plan_slug='foo', period='monthly', user=user,
|
||||
success_url='https://x/s', cancel_url='https://x/c',
|
||||
)
|
||||
raise AssertionError('Expected ValueError')
|
||||
except ValueError:
|
||||
pass
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_raises_on_invalid_period():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='badperiod@example.qc.ca')
|
||||
from src.billing.stripe_client import create_checkout_session
|
||||
try:
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='quarterly', user=user,
|
||||
success_url='https://x/s', cancel_url='https://x/c',
|
||||
)
|
||||
raise AssertionError('Expected ValueError')
|
||||
except ValueError:
|
||||
pass
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_raises_when_stripe_not_configured():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
# NO STRIPE_SECRET_KEY
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='nokey@example.qc.ca')
|
||||
from src.billing.stripe_client import (
|
||||
create_checkout_session, StripeNotConfiguredError,
|
||||
)
|
||||
try:
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='monthly', user=user,
|
||||
success_url='https://x/s', cancel_url='https://x/c',
|
||||
)
|
||||
raise AssertionError('Expected StripeNotConfiguredError')
|
||||
except StripeNotConfiguredError:
|
||||
pass
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_create_checkout_session_raises_when_plan_env_missing():
|
||||
with app.app_context():
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
# NO price IDs for dictia-cloud
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='noprice@example.qc.ca')
|
||||
from src.billing.stripe_client import (
|
||||
create_checkout_session, StripeNotConfiguredError,
|
||||
)
|
||||
try:
|
||||
create_checkout_session(
|
||||
plan_slug='dictia-cloud', period='monthly', user=user,
|
||||
success_url='https://x/s', cancel_url='https://x/c',
|
||||
)
|
||||
raise AssertionError('Expected StripeNotConfiguredError')
|
||||
except StripeNotConfiguredError:
|
||||
pass
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 18-22. /checkout/<plan> route
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_checkout_route_redirects_to_stripe_url():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='rt-redir@example.qc.ca', name='Frank')
|
||||
with app.test_client() as client:
|
||||
_login_session(client, user)
|
||||
with patch('src.billing.routes.create_checkout_session') as mock_create:
|
||||
mock_create.return_value = MagicMock(
|
||||
url='https://checkout.stripe.test/cs_redir'
|
||||
)
|
||||
resp = client.get('/checkout/dictia-cloud?period=monthly',
|
||||
follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
assert resp.headers['Location'] == 'https://checkout.stripe.test/cs_redir'
|
||||
# Ensure routes called the helper with the right args
|
||||
mock_create.assert_called_once()
|
||||
call_kwargs = mock_create.call_args.kwargs
|
||||
assert call_kwargs['plan_slug'] == 'dictia-cloud'
|
||||
assert call_kwargs['period'] == 'monthly'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_checkout_route_unknown_plan_redirects_to_tarifs():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='rt-unk@example.qc.ca')
|
||||
with app.test_client() as client:
|
||||
_login_session(client, user)
|
||||
resp = client.get('/checkout/foo', follow_redirects=False)
|
||||
assert resp.status_code == 302
|
||||
assert '/tarifs' in resp.headers['Location']
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_checkout_route_normalizes_invalid_period_to_monthly():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
_clear_stripe_env()
|
||||
os.environ['STRIPE_SECRET_KEY'] = 'sk_test_fake'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_MONTHLY'] = 'price_cm'
|
||||
os.environ['STRIPE_DICTIA_CLOUD_YEARLY'] = 'price_cy'
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='rt-period@example.qc.ca')
|
||||
with app.test_client() as client:
|
||||
_login_session(client, user)
|
||||
with patch('src.billing.routes.create_checkout_session') as mock_create:
|
||||
mock_create.return_value = MagicMock(
|
||||
url='https://checkout.stripe.test/cs_norm'
|
||||
)
|
||||
resp = client.get('/checkout/dictia-cloud?period=quarterly',
|
||||
follow_redirects=False)
|
||||
assert resp.status_code == 303
|
||||
assert mock_create.call_args.kwargs['period'] == 'monthly'
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_checkout_route_requires_login():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
_clear_stripe_env()
|
||||
db.create_all()
|
||||
try:
|
||||
with app.test_client() as client:
|
||||
resp = client.get('/checkout/dictia-cloud',
|
||||
follow_redirects=False)
|
||||
assert resp.status_code == 302
|
||||
assert '/login' in resp.headers['Location']
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
def test_checkout_route_friendly_message_when_stripe_not_configured():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
_clear_stripe_env()
|
||||
# NO STRIPE_SECRET_KEY
|
||||
db.create_all()
|
||||
try:
|
||||
user = _make_user(email='rt-noconfig@example.qc.ca')
|
||||
with app.test_client() as client:
|
||||
_login_session(client, user)
|
||||
resp = client.get('/checkout/dictia-cloud',
|
||||
follow_redirects=False)
|
||||
assert resp.status_code == 302
|
||||
assert '/tarifs' in resp.headers['Location']
|
||||
# Follow the redirect to see the flashed message
|
||||
resp2 = client.get('/tarifs')
|
||||
body = resp2.get_data(as_text=True)
|
||||
assert 'info@dictia.ca' in body
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
_clear_stripe_env()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 23-24. /checkout/success and /checkout/cancel
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_success_route_renders_template():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
db.create_all()
|
||||
try:
|
||||
with app.test_client() as client:
|
||||
resp = client.get('/checkout/success?session_id=cs_test_abc')
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_data(as_text=True)
|
||||
# Body should mention the async-activation note (per spec)
|
||||
assert 'minutes' in body.lower() or 'activé' in body.lower() \
|
||||
or 'activée' in body.lower() or 'confirmé' in body.lower()
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
|
||||
|
||||
def test_cancel_route_renders_template():
|
||||
with app.app_context():
|
||||
_disable_csrf()
|
||||
db.create_all()
|
||||
try:
|
||||
with app.test_client() as client:
|
||||
resp = client.get('/checkout/cancel')
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_data(as_text=True)
|
||||
# "no charge made" reassurance in French
|
||||
assert 'aucun' in body.lower() or 'annulé' in body.lower()
|
||||
finally:
|
||||
db.session.rollback()
|
||||
db.drop_all()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 25. Integration with no-crawl headers
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
def test_success_route_in_public_indexable_endpoints():
|
||||
"""Defensive: 'billing.success' was added to _PUBLIC_INDEXABLE_ENDPOINTS in B-1.3."""
|
||||
from src.app import _PUBLIC_INDEXABLE_ENDPOINTS
|
||||
assert 'billing.success' in _PUBLIC_INDEXABLE_ENDPOINTS
|
||||
Reference in New Issue
Block a user