mirror of
https://github.com/xtr-dev/payload-billing.git
synced 2025-12-10 10:53:23 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2907d0fa9d |
283
README.md
283
README.md
@@ -6,23 +6,6 @@ A billing and payment provider plugin for PayloadCMS 3.x. Supports Stripe, Molli
|
||||
|
||||
⚠️ **Pre-release Warning**: This package is currently in active development (v0.1.x). Breaking changes may occur before v1.0.0. Not recommended for production use.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Installation](#installation)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Imports](#imports)
|
||||
- [Usage Examples](#usage-examples)
|
||||
- [Creating a Payment](#creating-a-payment)
|
||||
- [Creating an Invoice](#creating-an-invoice)
|
||||
- [Creating a Refund](#creating-a-refund)
|
||||
- [Querying Payments](#querying-payments)
|
||||
- [Using REST API](#using-rest-api)
|
||||
- [Provider Types](#provider-types)
|
||||
- [Collections](#collections)
|
||||
- [Webhook Endpoints](#webhook-endpoints)
|
||||
- [Development](#development)
|
||||
|
||||
## Features
|
||||
|
||||
- 💳 Multiple payment providers (Stripe, Mollie, Test)
|
||||
@@ -207,272 +190,6 @@ The plugin supports flexible customer data handling:
|
||||
|
||||
3. **No Customer Collection**: Customer info fields always required and editable, no relationship field available
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Creating a Payment
|
||||
|
||||
Payments are created through PayloadCMS's local API or REST API. The plugin automatically initializes the payment with the configured provider.
|
||||
|
||||
```typescript
|
||||
// Using Payload Local API
|
||||
const payment = await payload.create({
|
||||
collection: 'payments',
|
||||
data: {
|
||||
provider: 'stripe', // or 'mollie' or 'test'
|
||||
amount: 2000, // Amount in cents ($20.00)
|
||||
currency: 'USD',
|
||||
description: 'Product purchase',
|
||||
status: 'pending',
|
||||
metadata: {
|
||||
orderId: 'order-123',
|
||||
customerId: 'cust-456'
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Creating an Invoice
|
||||
|
||||
Invoices can be created with customer information embedded or linked via relationship:
|
||||
|
||||
```typescript
|
||||
// Create invoice with embedded customer info
|
||||
const invoice = await payload.create({
|
||||
collection: 'invoices',
|
||||
data: {
|
||||
customerInfo: {
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
phone: '+1234567890',
|
||||
company: 'Acme Corp',
|
||||
taxId: 'TAX-123'
|
||||
},
|
||||
billingAddress: {
|
||||
line1: '123 Main St',
|
||||
line2: 'Suite 100',
|
||||
city: 'New York',
|
||||
state: 'NY',
|
||||
postalCode: '10001',
|
||||
country: 'US'
|
||||
},
|
||||
currency: 'USD',
|
||||
items: [
|
||||
{
|
||||
description: 'Web Development Services',
|
||||
quantity: 10,
|
||||
unitAmount: 5000 // $50.00 per hour
|
||||
},
|
||||
{
|
||||
description: 'Hosting (Monthly)',
|
||||
quantity: 1,
|
||||
unitAmount: 2500 // $25.00
|
||||
}
|
||||
],
|
||||
taxAmount: 7500, // $75.00 tax
|
||||
status: 'open'
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`Invoice created: ${invoice.number}`)
|
||||
console.log(`Total amount: $${invoice.amount / 100}`)
|
||||
```
|
||||
|
||||
### Creating an Invoice with Customer Relationship
|
||||
|
||||
If you've configured a customer collection with `customerRelationSlug` and `customerInfoExtractor`:
|
||||
|
||||
```typescript
|
||||
// Create invoice linked to customer (info auto-populated)
|
||||
const invoice = await payload.create({
|
||||
collection: 'invoices',
|
||||
data: {
|
||||
customer: 'customer-id-123', // Customer relationship
|
||||
currency: 'USD',
|
||||
items: [
|
||||
{
|
||||
description: 'Subscription - Pro Plan',
|
||||
quantity: 1,
|
||||
unitAmount: 9900 // $99.00
|
||||
}
|
||||
],
|
||||
status: 'open'
|
||||
// customerInfo and billingAddress are auto-populated from customer
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Creating a Refund
|
||||
|
||||
Refunds are linked to existing payments:
|
||||
|
||||
```typescript
|
||||
const refund = await payload.create({
|
||||
collection: 'refunds',
|
||||
data: {
|
||||
payment: payment.id, // Link to payment
|
||||
providerId: 'refund-provider-id', // Provider's refund ID
|
||||
amount: 1000, // Partial refund: $10.00
|
||||
currency: 'USD',
|
||||
status: 'succeeded',
|
||||
reason: 'requested_by_customer',
|
||||
description: 'Customer requested partial refund'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Querying Payments
|
||||
|
||||
```typescript
|
||||
// Find all successful payments
|
||||
const payments = await payload.find({
|
||||
collection: 'payments',
|
||||
where: {
|
||||
status: {
|
||||
equals: 'succeeded'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Find payments for a specific invoice
|
||||
const invoicePayments = await payload.find({
|
||||
collection: 'payments',
|
||||
where: {
|
||||
invoice: {
|
||||
equals: invoiceId
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Updating Payment Status
|
||||
|
||||
Payment status is typically updated via webhooks, but you can also update manually:
|
||||
|
||||
```typescript
|
||||
const updatedPayment = await payload.update({
|
||||
collection: 'payments',
|
||||
id: payment.id,
|
||||
data: {
|
||||
status: 'succeeded',
|
||||
providerData: {
|
||||
// Provider-specific data
|
||||
raw: providerResponse,
|
||||
timestamp: new Date().toISOString(),
|
||||
provider: 'stripe'
|
||||
}
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Marking an Invoice as Paid
|
||||
|
||||
```typescript
|
||||
const paidInvoice = await payload.update({
|
||||
collection: 'invoices',
|
||||
id: invoice.id,
|
||||
data: {
|
||||
status: 'paid',
|
||||
payment: payment.id // Link to payment
|
||||
// paidAt is automatically set by the plugin
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Using the Test Provider
|
||||
|
||||
The test provider is useful for local development:
|
||||
|
||||
```typescript
|
||||
// In your payload.config.ts
|
||||
import { billingPlugin, testProvider } from '@xtr-dev/payload-billing'
|
||||
|
||||
billingPlugin({
|
||||
providers: [
|
||||
testProvider({
|
||||
enabled: true,
|
||||
testModeIndicators: {
|
||||
showWarningBanners: true,
|
||||
showTestBadges: true,
|
||||
consoleWarnings: true
|
||||
}
|
||||
})
|
||||
],
|
||||
collections: {
|
||||
payments: 'payments',
|
||||
invoices: 'invoices',
|
||||
refunds: 'refunds',
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Then create test payments:
|
||||
|
||||
```typescript
|
||||
const testPayment = await payload.create({
|
||||
collection: 'payments',
|
||||
data: {
|
||||
provider: 'test',
|
||||
amount: 5000,
|
||||
currency: 'USD',
|
||||
description: 'Test payment',
|
||||
status: 'pending'
|
||||
}
|
||||
})
|
||||
// Test provider automatically processes the payment
|
||||
```
|
||||
|
||||
### Using REST API
|
||||
|
||||
All collections can be accessed via PayloadCMS REST API:
|
||||
|
||||
```bash
|
||||
# Create a payment
|
||||
curl -X POST http://localhost:3000/api/payments \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \
|
||||
-d '{
|
||||
"provider": "stripe",
|
||||
"amount": 2000,
|
||||
"currency": "USD",
|
||||
"description": "Product purchase",
|
||||
"status": "pending"
|
||||
}'
|
||||
|
||||
# Create an invoice
|
||||
curl -X POST http://localhost:3000/api/invoices \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer YOUR_TOKEN" \
|
||||
-d '{
|
||||
"customerInfo": {
|
||||
"name": "John Doe",
|
||||
"email": "john@example.com"
|
||||
},
|
||||
"billingAddress": {
|
||||
"line1": "123 Main St",
|
||||
"city": "New York",
|
||||
"postalCode": "10001",
|
||||
"country": "US"
|
||||
},
|
||||
"currency": "USD",
|
||||
"items": [
|
||||
{
|
||||
"description": "Service",
|
||||
"quantity": 1,
|
||||
"unitAmount": 5000
|
||||
}
|
||||
],
|
||||
"status": "open"
|
||||
}'
|
||||
|
||||
# Get all payments
|
||||
curl http://localhost:3000/api/payments \
|
||||
-H "Authorization: Bearer YOUR_TOKEN"
|
||||
|
||||
# Get a specific invoice
|
||||
curl http://localhost:3000/api/invoices/INVOICE_ID \
|
||||
-H "Authorization: Bearer YOUR_TOKEN"
|
||||
```
|
||||
|
||||
## Webhook Endpoints
|
||||
|
||||
Automatic webhook endpoints are created for configured providers:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xtr-dev/payload-billing",
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.9",
|
||||
"description": "PayloadCMS plugin for billing and payment provider integrations with tracking and local testing",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -5,11 +5,10 @@ import {
|
||||
CollectionBeforeValidateHook,
|
||||
CollectionConfig, Field,
|
||||
} from 'payload'
|
||||
import type { BillingPluginConfig} from '@/plugin/config';
|
||||
import { defaults } from '@/plugin/config'
|
||||
import { extractSlug } from '@/plugin/utils'
|
||||
import { createContextLogger } from '@/utils/logger'
|
||||
import type { Invoice } from '@/plugin/types'
|
||||
import type { BillingPluginConfig} from '../plugin/config';
|
||||
import { defaults } from '../plugin/config'
|
||||
import { extractSlug } from '../plugin/utils'
|
||||
import type { Invoice } from '../plugin/types/invoices'
|
||||
|
||||
export function createInvoicesCollection(pluginConfig: BillingPluginConfig): CollectionConfig {
|
||||
const {customerRelationSlug, customerInfoExtractor} = pluginConfig
|
||||
@@ -315,8 +314,7 @@ export function createInvoicesCollection(pluginConfig: BillingPluginConfig): Col
|
||||
afterChange: [
|
||||
({ doc, operation, req }) => {
|
||||
if (operation === 'create') {
|
||||
const logger = createContextLogger(req.payload, 'Invoices Collection')
|
||||
logger.info(`Invoice created: ${doc.number}`)
|
||||
req.payload.logger.info(`Invoice created: ${doc.number}`)
|
||||
}
|
||||
},
|
||||
] satisfies CollectionAfterChangeHook<Invoice>[],
|
||||
@@ -352,8 +350,7 @@ export function createInvoicesCollection(pluginConfig: BillingPluginConfig): Col
|
||||
data.billingAddress = extractedInfo.billingAddress
|
||||
}
|
||||
} catch (error) {
|
||||
const logger = createContextLogger(req.payload, 'Invoices Collection')
|
||||
logger.error(`Failed to extract customer info: ${error}`)
|
||||
req.payload.logger.error(`Failed to extract customer info: ${error}`)
|
||||
throw new Error('Failed to extract customer information')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { AccessArgs, CollectionConfig } from 'payload'
|
||||
import { BillingPluginConfig, defaults } from '../plugin/config'
|
||||
import { extractSlug } from '../plugin/utils'
|
||||
import { Payment } from '../plugin/types/index'
|
||||
import { createContextLogger } from '../utils/logger'
|
||||
|
||||
export function createRefundsCollection(pluginConfig: BillingPluginConfig): CollectionConfig {
|
||||
// TODO: finish collection overrides
|
||||
@@ -112,8 +111,7 @@ export function createRefundsCollection(pluginConfig: BillingPluginConfig): Coll
|
||||
afterChange: [
|
||||
async ({ doc, operation, req }) => {
|
||||
if (operation === 'create') {
|
||||
const logger = createContextLogger(req.payload, 'Refunds Collection')
|
||||
logger.info(`Refund created: ${doc.id} for payment: ${doc.payment}`)
|
||||
req.payload.logger.info(`Refund created: ${doc.id} for payment: ${doc.payment}`)
|
||||
|
||||
// Update the related payment's refund relationship
|
||||
try {
|
||||
@@ -131,8 +129,7 @@ export function createRefundsCollection(pluginConfig: BillingPluginConfig): Coll
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
const logger = createContextLogger(req.payload, 'Refunds Collection')
|
||||
logger.error(`Failed to update payment refunds: ${error}`)
|
||||
req.payload.logger.error(`Failed to update payment refunds: ${error}`)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5,9 +5,6 @@ export type { BillingPluginConfig, CustomerInfoExtractor, AdvancedTestProviderCo
|
||||
export type { Invoice, Payment, Refund } from './plugin/types/index.js'
|
||||
export type { PaymentProvider, ProviderData } from './providers/types.js'
|
||||
|
||||
// Export logging utilities
|
||||
export { getPluginLogger, createContextLogger } from './utils/logger.js'
|
||||
|
||||
// Export all providers
|
||||
export { testProvider } from './providers/test.js'
|
||||
export type {
|
||||
|
||||
@@ -55,6 +55,6 @@ export interface BillingPluginConfig {
|
||||
customerInfoExtractor?: CustomerInfoExtractor // Callback to extract customer info from relationship
|
||||
customerRelationSlug?: string // Customer collection slug for relationship
|
||||
disabled?: boolean
|
||||
providers?: (PaymentProvider | undefined | null)[]
|
||||
providers?: PaymentProvider[]
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ export const billingPlugin = (pluginConfig: BillingPluginConfig = {}) => (config
|
||||
];
|
||||
|
||||
(pluginConfig.providers || [])
|
||||
.filter(provider => provider?.onConfig)
|
||||
.forEach(provider => provider?.onConfig!(config, pluginConfig))
|
||||
.filter(provider => provider.onConfig)
|
||||
.forEach(provider => provider.onConfig!(config, pluginConfig))
|
||||
|
||||
const incomingOnInit = config.onInit
|
||||
config.onInit = async (payload) => {
|
||||
@@ -38,17 +38,17 @@ export const billingPlugin = (pluginConfig: BillingPluginConfig = {}) => (config
|
||||
}
|
||||
singleton.set(payload, {
|
||||
config: pluginConfig,
|
||||
providerConfig: (pluginConfig.providers || []).filter(Boolean).reduce(
|
||||
providerConfig: (pluginConfig.providers || []).reduce(
|
||||
(record, provider) => {
|
||||
record[provider!.key] = provider as PaymentProvider
|
||||
record[provider.key] = provider
|
||||
return record
|
||||
},
|
||||
{} as Record<string, PaymentProvider>
|
||||
)
|
||||
} satisfies BillingPlugin)
|
||||
await Promise.all((pluginConfig.providers || [])
|
||||
.filter(provider => provider?.onInit)
|
||||
.map(provider => provider?.onInit!(payload)))
|
||||
.filter(provider => provider.onInit)
|
||||
.map(provider => provider.onInit!(payload)))
|
||||
}
|
||||
|
||||
return config
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
validateProductionUrl
|
||||
} from './utils'
|
||||
import { formatAmountForProvider, isValidAmount, isValidCurrencyCode } from './currency'
|
||||
import { createContextLogger } from '../utils/logger'
|
||||
|
||||
const symbol = Symbol('mollie')
|
||||
export type MollieProviderConfig = Parameters<typeof createMollieClient>[0]
|
||||
@@ -97,13 +96,12 @@ export const mollieProvider = (mollieConfig: MollieProviderConfig & {
|
||||
if (status === 'succeeded' && updateSuccess) {
|
||||
await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig)
|
||||
} else if (!updateSuccess) {
|
||||
const logger = createContextLogger(payload, 'Mollie Webhook')
|
||||
logger.warn(`Failed to update payment ${payment.id}, skipping invoice update`)
|
||||
console.warn(`[Mollie Webhook] Failed to update payment ${payment.id}, skipping invoice update`)
|
||||
}
|
||||
|
||||
return webhookResponses.success()
|
||||
} catch (error) {
|
||||
return handleWebhookError('Mollie', error, undefined, req.payload)
|
||||
return handleWebhookError('Mollie', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
logWebhookEvent
|
||||
} from './utils'
|
||||
import { isValidAmount, isValidCurrencyCode } from './currency'
|
||||
import { createContextLogger } from '../utils/logger'
|
||||
|
||||
const symbol = Symbol('stripe')
|
||||
|
||||
@@ -61,13 +60,13 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
return webhookResponses.missingBody()
|
||||
}
|
||||
} catch (error) {
|
||||
return handleWebhookError('Stripe', error, 'Failed to read request body', req.payload)
|
||||
return handleWebhookError('Stripe', error, 'Failed to read request body')
|
||||
}
|
||||
|
||||
const signature = req.headers.get('stripe-signature')
|
||||
|
||||
if (!signature) {
|
||||
return webhookResponses.error('Missing webhook signature', 400, req.payload)
|
||||
return webhookResponses.error('Missing webhook signature', 400)
|
||||
}
|
||||
|
||||
// webhookSecret is guaranteed to exist since we only register this endpoint when it's configured
|
||||
@@ -77,7 +76,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(body, signature, stripeConfig.webhookSecret!)
|
||||
} catch (err) {
|
||||
return handleWebhookError('Stripe', err, 'Signature verification failed', req.payload)
|
||||
return handleWebhookError('Stripe', err, 'Signature verification failed')
|
||||
}
|
||||
|
||||
// Handle different event types
|
||||
@@ -91,7 +90,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
const payment = await findPaymentByProviderId(payload, paymentIntent.id, pluginConfig)
|
||||
|
||||
if (!payment) {
|
||||
logWebhookEvent('Stripe', `Payment not found for intent: ${paymentIntent.id}`, undefined, req.payload)
|
||||
logWebhookEvent('Stripe', `Payment not found for intent: ${paymentIntent.id}`)
|
||||
return webhookResponses.success() // Still return 200 to acknowledge receipt
|
||||
}
|
||||
|
||||
@@ -130,8 +129,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
if (status === 'succeeded' && updateSuccess) {
|
||||
await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig)
|
||||
} else if (!updateSuccess) {
|
||||
const logger = createContextLogger(payload, 'Stripe Webhook')
|
||||
logger.warn(`Failed to update payment ${payment.id}, skipping invoice update`)
|
||||
console.warn(`[Stripe Webhook] Failed to update payment ${payment.id}, skipping invoice update`)
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -174,8 +172,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
)
|
||||
|
||||
if (!updateSuccess) {
|
||||
const logger = createContextLogger(payload, 'Stripe Webhook')
|
||||
logger.warn(`Failed to update refund status for payment ${payment.id}`)
|
||||
console.warn(`[Stripe Webhook] Failed to update refund status for payment ${payment.id}`)
|
||||
}
|
||||
}
|
||||
break
|
||||
@@ -183,16 +180,19 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
|
||||
default:
|
||||
// Unhandled event type
|
||||
logWebhookEvent('Stripe', `Unhandled event type: ${event.type}`, undefined, req.payload)
|
||||
logWebhookEvent('Stripe', `Unhandled event type: ${event.type}`)
|
||||
}
|
||||
|
||||
return webhookResponses.success()
|
||||
} catch (error) {
|
||||
return handleWebhookError('Stripe', error, undefined, req.payload)
|
||||
return handleWebhookError('Stripe', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
} else {
|
||||
// Log that webhook endpoint is not registered
|
||||
console.warn('[Stripe Provider] Webhook endpoint not registered - webhookSecret not configured')
|
||||
}
|
||||
},
|
||||
onInit: async (payload: Payload) => {
|
||||
@@ -201,12 +201,6 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
|
||||
apiVersion: stripeConfig.apiVersion || DEFAULT_API_VERSION,
|
||||
})
|
||||
singleton.set(payload, stripe)
|
||||
|
||||
// Log webhook registration status
|
||||
if (!stripeConfig.webhookSecret) {
|
||||
const logger = createContextLogger(payload, 'Stripe Provider')
|
||||
logger.warn('Webhook endpoint not registered - webhookSecret not configured')
|
||||
}
|
||||
},
|
||||
initPayment: async (payload, payment) => {
|
||||
// Validate required fields
|
||||
|
||||
@@ -4,12 +4,6 @@ import type { BillingPluginConfig } from '../plugin/config'
|
||||
import type { Payload } from 'payload'
|
||||
import { handleWebhookError, logWebhookEvent } from './utils'
|
||||
import { isValidAmount, isValidCurrencyCode } from './currency'
|
||||
import { createContextLogger } from '../utils/logger'
|
||||
|
||||
const TestModeWarningSymbol = Symbol('TestModeWarning')
|
||||
const hasGivenTestModeWarning = () => TestModeWarningSymbol in globalThis
|
||||
const setTestModeWarning = () => ((<any>globalThis)[TestModeWarningSymbol] = true)
|
||||
|
||||
|
||||
// Request validation schemas
|
||||
interface ProcessPaymentRequest {
|
||||
@@ -103,8 +97,7 @@ async function updatePaymentInDatabase(
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown database error'
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.error('Database update failed:', errorMessage)
|
||||
console.error('[Test Provider] Database update failed:', errorMessage)
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}
|
||||
@@ -224,14 +217,17 @@ const testPaymentSessions = new Map<string, TestPaymentSession>()
|
||||
|
||||
export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
if (!testConfig.enabled) {
|
||||
return
|
||||
throw new Error('Test provider is disabled')
|
||||
}
|
||||
|
||||
const scenarios = testConfig.scenarios || DEFAULT_SCENARIOS
|
||||
const baseUrl = testConfig.baseUrl || (process.env.PAYLOAD_PUBLIC_SERVER_URL || 'http://localhost:3000')
|
||||
const uiRoute = testConfig.customUiRoute || '/test-payment'
|
||||
|
||||
// Test mode warnings will be logged in onInit when payload is available
|
||||
// Log test mode warnings if enabled
|
||||
if (testConfig.testModeIndicators?.consoleWarnings !== false) {
|
||||
console.warn('🧪 [TEST PROVIDER] Payment system is running in test mode')
|
||||
}
|
||||
|
||||
return {
|
||||
key: 'test',
|
||||
@@ -242,7 +238,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
{
|
||||
path: '/payload-billing/test/payment/:id',
|
||||
method: 'get',
|
||||
handler: (req) => {
|
||||
handler: async (req) => {
|
||||
// Extract payment ID from URL path
|
||||
const urlParts = req.url?.split('/') || []
|
||||
const paymentId = urlParts[urlParts.length - 1]
|
||||
@@ -346,8 +342,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
// Process payment after delay
|
||||
setTimeout(() => {
|
||||
processTestPayment(payload, session, pluginConfig).catch(async (error) => {
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.error('Failed to process payment:', error)
|
||||
console.error('[Test Provider] Failed to process payment:', error)
|
||||
|
||||
// Ensure session status is updated consistently
|
||||
session.status = 'failed'
|
||||
@@ -373,11 +368,10 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
)
|
||||
|
||||
if (!dbResult.success) {
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.error('Database error during failure handling:', dbResult.error)
|
||||
console.error('[Test Provider] Database error during failure handling:', dbResult.error)
|
||||
// Even if database update fails, we maintain session consistency
|
||||
} else {
|
||||
logWebhookEvent('Test Provider', `Payment ${session.id} marked as failed after processing error`, undefined, req.payload)
|
||||
logWebhookEvent('Test Provider', `Payment ${session.id} marked as failed after processing error`)
|
||||
}
|
||||
})
|
||||
}, scenario.delay || testConfig.defaultDelay || 1000)
|
||||
@@ -391,7 +385,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
} catch (error) {
|
||||
return handleWebhookError('Test Provider', error, 'Failed to process test payment', req.payload)
|
||||
return handleWebhookError('Test Provider', error, 'Failed to process test payment')
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -439,14 +433,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
]
|
||||
},
|
||||
onInit: (payload: Payload) => {
|
||||
logWebhookEvent('Test Provider', 'Test payment provider initialized', undefined, payload)
|
||||
|
||||
// Log test mode warnings if enabled
|
||||
if (testConfig.testModeIndicators?.consoleWarnings !== false && !hasGivenTestModeWarning()) {
|
||||
setTestModeWarning()
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.warn('🧪 Payment system is running in test mode')
|
||||
}
|
||||
logWebhookEvent('Test Provider', 'Test payment provider initialized')
|
||||
|
||||
// Clean up old sessions periodically (older than 1 hour)
|
||||
setInterval(() => {
|
||||
@@ -458,7 +445,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
|
||||
})
|
||||
}, 10 * 60 * 1000) // Clean every 10 minutes
|
||||
},
|
||||
initPayment: (payload, payment) => {
|
||||
initPayment: async (payload, payment) => {
|
||||
// Validate required fields
|
||||
if (!payment.amount) {
|
||||
throw new Error('Amount is required')
|
||||
@@ -575,10 +562,9 @@ async function processTestPayment(
|
||||
)
|
||||
|
||||
if (dbResult.success) {
|
||||
logWebhookEvent('Test Provider', `Payment ${session.id} processed with outcome: ${session.scenario.outcome}`, undefined, payload)
|
||||
logWebhookEvent('Test Provider', `Payment ${session.id} processed with outcome: ${session.scenario.outcome}`)
|
||||
} else {
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.error('Failed to update payment in database:', dbResult.error)
|
||||
console.error('[Test Provider] Failed to update payment in database:', dbResult.error)
|
||||
// Update session status to indicate database error, but don't throw
|
||||
// This allows the UI to still show the intended test result
|
||||
session.status = 'failed'
|
||||
@@ -586,8 +572,7 @@ async function processTestPayment(
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown processing error'
|
||||
const logger = createContextLogger(payload, 'Test Provider')
|
||||
logger.error('Failed to process payment:', errorMessage)
|
||||
console.error('[Test Provider] Failed to process payment:', errorMessage)
|
||||
session.status = 'failed'
|
||||
throw error // Re-throw to be handled by the caller
|
||||
}
|
||||
@@ -928,12 +913,12 @@ function generateTestPaymentUI(
|
||||
setTimeout(() => pollStatus(), 2000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[Test Provider] Failed to poll status:', error);
|
||||
console.error('Failed to poll status:', error);
|
||||
}
|
||||
}
|
||||
|
||||
${testModeIndicators.consoleWarnings !== false ? `
|
||||
console.warn('[Test Provider] 🧪 TEST MODE: This is a simulated payment interface for development purposes');
|
||||
console.warn('🧪 TEST MODE: This is a simulated payment interface for development purposes');
|
||||
` : ''}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -4,7 +4,6 @@ import type { BillingPluginConfig } from '../plugin/config'
|
||||
import type { ProviderData } from './types'
|
||||
import { defaults } from '../plugin/config'
|
||||
import { extractSlug, toPayloadId } from '../plugin/utils'
|
||||
import { createContextLogger } from '../utils/logger'
|
||||
|
||||
/**
|
||||
* Common webhook response utilities
|
||||
@@ -12,14 +11,9 @@ import { createContextLogger } from '../utils/logger'
|
||||
*/
|
||||
export const webhookResponses = {
|
||||
success: () => Response.json({ received: true }, { status: 200 }),
|
||||
error: (message: string, status = 400, payload?: Payload) => {
|
||||
error: (message: string, status = 400) => {
|
||||
// Log error internally but don't expose details
|
||||
if (payload) {
|
||||
const logger = createContextLogger(payload, 'Webhook')
|
||||
logger.error('Error:', message)
|
||||
} else {
|
||||
console.error('[Webhook] Error:', message)
|
||||
}
|
||||
console.error('[Webhook] Error:', message)
|
||||
return Response.json({ error: 'Invalid request' }, { status })
|
||||
},
|
||||
missingBody: () => Response.json({ received: true }, { status: 200 }),
|
||||
@@ -69,8 +63,7 @@ export async function updatePaymentStatus(
|
||||
}) as Payment
|
||||
|
||||
if (!currentPayment) {
|
||||
const logger = createContextLogger(payload, 'Payment Update')
|
||||
logger.error(`Payment ${paymentId} not found`)
|
||||
console.error(`[Payment Update] Payment ${paymentId} not found`)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -81,8 +74,7 @@ export async function updatePaymentStatus(
|
||||
const transactionID = await payload.db.beginTransaction()
|
||||
|
||||
if (!transactionID) {
|
||||
const logger = createContextLogger(payload, 'Payment Update')
|
||||
logger.error('Failed to begin transaction')
|
||||
console.error(`[Payment Update] Failed to begin transaction`)
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -97,8 +89,7 @@ export async function updatePaymentStatus(
|
||||
// Check if version still matches
|
||||
if ((paymentInTransaction.version || 1) !== currentVersion) {
|
||||
// Version conflict detected - payment was modified by another process
|
||||
const logger = createContextLogger(payload, 'Payment Update')
|
||||
logger.warn(`Version conflict for payment ${paymentId} (expected version: ${currentVersion}, got: ${paymentInTransaction.version})`)
|
||||
console.warn(`[Payment Update] Version conflict for payment ${paymentId} (expected version: ${currentVersion}, got: ${paymentInTransaction.version})`)
|
||||
await payload.db.rollbackTransaction(transactionID)
|
||||
return false
|
||||
}
|
||||
@@ -125,8 +116,7 @@ export async function updatePaymentStatus(
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
const logger = createContextLogger(payload, 'Payment Update')
|
||||
logger.error(`Failed to update payment ${paymentId}:`, error)
|
||||
console.error(`[Payment Update] Failed to update payment ${paymentId}:`, error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -162,19 +152,13 @@ export async function updateInvoiceOnPaymentSuccess(
|
||||
export function handleWebhookError(
|
||||
provider: string,
|
||||
error: unknown,
|
||||
context?: string,
|
||||
payload?: Payload
|
||||
context?: string
|
||||
): Response {
|
||||
const message = error instanceof Error ? error.message : 'Unknown error'
|
||||
const fullContext = context ? `${provider} Webhook - ${context}` : `${provider} Webhook`
|
||||
const fullContext = context ? `[${provider} Webhook - ${context}]` : `[${provider} Webhook]`
|
||||
|
||||
// Log detailed error internally for debugging
|
||||
if (payload) {
|
||||
const logger = createContextLogger(payload, fullContext)
|
||||
logger.error('Error:', error)
|
||||
} else {
|
||||
console.error(`[${fullContext}] Error:`, error)
|
||||
}
|
||||
console.error(`${fullContext} Error:`, error)
|
||||
|
||||
// Return generic response to avoid information disclosure
|
||||
return Response.json({
|
||||
@@ -189,15 +173,9 @@ export function handleWebhookError(
|
||||
export function logWebhookEvent(
|
||||
provider: string,
|
||||
event: string,
|
||||
details?: any,
|
||||
payload?: Payload
|
||||
details?: any
|
||||
): void {
|
||||
if (payload) {
|
||||
const logger = createContextLogger(payload, `${provider} Webhook`)
|
||||
logger.info(event, details ? JSON.stringify(details) : '')
|
||||
} else {
|
||||
console.log(`[${provider} Webhook] ${event}`, details ? JSON.stringify(details) : '')
|
||||
}
|
||||
console.log(`[${provider} Webhook] ${event}`, details ? JSON.stringify(details) : '')
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
let pluginLogger: any = null
|
||||
|
||||
/**
|
||||
* Get or create the plugin logger instance
|
||||
* Uses PAYLOAD_BILLING_LOG_LEVEL environment variable to configure log level
|
||||
* Defaults to 'info' if not set
|
||||
*/
|
||||
export function getPluginLogger(payload: Payload) {
|
||||
if (!pluginLogger && payload.logger) {
|
||||
const logLevel = process.env.PAYLOAD_BILLING_LOG_LEVEL || 'info'
|
||||
|
||||
pluginLogger = payload.logger.child({
|
||||
level: logLevel,
|
||||
plugin: '@xtr-dev/payload-billing'
|
||||
})
|
||||
|
||||
// Log the configured log level on first initialization
|
||||
pluginLogger.info(`Logger initialized with level: ${logLevel}`)
|
||||
}
|
||||
|
||||
// Fallback to console if logger not available (shouldn't happen in normal operation)
|
||||
if (!pluginLogger) {
|
||||
return {
|
||||
debug: (...args: any[]) => console.log('[BILLING DEBUG]', ...args),
|
||||
info: (...args: any[]) => console.log('[BILLING INFO]', ...args),
|
||||
warn: (...args: any[]) => console.warn('[BILLING WARN]', ...args),
|
||||
error: (...args: any[]) => console.error('[BILLING ERROR]', ...args),
|
||||
}
|
||||
}
|
||||
|
||||
return pluginLogger
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a context-specific logger for a particular operation
|
||||
*/
|
||||
export function createContextLogger(payload: Payload, context: string) {
|
||||
const logger = getPluginLogger(payload)
|
||||
|
||||
return {
|
||||
debug: (message: string, ...args: any[]) => logger.debug(`[${context}] ${message}`, ...args),
|
||||
info: (message: string, ...args: any[]) => logger.info(`[${context}] ${message}`, ...args),
|
||||
warn: (message: string, ...args: any[]) => logger.warn(`[${context}] ${message}`, ...args),
|
||||
error: (message: string, ...args: any[]) => logger.error(`[${context}] ${message}`, ...args),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user