@forestadmin-experimental/datasource-stripe
v1.0.0
Published
Forest Admin DataSource for Stripe - Connect your Stripe account to Forest Admin
Readme
@forestadmin-experimental/datasource-stripe
Forest Admin DataSource for Stripe - Connect your Stripe account to Forest Admin.
Features
- Full Stripe Integration: Access all major Stripe resources as Forest Admin collections
- Real-time Data: Data is fetched directly from Stripe API
- CRUD Operations: Create, read, update, and delete operations where supported by Stripe
- Type Mapping: Automatic mapping of Stripe types to Forest Admin field types
- Filtering: Support for common filter operations on Stripe data
- Resource Selection: Include or exclude specific Stripe resources
- Retry Mechanism: Built-in retry with exponential backoff for rate limiting
- TypeScript: Full TypeScript support with type definitions
Architecture
datasource-stripe/
├── src/
│ ├── collections/ # Individual collection implementations
│ │ ├── balance-transactions.ts
│ │ ├── charges.ts
│ │ ├── customers.ts
│ │ ├── index.ts
│ │ ├── invoices.ts
│ │ ├── payment-intents.ts
│ │ ├── prices.ts
│ │ ├── products.ts
│ │ ├── refunds.ts
│ │ └── subscriptions.ts
│ ├── types/ # TypeScript type definitions
│ │ ├── config.ts
│ │ ├── index.ts
│ │ └── stripe.ts
│ ├── utils/ # Utility functions
│ │ ├── constants.ts
│ │ ├── index.ts
│ │ ├── retry-handler.ts
│ │ ├── serializer.ts
│ │ └── type-converter.ts
│ ├── collection.ts # Base collection class
│ ├── datasource.ts # Main datasource class
│ └── index.ts # Public API exports
├── test/ # Unit tests
└── package.jsonSupported Resources
| Resource | Collection Name | Create | Read | Update | Delete | |----------|----------------|--------|------|--------|--------| | Customers | Stripe Customers | ✅ | ✅ | ✅ | ✅ | | Products | Stripe Products | ✅ | ✅ | ✅ | ✅ | | Prices | Stripe Prices | ✅ | ✅ | ✅ | Archive | | Subscriptions | Stripe Subscriptions | ✅ | ✅ | ✅ | Cancel | | Invoices | Stripe Invoices | ✅ | ✅ | ✅ | Void/Delete | | Payment Intents | Stripe Payment Intents | ✅ | ✅ | ✅ | Cancel | | Charges | Stripe Charges | ❌ | ✅ | ⚠️ | ❌ | | Refunds | Stripe Refunds | ✅ | ✅ | ✅ | Cancel | | Balance Transactions | Stripe Balance Transactions | ❌ | ✅ | ❌ | ❌ |
Note: Some resources have limited operations based on Stripe API constraints.
Installation
npm install @forestadmin-experimental/datasource-stripe stripeQuick Start
Basic Usage
import { createAgent } from '@forestadmin/agent';
import { createStripeDataSource } from '@forestadmin-experimental/datasource-stripe';
const agent = createAgent({
authSecret: process.env.FOREST_AUTH_SECRET,
envSecret: process.env.FOREST_ENV_SECRET,
isProduction: process.env.NODE_ENV === 'production',
});
// Add Stripe datasource (reads STRIPE_SECRET_KEY from environment)
agent.addDataSource(createStripeDataSource());
agent.mountOnStandaloneServer(3000);
agent.start();With Configuration
agent.addDataSource(createStripeDataSource({
// Stripe Secret Key (optional if STRIPE_SECRET_KEY env var is set)
secretKey: 'sk_test_xxxxx',
// Stripe API version (optional)
apiVersion: '2023-10-16',
// Only include specific resources (optional)
includeResources: ['customers', 'subscriptions', 'invoices'],
// Exclude specific resources (optional)
excludeResources: ['balance_transactions'],
// Retry options for rate limiting (optional)
retryOptions: {
maxRetries: 5,
initialDelayMs: 1000,
maxDelayMs: 30000,
backoffMultiplier: 2,
},
}));Configuration Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| secretKey | string | process.env.STRIPE_SECRET_KEY | Stripe Secret API Key |
| apiVersion | string | '2023-10-16' | Stripe API version |
| includeResources | string[] | null (all) | Only include these resources |
| excludeResources | string[] | [] | Exclude these resources |
| retryOptions | RetryOptions | See below | Retry configuration |
Retry Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| maxRetries | number | 3 | Maximum number of retry attempts |
| initialDelayMs | number | 1000 | Initial delay before first retry (ms) |
| maxDelayMs | number | 30000 | Maximum delay between retries (ms) |
| backoffMultiplier | number | 2 | Multiplier for exponential backoff |
Environment Variables
# Required: Stripe Secret Key
STRIPE_SECRET_KEY=sk_test_xxxxx
# Forest Admin configuration
FOREST_AUTH_SECRET=xxxxx
FOREST_ENV_SECRET=xxxxxResource Details
Customers
Manage your Stripe customers. Full CRUD support.
Key Fields:
id- Customer IDemail- Email addressname- Customer namephone- Phone numberbalance- Account balance (read-only)metadata- Custom metadata
Products
Manage your product catalog.
Key Fields:
id- Product IDname- Product namedescription- Product descriptionactive- Whether product is activedefault_price- Default price IDimages- Product images
Prices
Manage pricing for your products.
Key Fields:
id- Price IDproduct- Associated product IDunit_amount- Price in centscurrency- Currency coderecurring- Recurring pricing detailstype-one_timeorrecurring
Subscriptions
Manage customer subscriptions.
Key Fields:
id- Subscription IDcustomer- Customer IDstatus- Subscription statuscurrent_period_start- Current period start datecurrent_period_end- Current period end dateitems- Subscription items
Invoices
Manage invoices.
Key Fields:
id- Invoice IDcustomer- Customer IDstatus- Invoice statusamount_due- Amount due in centsamount_paid- Amount paid in centshosted_invoice_url- Hosted invoice URLinvoice_pdf- PDF download URL
Payment Intents
Manage payment intents.
Key Fields:
id- Payment Intent IDamount- Amount in centscurrency- Currency codestatus- Payment statuscustomer- Customer IDpayment_method- Payment method ID
Charges
View charge history (mostly read-only).
Key Fields:
id- Charge IDamount- Amount in centsstatus- Charge statuspaid- Whether charge was paidrefunded- Whether charge was refundedreceipt_url- Receipt URL
Refunds
Manage refunds.
Key Fields:
id- Refund IDamount- Refund amount in centscharge- Original charge IDstatus- Refund statusreason- Refund reason
Balance Transactions
View balance transaction history (read-only).
Key Fields:
id- Transaction IDamount- Amount in centsnet- Net amount after feesfee- Stripe feetype- Transaction typeavailable_on- When funds become available
Filtering Support
The datasource supports filtering on common fields:
- Email filtering: Filter customers by email
- Status filtering: Filter by status on subscriptions, invoices, payment intents
- Customer filtering: Filter resources by customer ID
- Date filtering: Filter by created date with operators (gt, gte, lt, lte)
- Active filtering: Filter products by active status
Currency Handling
Stripe uses cents for currency amounts. The datasource provides utility functions:
import { formatCurrencyAmount, toCurrencyAmount } from '@forestadmin-experimental/datasource-stripe';
// Convert from cents to decimal
formatCurrencyAmount(1000, 'usd'); // Returns 10.00
// Convert from decimal to cents
toCurrencyAmount(10.00, 'usd'); // Returns 1000
// Zero-decimal currencies (JPY, KRW, etc.) are handled automatically
formatCurrencyAmount(1000, 'jpy'); // Returns 1000Customization
Adding Custom Actions
agent.customizeCollection('Stripe Customers', collection => {
collection.addAction('Send Welcome Email', {
scope: 'Single',
execute: async (context, resultBuilder) => {
const customer = await context.getRecord(['id', 'email', 'name']);
// Send email logic here
return resultBuilder.success(`Email sent to ${customer.email}`);
}
});
});Adding Computed Fields
agent.customizeCollection('Stripe Invoices', collection => {
collection.addField('amount_due_formatted', {
columnType: 'String',
dependencies: ['amount_due', 'currency'],
getValues: (records) => records.map(r =>
`${(r.amount_due / 100).toFixed(2)} ${r.currency.toUpperCase()}`
),
});
});Error Handling
The datasource handles Stripe API errors and provides meaningful error messages. Common errors:
- Authentication Error: Invalid or missing API key
- Resource Missing: Record not found
- Invalid Request: Invalid parameters or operation
- Rate Limit Error: Too many requests (automatically retried)
Rate Limiting
The datasource includes built-in retry logic for rate limit errors (HTTP 429). By default:
- Up to 3 retries with exponential backoff
- Initial delay of 1 second, doubling with each retry
- Maximum delay capped at 30 seconds
Exported Utilities
import {
// Main exports
createStripeDataSource,
StripeDataSource,
StripeCollection,
// Collection classes
CustomersCollection,
ProductsCollection,
PricesCollection,
SubscriptionsCollection,
InvoicesCollection,
PaymentIntentsCollection,
ChargesCollection,
RefundsCollection,
BalanceTransactionsCollection,
// Types
StripeDataSourceOptions,
RetryOptions,
StripeResourceType,
StripeRecord,
// Utilities
withRetry,
formatCurrencyAmount,
toCurrencyAmount,
timestampToDate,
dateToTimestamp,
mapFieldType,
getFilterOperators,
// Constants
DEFAULT_PAGE_SIZE,
STRIPE_API_VERSION,
SUPPORTED_RESOURCES,
ZERO_DECIMAL_CURRENCIES,
} from '@forestadmin-experimental/datasource-stripe';Limitations
- Pagination: Stripe uses cursor-based pagination; page numbers are not supported
- Sorting: Limited sorting options based on Stripe API capabilities
- Complex Filters: Some advanced filtering may require client-side processing
- Rate Limits: Subject to Stripe API rate limits (automatic retry included)
License
GPL-3.0
Contributing
Contributions are welcome! Please read the contributing guidelines first.
