Package Exports
- stripe-replit-sync
Readme
Stripe Sync Engine
A TypeScript library to synchronize Stripe data into a PostgreSQL database, designed for use in Node.js backends and serverless environments.
Features
- Automatically manages Stripe webhooks for real-time updates
- Sync Stripe objects (customers, invoices, products, etc.) to your PostgreSQL database
- UUID-based webhook routing for managed webhooks
Installation
npm install stripe-replit-sync stripe
# or
pnpm add stripe-replit-sync stripe
# or
yarn add stripe-replit-sync stripeUsage
import { StripeSync } from 'stripe-replit-sync'
const sync = new StripeSync({
poolConfig: {
connectionString: 'postgres://user:pass@host:port/db',
max: 10, // Maximum number of connections
},
stripeSecretKey: 'sk_test_...',
stripeWebhookSecret: 'whsec_...',
// logger: <a pino logger>
})
// Example: process a Stripe webhook
await sync.processWebhook(payload, signature)Low-Level API (Advanced)
For more control, you can use the StripeSync class directly:
import { StripeSync } from 'stripe-experiment-sync'
const sync = new StripeSync({
poolConfig: {
connectionString: 'postgres://user:pass@host:port/db',
max: 10, // Maximum number of connections
},
stripeSecretKey: 'sk_test_...',
stripeWebhookSecret: 'whsec_...',
// logger: <a pino logger>
})
// Example: process a Stripe webhook
await sync.processWebhook(payload, signature)Processing Webhooks
The processWebhook method supports both standard and managed webhook approaches:
// For managed webhooks (with UUID-based routing):
await sync.processWebhook(payload, signature, uuid)
// For standard webhooks (requires stripeWebhookSecret in config):
await sync.processWebhook(payload, signature)
// Or process an event directly (no signature validation):
await sync.processEvent(event)Managed Webhook Endpoints
The library provides methods to create and manage webhook endpoints with UUID-based routing for security:
// Create or reuse an existing webhook endpoint for a base URL
const { webhook, uuid } = await sync.findOrCreateManagedWebhook(
'https://example.com/stripe-webhooks',
{
enabled_events: ['*'], // or specific events like ['customer.created', 'invoice.paid']
description: 'My app webhook',
}
)
// webhook.url will be: https://example.com/stripe-webhooks/{uuid}
// Create a new webhook endpoint (always creates new)
const { webhook, uuid } = await sync.createManagedWebhook('https://example.com/stripe-webhooks', {
enabled_events: ['customer.created', 'customer.updated'],
})
// Get a managed webhook by ID
const webhook = await sync.getManagedWebhook('we_xxx')
// Delete a managed webhook
await sync.deleteManagedWebhook('we_xxx')The UUID-based routing allows multiple webhook endpoints for the same base URL, making it ideal for:
- Development environments with ngrok/tunnels that change URLs
- Multi-tenant applications
- Testing and staging environments
Configuration
| Option | Type | Description |
|---|---|---|
databaseUrl |
string | Deprecated: Use poolConfig with a connection string instead. |
schema |
string | Database schema name (default: stripe) |
stripeSecretKey |
string | Stripe secret key |
stripeWebhookSecret |
string | Stripe webhook signing secret |
stripeApiVersion |
string | Stripe API version (default: 2020-08-27) |
autoExpandLists |
boolean | Fetch all list items from Stripe (not just the default 10) |
backfillRelatedEntities |
boolean | Ensure related entities are present for foreign key integrity |
revalidateObjectsViaStripeApi |
Array | Always fetch latest entity from Stripe instead of trusting webhook payload, possible values: charge, credit_note, customer, dispute, invoice, payment_intent, payment_method, plan, price, product, refund, review, radar.early_fraud_warning, setup_intent, subscription, subscription_schedule, tax_id |
poolConfig |
object | Configuration for PostgreSQL connection pooling. Supports options like connectionString, max, and keepAlive. For more details, refer to the Node-Postgres Pool API documentation. |
maxPostgresConnections |
number | Deprecated: Use poolConfig.max instead to configure the maximum number of PostgreSQL connections. |
logger |
Logger | Logger instance (pino) |
Database Schema
The library will create and manage a stripe schema in your PostgreSQL database, with tables for all supported Stripe objects (products, customers, invoices, etc.).
Migrations
Migrations are included in the db/migrations directory. You can run them using the provided runMigrations function:
import { runMigrations } from 'stripe-replit-sync'
await runMigrations({ databaseUrl: 'postgres://...' })Backfilling and Syncing Data
Syncing a Single Entity
You can sync or update a single Stripe entity by its ID using the syncSingleEntity method:
await sync.syncSingleEntity('cus_12345')The entity type is detected automatically based on the Stripe ID prefix (e.g., cus_ for customer, prod_ for product). ent_ is not supported at the moment.
Backfilling Data
To backfill Stripe data (e.g., all products created after a certain date), use the syncBackfill method:
await sync.syncBackfill({
object: 'product',
created: { gte: 1643872333 }, // Unix timestamp
})objectcan be one of:all,charge,customer,dispute,invoice,payment_method,payment_intent,plan,price,product,setup_intent,subscription.createdis a Stripe RangeQueryParam and supportsgt,gte,lt,lte.
Note: For large Stripe accounts (more than 10,000 objects), it is recommended to write a script that loops through each day and sets the
createddate filters to the start and end of day. This avoids timeouts and memory issues when syncing large datasets.