- Catalogue src/billing/plans.ts : prix mensuels/annuels (2 mois offerts), fonctions incluses et limites ; ancien prix 10 € = tarif fondateur - Formule enregistrée sur l'abonnement, déduite du prix Stripe (lookup_key) : un changement fait depuis le portail client est repris automatiquement - Lien d'abonnement au choix (formule, périodicité), essai 30 jours (une fois par magasin), codes promo ; e-mail de fin d'essai (trial_will_end) - Portail client Stripe (changer de formule, moyen de paiement, résilier) - EntitlementsService : droits par formule ; appliqué à la limite de 3 employés en Essentiel et au retrait de « Propulsé par » en Pro - Factures : libellé de la formule et de la périodicité - scripts/stripe-setup.ts idempotent (produits, prix, portail, webhook) - Admin : choix de la formule, badges, espace abonnement Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
5.7 KiB
TypeScript
139 lines
5.7 KiB
TypeScript
/**
|
|
* Prépare le compte Stripe pour les formules MonEspacePro. Idempotent :
|
|
* peut être relancé (test, puis production) sans créer de doublons.
|
|
*
|
|
* npx ts-node scripts/stripe-setup.ts
|
|
*
|
|
* - un produit par formule et ses prix mensuel / annuel (lookup_key du catalogue) ;
|
|
* - la configuration du portail client (changement de formule, résiliation…) ;
|
|
* - les événements du webhook (ajout de la fin d'essai).
|
|
* Affiche STRIPE_PORTAL_CONFIG_ID à recopier dans le .env.
|
|
*/
|
|
import Stripe from 'stripe';
|
|
import { PLANS } from '../src/billing/plans';
|
|
|
|
try {
|
|
process.loadEnvFile();
|
|
} catch {
|
|
/* variables déjà présentes */
|
|
}
|
|
|
|
const key = process.env.STRIPE_SECRET_KEY;
|
|
if (!key) throw new Error('STRIPE_SECRET_KEY manquante');
|
|
const stripe = new Stripe(key);
|
|
const mode = key.startsWith('sk_test_') ? 'TEST' : 'PRODUCTION';
|
|
|
|
const WEBHOOK_EVENTS: Stripe.WebhookEndpointCreateParams.EnabledEvent[] = [
|
|
'checkout.session.completed',
|
|
'customer.subscription.created',
|
|
'customer.subscription.updated',
|
|
'customer.subscription.deleted',
|
|
'customer.subscription.trial_will_end',
|
|
'invoice.paid',
|
|
'invoice.payment_failed',
|
|
];
|
|
|
|
async function main() {
|
|
console.log(`Stripe en mode ${mode}\n`);
|
|
const portalProducts: Stripe.BillingPortal.ConfigurationCreateParams.Features.SubscriptionUpdate.Product[] = [];
|
|
|
|
// Pas de products.search : son index n'est pas immédiat et ferait créer des doublons.
|
|
const allProducts = await stripe.products.list({ active: true, limit: 100 });
|
|
|
|
for (const def of Object.values(PLANS)) {
|
|
// Produit : celui d'un prix existant de la formule, sinon par sa métadonnée, sinon création.
|
|
const knownPrice = (await stripe.prices.list({ lookup_keys: Object.values(def.lookupKey), limit: 1 })).data[0];
|
|
const product =
|
|
(knownPrice && (await stripe.products.retrieve(String(knownPrice.product)))) ??
|
|
allProducts.data.find((p) => p.metadata?.mep_plan === def.plan) ??
|
|
(await stripe.products.create({
|
|
name: `MonEspacePro ${def.name}`,
|
|
description: def.tagline,
|
|
metadata: { mep_plan: def.plan },
|
|
}));
|
|
const priceIds: string[] = [];
|
|
for (const interval of ['MONTH', 'YEAR'] as const) {
|
|
const lookupKey = def.lookupKey[interval];
|
|
let price = (await stripe.prices.list({ lookup_keys: [lookupKey], limit: 1 })).data[0];
|
|
if (price && price.unit_amount !== def.priceCents[interval]) {
|
|
// Le prix a changé dans le catalogue : nouveau prix, la clé lui est transférée.
|
|
price = await stripe.prices.create({
|
|
product: product.id,
|
|
currency: 'eur',
|
|
unit_amount: def.priceCents[interval],
|
|
recurring: { interval: interval === 'YEAR' ? 'year' : 'month' },
|
|
lookup_key: lookupKey,
|
|
transfer_lookup_key: true,
|
|
nickname: `${def.name} ${interval === 'YEAR' ? 'annuel' : 'mensuel'}`,
|
|
});
|
|
console.log(` prix mis à jour ${lookupKey} → ${price.id}`);
|
|
} else if (!price) {
|
|
price = await stripe.prices.create({
|
|
product: product.id,
|
|
currency: 'eur',
|
|
unit_amount: def.priceCents[interval],
|
|
recurring: { interval: interval === 'YEAR' ? 'year' : 'month' },
|
|
lookup_key: lookupKey,
|
|
nickname: `${def.name} ${interval === 'YEAR' ? 'annuel' : 'mensuel'}`,
|
|
});
|
|
console.log(` prix créé ${lookupKey} → ${price.id}`);
|
|
}
|
|
priceIds.push(price.id);
|
|
}
|
|
portalProducts.push({ product: product.id, prices: priceIds });
|
|
console.log(`✓ ${def.name} (${product.id})`);
|
|
}
|
|
|
|
// Portail client
|
|
const portalParams: Stripe.BillingPortal.ConfigurationCreateParams = {
|
|
business_profile: {
|
|
headline: 'MonEspacePro — gérez votre abonnement',
|
|
privacy_policy_url: 'https://monespacepro.eu/confidentialite/',
|
|
terms_of_service_url: 'https://monespacepro.eu/cgv/',
|
|
},
|
|
default_return_url: 'https://monespacepro.eu/',
|
|
features: {
|
|
customer_update: { enabled: true, allowed_updates: ['email', 'address', 'phone', 'name'] },
|
|
invoice_history: { enabled: true },
|
|
payment_method_update: { enabled: true },
|
|
subscription_cancel: {
|
|
enabled: true,
|
|
mode: 'at_period_end',
|
|
cancellation_reason: {
|
|
enabled: true,
|
|
options: ['too_expensive', 'unused', 'missing_features', 'switched_service', 'other'],
|
|
},
|
|
},
|
|
subscription_update: {
|
|
enabled: true,
|
|
default_allowed_updates: ['price'],
|
|
proration_behavior: 'create_prorations',
|
|
products: portalProducts,
|
|
},
|
|
},
|
|
};
|
|
const configs = await stripe.billingPortal.configurations.list({ active: true, limit: 100 });
|
|
const ours = configs.data.find((c) => c.metadata?.mep === 'portal');
|
|
const portal = ours
|
|
? await stripe.billingPortal.configurations.update(ours.id, portalParams)
|
|
: await stripe.billingPortal.configurations.create({ ...portalParams, metadata: { mep: 'portal' } });
|
|
console.log(`✓ Portail client ${ours ? 'mis à jour' : 'créé'}`);
|
|
|
|
// Webhook
|
|
const url = 'https://api.monespacepro.eu/api/stripe/webhook';
|
|
const hook = (await stripe.webhookEndpoints.list({ limit: 100 })).data.find((w) => w.url === url);
|
|
if (hook) {
|
|
await stripe.webhookEndpoints.update(hook.id, { enabled_events: WEBHOOK_EVENTS });
|
|
console.log('✓ Webhook : événements à jour');
|
|
} else {
|
|
const created = await stripe.webhookEndpoints.create({ url, enabled_events: WEBHOOK_EVENTS, description: 'MonEspacePro API' });
|
|
console.log(`✓ Webhook créé — STRIPE_WEBHOOK_SECRET=${created.secret}`);
|
|
}
|
|
|
|
console.log(`\nÀ mettre dans le .env :\nSTRIPE_PORTAL_CONFIG_ID=${portal.id}`);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error('ERREUR', e.message);
|
|
process.exit(1);
|
|
});
|