Stripe SDK Node.js: integrazione base

Stripe SDK Node.js: integrazione base

L'SDK Node.js di Stripe (stripe-node) è il pacchetto npm ufficiale per integrare Stripe in applicazioni JavaScript/TypeScript lato server. Supporta Promise nativo, async/await e fornisce tipi TypeScript completi out-of-the-box.

Installazione e setup

Installa con 'npm install stripe' o 'yarn add stripe'. Inizializza l'istanza con const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) o, in TypeScript, import Stripe from 'stripe'; const stripe = new Stripe(key, { apiVersion: '2024-04-10' }). La libreria offre tipi TypeScript ottimi che riducono drasticamente errori comuni.

Express e webhook

In Express devi gestire il body raw per la verifica firma webhook: usa express.raw({ type: 'application/json' }) sull'endpoint webhook prima di express.json(). La verifica avviene con stripe.webhooks.constructEvent(req.body, sig, secret). Per il resto del server puoi usare express.json() normalmente.

TypeScript types e versione API

L'SDK Node.js include types ufficiali allineati alla versione API dichiarata. Quando inizializzi con new Stripe(key, { apiVersion: '2024-04-10' }), TypeScript verifica i types contro quella versione specifica. Upgradare apiVersion richiede review breaking change in docs e refactor codice. Per refactor sicuro, abilita 'strict' in tsconfig.json e usa types come Stripe.PaymentIntent, Stripe.Customer, Stripe.Event ovunque. L'autocompletion IDE su parametri opzionali risparmia ore di lookup documentazione.

Server frameworks: Express, Fastify, NestJS

Express è il più' diffuso: usa express.raw({ type: 'application/json' }) sul path webhook prima di express.json(). Fastify richiede l'analogo fastify.addContentTypeParser('application/json', { parseAs: 'buffer' }, ...) per il path webhook. NestJS espone l'opzione 'rawBody: true' in NestFactory.create() e accede via @Req() req: RawBodyRequest. Per Next.js API routes, configura bodyParser: false nella route webhook e usa stream-to-buffer. Errore tipico: dimenticare la config raw body specifica per webhook produce signature verification failure.

Stripe Connect in Node.js: marketplace pattern

Per costruire marketplace in Node.js, pattern tipico: 1) Onboarding seller via Account Links (Express); 2) Storage account_id in DB collegato a user record; 3) Per ogni transazione, PaymentIntent con transfer_data.destination=account_id; 4) Webhook account.updated per tracking status; 5) Dashboard per seller con account_id-scoped queries. Library helper come stripe-node + custom abstraction layer (es. classes Marketplace, Seller, Transaction) per pulire codice business logic. Test integration con account stripe test marked as Connect.

Performance Node.js e clustering

Per high-throughput (1k+ webhook/sec), Node.js può diventare bottleneck single-threaded: 1) Cluster mode (cluster module o PM2) per parallelizzare su CPU core; 2) Webhook handler minimal: parse + verify + enqueue, no business logic inline; 3) Worker queue (BullMQ, Bee-Queue su Redis) per async processing; 4) Connection pooling per database (pg-pool, mongoose connection); 5) HTTP/2 con keepalive verso api.stripe.com. Stripe SDK accetta opzione 'maxNetworkRetries' e 'httpClient' per fine-tuning. Benchmark con autocannon prima/dopo ottimizzazione per misurare miglioramenti.

Serverless e edge deployment

Stripe + Node.js si presta a deployment serverless (AWS Lambda, Vercel, Cloudflare Workers): 1) Cold start mitigation - import minimo, Stripe SDK pesa 1-2MB; 2) Edge deployment per webhook handler globale - reduces latency cliente; 3) Stateless function - state in DB/Redis, non in memory; 4) Cost optimization - pay per invocation vs sempre-on server. Limitazioni serverless: timeout (15 min Lambda, 30s Vercel default), no long-running task (use queue). Per business mission-critical valuta combo serverless (low traffic endpoint) + container (high throughput): Stripe SDK funziona identicamente in entrambi.

Deno e Bun: nuove runtime JavaScript

Stripe Node.js SDK è compatibile anche con runtime JavaScript moderne: 1) Deno - require import via esm.sh o npm specifier; 2) Bun - npm install standard, performance superiore Node; 3) Cloudflare Workers - usa Stripe SDK lite o stripe-deno fork; 4) Vercel Edge Functions - subset SDK funzionante. Trend: edge-native checkout endpoint per latency globale. Limitazioni: alcune feature SDK (fs read certificati custom, http agent personalizzato) potrebbero non funzionare su edge runtime. Per nuovi progetti greenfield, Bun + Stripe è combo molto performante. Per legacy production, Node LTS resta scelta sicura.

Procedura passo-passo

  1. Inizializza progetto Node con 'npm init -y' se nuovo.
  2. Installa stripe e dotenv: 'npm install stripe dotenv'.
  3. Crea .env con STRIPE_SECRET_KEY e STRIPE_WEBHOOK_SECRET.
  4. In server.js: require('dotenv').config(); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY).
  5. Crea endpoint POST /create-payment-intent che restituisce client_secret.
  6. Crea endpoint POST /webhook con express.raw e verifica firma.
  7. Gestisci eventi switch(event.type) per payment_intent.succeeded e altri.
  8. Testa con Stripe CLI: stripe listen --forward-to localhost:3000/webhook.

Errori comuni e come risolverli

  • Body parsed prima del webhook: express.json() prima di express.raw rompe la firma; ordine matters.
  • Versione API non pinned: comportamento incoerente fra ambienti; specifica apiVersion.
  • Promise non awaitate: errori unhandled rejection; usa sempre await o .catch.
  • Secret key client-side: non importare l'SDK in frontend; usa Stripe.js (pk_).

Domande frequenti

D: L'SDK supporta TypeScript?
R: Sì, tipi ufficiali inclusi nel pacchetto da v8+.

D: Posso usarlo con NestJS/Next.js?
R: Sì, integrazione standard; in Next.js usa API routes server-side.

D: L'SDK fa retry automatico?
R: Sì, su network error e 5xx, configurabile con maxNetworkRetries.

D: Quale Node version serve?
R: Node.js 12+ supportato; consigliato 18+ LTS.

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?