Stripe SDK Python: integrazione base

Stripe SDK Python: integrazione base

L'SDK Python di Stripe (stripe-python) è il pacchetto pip ufficiale per integrare Stripe in applicazioni Python. Supporta Python 3.6+ ed è compatibile con Flask, Django, FastAPI e qualunque framework web Python.

Installazione e setup

Installa con 'pip install stripe'. Configura stripe.api_key = os.environ['STRIPE_SECRET_KEY'] in fase di bootstrap. La libreria è sincrona di default; per usi async con FastAPI o aiohttp considera l'uso di asyncio.to_thread() o il package stripe-async di terze parti. Tutti gli oggetti restituiti supportano accesso a dict-like e attributo.

Flask/Django e webhook

In Flask: usa request.get_data() per ottenere il body raw e stripe.Webhook.construct_event() per verificare la firma. In Django: usa request.body in una view CSRF-exempt. La gestione errori avviene con stripe.error.* exceptions (CardError, RateLimitError, InvalidRequestError, AuthenticationError, APIConnectionError, StripeError).

FastAPI e gestione asincrona

FastAPI usa asyncio nativo ma stripe-python è sincrono. Pattern consigliato: from fastapi import FastAPI; @app.post('/create-payment'); async def create_payment(): intent = await asyncio.to_thread(stripe.PaymentIntent.create, amount=2000, currency='eur'). In questo modo non blocchi l'event loop. Per webhook usa Request body raw via await request.body(). Le exception stripe.error.* si convertono in HTTPException con status appropriato (e.g. CardError -> 402 Payment Required). Logging strutturato con loguru o standard logging modulato per env.

Django Cashier e packages community

Django ha dj-stripe, package mature (5k+ star GitHub) che mappa tutti gli oggetti Stripe a model Django con sync bidirezionale. Permette di query subscription/customer/invoice come model Django (es. user.subscriptions.filter(status='active')). Include webhook handler generico, admin Django con dashboard, signal per ogni evento. Setup: pip install dj-stripe, aggiunge a INSTALLED_APPS, migra, esegue management command dj_stripe_init_customers per popolare model esistenti. Riduce drasticamente codice custom per progetti SaaS Django-based.

Stripe Python e Pandas analytics

Python eccelle in data analytics Stripe: combina stripe-python con pandas per analisi cohort/LTV/churn. Pattern: 1) Export charges via stripe.Charge.list(limit=100).auto_paging_iter() per iterazione full table; 2) Converti in DataFrame: pd.DataFrame([c.to_dict() for c in charges]); 3) Pandas magic: groupby cohort, pivot, rolling, plot con matplotlib/seaborn. Per dataset grandi (1M+ row) usa Sigma direttamente o data warehouse. Per analytics ad-hoc da Jupyter notebook, stripe-python + pandas è workflow estremamente produttivo.

Type hints e tooling Python moderni

stripe-python da v7 include type hints completi. Combinati con mypy/pyright in strict mode, catchi errori a compile time invece di runtime. Esempio: customer: stripe.Customer = stripe.Customer.retrieve('cus_123'); customer.invalid_field genera errore static. Tooling raccomandato: 1) Black/ruff per formatting; 2) mypy strict per type checking; 3) pytest per testing; 4) python-dotenv per env management; 5) loguru per logging strutturato; 6) httpx per chiamate parallel async (con asyncio + to_thread per stripe-python sync calls).

Pipeline ML e data science Python

Stripe data + Python = combinazione potente per ML/data science: 1) Churn prediction con sklearn/xgboost sui pattern subscription history; 2) Fraud detection custom layer su top di Radar con feature engineering specifico del business; 3) LTV prediction con survival analysis (lifelines library); 4) Pricing optimization con A/B test analysis e Bayesian inference. Pipeline tipica: 1) Extract via stripe-python o Sigma; 2) Transform in pandas/polars; 3) Train model con sklearn/pytorch; 4) Deploy via Flask/FastAPI API; 5) Inference call da webhook handler real-time. Container Docker per ogni step, orchestration via Airflow/Prefect. Investment 1-3 mesi per data team ma ROI elevato in retention/conversion.

Stripe e data engineering Python

Python è linguaggio dominante in data engineering. Combinato con Stripe ecosystem permette pipeline ETL/ELT robuste: 1) Source - stripe-python o Sigma per export; 2) Orchestration - Airflow, Dagster, Prefect; 3) Storage - Snowflake, BigQuery, Postgres data warehouse; 4) Transformation - dbt, Polars, Pandas; 5) Visualization - Looker, Tableau, Metabase. Stripe expose dati via API + Webhooks + Sigma. Per real-time analytics, webhook -> Kafka -> ClickHouse pattern è winning. Stripe non offre native CDC (Change Data Capture) ma via webhook + Sigma puoi build CDC custom. Aziende Stripe-customer data-driven hanno team dedicato 'Stripe Analyst' per maintainance pipeline.

Procedura passo-passo

  1. Crea virtualenv e installa: 'pip install stripe python-dotenv'.
  2. Crea .env con STRIPE_SECRET_KEY e STRIPE_WEBHOOK_SECRET.
  3. In settings.py o app.py: stripe.api_key = os.environ['STRIPE_SECRET_KEY'].
  4. Implementa view create_payment_intent che restituisce client_secret.
  5. Crea view webhook che usa stripe.Webhook.construct_event per verifica.
  6. In Django: @csrf_exempt sulla view webhook (la firma è già verifica sicura).
  7. Gestisci event.type con if/elif per payment_intent.succeeded e altri.
  8. Testa con Stripe CLI: stripe listen --forward-to localhost:8000/webhook.

Errori comuni e come risolverli

  • CSRF non disabilitato in Django: POST webhook fallisce; usa @csrf_exempt.
  • Body parsato male: Flask: usa request.get_data() non request.get_json() per webhook.
  • Errori stripe.error non gestiti: wrappa in try/except per logica retry.
  • Versione Python obsoleta: stripe-python >= 7 richiede Python 3.6+.

Domande frequenti

D: L'SDK supporta asyncio?
R: No nativamente; usa asyncio.to_thread() o stripe-async di terze parti.

D: Posso usarlo con FastAPI?
R: Sì, in modo sincrono o wrappato in to_thread per non bloccare loop.

D: Esistono type hints?
R: Sì, da stripe-python v7 sono inclusi type hints completi.

D: L'SDK fa retry automatico?
R: Sì, su network error con configurazione default modificabile.

Hai bisogno di aiuto?

Se vuoi integrare Stripe con il team di G Tech Group, scrivici tramite il modulo di contatto.

Hai trovato utile quest'articolo?