1 Commits
dev ... v0.1.9

Author SHA1 Message Date
Bas
2907d0fa9d Merge pull request #25 from xtr-dev/dev
Dev
2025-09-19 14:06:09 +02:00
12 changed files with 58 additions and 443 deletions

283
README.md
View File

@@ -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. ⚠️ **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 ## Features
- 💳 Multiple payment providers (Stripe, Mollie, Test) - 💳 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 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 ## Webhook Endpoints
Automatic webhook endpoints are created for configured providers: Automatic webhook endpoints are created for configured providers:

View File

@@ -1,6 +1,6 @@
{ {
"name": "@xtr-dev/payload-billing", "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", "description": "PayloadCMS plugin for billing and payment provider integrations with tracking and local testing",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",

View File

@@ -5,11 +5,10 @@ import {
CollectionBeforeValidateHook, CollectionBeforeValidateHook,
CollectionConfig, Field, CollectionConfig, Field,
} from 'payload' } from 'payload'
import type { BillingPluginConfig} from '@/plugin/config'; import type { BillingPluginConfig} from '../plugin/config';
import { defaults } from '@/plugin/config' import { defaults } from '../plugin/config'
import { extractSlug } from '@/plugin/utils' import { extractSlug } from '../plugin/utils'
import { createContextLogger } from '@/utils/logger' import type { Invoice } from '../plugin/types/invoices'
import type { Invoice } from '@/plugin/types'
export function createInvoicesCollection(pluginConfig: BillingPluginConfig): CollectionConfig { export function createInvoicesCollection(pluginConfig: BillingPluginConfig): CollectionConfig {
const {customerRelationSlug, customerInfoExtractor} = pluginConfig const {customerRelationSlug, customerInfoExtractor} = pluginConfig
@@ -315,8 +314,7 @@ export function createInvoicesCollection(pluginConfig: BillingPluginConfig): Col
afterChange: [ afterChange: [
({ doc, operation, req }) => { ({ doc, operation, req }) => {
if (operation === 'create') { if (operation === 'create') {
const logger = createContextLogger(req.payload, 'Invoices Collection') req.payload.logger.info(`Invoice created: ${doc.number}`)
logger.info(`Invoice created: ${doc.number}`)
} }
}, },
] satisfies CollectionAfterChangeHook<Invoice>[], ] satisfies CollectionAfterChangeHook<Invoice>[],
@@ -352,8 +350,7 @@ export function createInvoicesCollection(pluginConfig: BillingPluginConfig): Col
data.billingAddress = extractedInfo.billingAddress data.billingAddress = extractedInfo.billingAddress
} }
} catch (error) { } catch (error) {
const logger = createContextLogger(req.payload, 'Invoices Collection') req.payload.logger.error(`Failed to extract customer info: ${error}`)
logger.error(`Failed to extract customer info: ${error}`)
throw new Error('Failed to extract customer information') throw new Error('Failed to extract customer information')
} }
} }

View File

@@ -2,7 +2,6 @@ import type { AccessArgs, CollectionConfig } from 'payload'
import { BillingPluginConfig, defaults } from '../plugin/config' import { BillingPluginConfig, defaults } from '../plugin/config'
import { extractSlug } from '../plugin/utils' import { extractSlug } from '../plugin/utils'
import { Payment } from '../plugin/types/index' import { Payment } from '../plugin/types/index'
import { createContextLogger } from '../utils/logger'
export function createRefundsCollection(pluginConfig: BillingPluginConfig): CollectionConfig { export function createRefundsCollection(pluginConfig: BillingPluginConfig): CollectionConfig {
// TODO: finish collection overrides // TODO: finish collection overrides
@@ -112,8 +111,7 @@ export function createRefundsCollection(pluginConfig: BillingPluginConfig): Coll
afterChange: [ afterChange: [
async ({ doc, operation, req }) => { async ({ doc, operation, req }) => {
if (operation === 'create') { if (operation === 'create') {
const logger = createContextLogger(req.payload, 'Refunds Collection') req.payload.logger.info(`Refund created: ${doc.id} for payment: ${doc.payment}`)
logger.info(`Refund created: ${doc.id} for payment: ${doc.payment}`)
// Update the related payment's refund relationship // Update the related payment's refund relationship
try { try {
@@ -131,8 +129,7 @@ export function createRefundsCollection(pluginConfig: BillingPluginConfig): Coll
}, },
}) })
} catch (error) { } catch (error) {
const logger = createContextLogger(req.payload, 'Refunds Collection') req.payload.logger.error(`Failed to update payment refunds: ${error}`)
logger.error(`Failed to update payment refunds: ${error}`)
} }
} }
}, },

View File

@@ -5,9 +5,6 @@ export type { BillingPluginConfig, CustomerInfoExtractor, AdvancedTestProviderCo
export type { Invoice, Payment, Refund } from './plugin/types/index.js' export type { Invoice, Payment, Refund } from './plugin/types/index.js'
export type { PaymentProvider, ProviderData } from './providers/types.js' export type { PaymentProvider, ProviderData } from './providers/types.js'
// Export logging utilities
export { getPluginLogger, createContextLogger } from './utils/logger.js'
// Export all providers // Export all providers
export { testProvider } from './providers/test.js' export { testProvider } from './providers/test.js'
export type { export type {

View File

@@ -55,6 +55,6 @@ export interface BillingPluginConfig {
customerInfoExtractor?: CustomerInfoExtractor // Callback to extract customer info from relationship customerInfoExtractor?: CustomerInfoExtractor // Callback to extract customer info from relationship
customerRelationSlug?: string // Customer collection slug for relationship customerRelationSlug?: string // Customer collection slug for relationship
disabled?: boolean disabled?: boolean
providers?: (PaymentProvider | undefined | null)[] providers?: PaymentProvider[]
} }

View File

@@ -28,8 +28,8 @@ export const billingPlugin = (pluginConfig: BillingPluginConfig = {}) => (config
]; ];
(pluginConfig.providers || []) (pluginConfig.providers || [])
.filter(provider => provider?.onConfig) .filter(provider => provider.onConfig)
.forEach(provider => provider?.onConfig!(config, pluginConfig)) .forEach(provider => provider.onConfig!(config, pluginConfig))
const incomingOnInit = config.onInit const incomingOnInit = config.onInit
config.onInit = async (payload) => { config.onInit = async (payload) => {
@@ -38,17 +38,17 @@ export const billingPlugin = (pluginConfig: BillingPluginConfig = {}) => (config
} }
singleton.set(payload, { singleton.set(payload, {
config: pluginConfig, config: pluginConfig,
providerConfig: (pluginConfig.providers || []).filter(Boolean).reduce( providerConfig: (pluginConfig.providers || []).reduce(
(record, provider) => { (record, provider) => {
record[provider!.key] = provider as PaymentProvider record[provider.key] = provider
return record return record
}, },
{} as Record<string, PaymentProvider> {} as Record<string, PaymentProvider>
) )
} satisfies BillingPlugin) } satisfies BillingPlugin)
await Promise.all((pluginConfig.providers || []) await Promise.all((pluginConfig.providers || [])
.filter(provider => provider?.onInit) .filter(provider => provider.onInit)
.map(provider => provider?.onInit!(payload))) .map(provider => provider.onInit!(payload)))
} }
return config return config

View File

@@ -12,7 +12,6 @@ import {
validateProductionUrl validateProductionUrl
} from './utils' } from './utils'
import { formatAmountForProvider, isValidAmount, isValidCurrencyCode } from './currency' import { formatAmountForProvider, isValidAmount, isValidCurrencyCode } from './currency'
import { createContextLogger } from '../utils/logger'
const symbol = Symbol('mollie') const symbol = Symbol('mollie')
export type MollieProviderConfig = Parameters<typeof createMollieClient>[0] export type MollieProviderConfig = Parameters<typeof createMollieClient>[0]
@@ -97,13 +96,12 @@ export const mollieProvider = (mollieConfig: MollieProviderConfig & {
if (status === 'succeeded' && updateSuccess) { if (status === 'succeeded' && updateSuccess) {
await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig) await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig)
} else if (!updateSuccess) { } else if (!updateSuccess) {
const logger = createContextLogger(payload, 'Mollie Webhook') console.warn(`[Mollie Webhook] Failed to update payment ${payment.id}, skipping invoice update`)
logger.warn(`Failed to update payment ${payment.id}, skipping invoice update`)
} }
return webhookResponses.success() return webhookResponses.success()
} catch (error) { } catch (error) {
return handleWebhookError('Mollie', error, undefined, req.payload) return handleWebhookError('Mollie', error)
} }
} }
} }

View File

@@ -12,7 +12,6 @@ import {
logWebhookEvent logWebhookEvent
} from './utils' } from './utils'
import { isValidAmount, isValidCurrencyCode } from './currency' import { isValidAmount, isValidCurrencyCode } from './currency'
import { createContextLogger } from '../utils/logger'
const symbol = Symbol('stripe') const symbol = Symbol('stripe')
@@ -61,13 +60,13 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
return webhookResponses.missingBody() return webhookResponses.missingBody()
} }
} catch (error) { } 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') const signature = req.headers.get('stripe-signature')
if (!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 // 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 { try {
event = stripe.webhooks.constructEvent(body, signature, stripeConfig.webhookSecret!) event = stripe.webhooks.constructEvent(body, signature, stripeConfig.webhookSecret!)
} catch (err) { } catch (err) {
return handleWebhookError('Stripe', err, 'Signature verification failed', req.payload) return handleWebhookError('Stripe', err, 'Signature verification failed')
} }
// Handle different event types // Handle different event types
@@ -91,7 +90,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
const payment = await findPaymentByProviderId(payload, paymentIntent.id, pluginConfig) const payment = await findPaymentByProviderId(payload, paymentIntent.id, pluginConfig)
if (!payment) { 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 return webhookResponses.success() // Still return 200 to acknowledge receipt
} }
@@ -130,8 +129,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
if (status === 'succeeded' && updateSuccess) { if (status === 'succeeded' && updateSuccess) {
await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig) await updateInvoiceOnPaymentSuccess(payload, payment, pluginConfig)
} else if (!updateSuccess) { } else if (!updateSuccess) {
const logger = createContextLogger(payload, 'Stripe Webhook') console.warn(`[Stripe Webhook] Failed to update payment ${payment.id}, skipping invoice update`)
logger.warn(`Failed to update payment ${payment.id}, skipping invoice update`)
} }
break break
} }
@@ -174,8 +172,7 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
) )
if (!updateSuccess) { if (!updateSuccess) {
const logger = createContextLogger(payload, 'Stripe Webhook') console.warn(`[Stripe Webhook] Failed to update refund status for payment ${payment.id}`)
logger.warn(`Failed to update refund status for payment ${payment.id}`)
} }
} }
break break
@@ -183,16 +180,19 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
default: default:
// Unhandled event type // Unhandled event type
logWebhookEvent('Stripe', `Unhandled event type: ${event.type}`, undefined, req.payload) logWebhookEvent('Stripe', `Unhandled event type: ${event.type}`)
} }
return webhookResponses.success() return webhookResponses.success()
} catch (error) { } 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) => { onInit: async (payload: Payload) => {
@@ -201,12 +201,6 @@ export const stripeProvider = (stripeConfig: StripeProviderConfig) => {
apiVersion: stripeConfig.apiVersion || DEFAULT_API_VERSION, apiVersion: stripeConfig.apiVersion || DEFAULT_API_VERSION,
}) })
singleton.set(payload, stripe) 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) => { initPayment: async (payload, payment) => {
// Validate required fields // Validate required fields

View File

@@ -4,12 +4,6 @@ import type { BillingPluginConfig } from '../plugin/config'
import type { Payload } from 'payload' import type { Payload } from 'payload'
import { handleWebhookError, logWebhookEvent } from './utils' import { handleWebhookError, logWebhookEvent } from './utils'
import { isValidAmount, isValidCurrencyCode } from './currency' 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 // Request validation schemas
interface ProcessPaymentRequest { interface ProcessPaymentRequest {
@@ -103,8 +97,7 @@ async function updatePaymentInDatabase(
return { success: true } return { success: true }
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown database error' const errorMessage = error instanceof Error ? error.message : 'Unknown database error'
const logger = createContextLogger(payload, 'Test Provider') console.error('[Test Provider] Database update failed:', errorMessage)
logger.error('Database update failed:', errorMessage)
return { success: false, error: errorMessage } return { success: false, error: errorMessage }
} }
} }
@@ -224,14 +217,17 @@ const testPaymentSessions = new Map<string, TestPaymentSession>()
export const testProvider = (testConfig: TestProviderConfig) => { export const testProvider = (testConfig: TestProviderConfig) => {
if (!testConfig.enabled) { if (!testConfig.enabled) {
return throw new Error('Test provider is disabled')
} }
const scenarios = testConfig.scenarios || DEFAULT_SCENARIOS const scenarios = testConfig.scenarios || DEFAULT_SCENARIOS
const baseUrl = testConfig.baseUrl || (process.env.PAYLOAD_PUBLIC_SERVER_URL || 'http://localhost:3000') const baseUrl = testConfig.baseUrl || (process.env.PAYLOAD_PUBLIC_SERVER_URL || 'http://localhost:3000')
const uiRoute = testConfig.customUiRoute || '/test-payment' 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 { return {
key: 'test', key: 'test',
@@ -242,7 +238,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
{ {
path: '/payload-billing/test/payment/:id', path: '/payload-billing/test/payment/:id',
method: 'get', method: 'get',
handler: (req) => { handler: async (req) => {
// Extract payment ID from URL path // Extract payment ID from URL path
const urlParts = req.url?.split('/') || [] const urlParts = req.url?.split('/') || []
const paymentId = urlParts[urlParts.length - 1] const paymentId = urlParts[urlParts.length - 1]
@@ -346,8 +342,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
// Process payment after delay // Process payment after delay
setTimeout(() => { setTimeout(() => {
processTestPayment(payload, session, pluginConfig).catch(async (error) => { processTestPayment(payload, session, pluginConfig).catch(async (error) => {
const logger = createContextLogger(payload, 'Test Provider') console.error('[Test Provider] Failed to process payment:', error)
logger.error('Failed to process payment:', error)
// Ensure session status is updated consistently // Ensure session status is updated consistently
session.status = 'failed' session.status = 'failed'
@@ -373,11 +368,10 @@ export const testProvider = (testConfig: TestProviderConfig) => {
) )
if (!dbResult.success) { if (!dbResult.success) {
const logger = createContextLogger(payload, 'Test Provider') console.error('[Test Provider] Database error during failure handling:', dbResult.error)
logger.error('Database error during failure handling:', dbResult.error)
// Even if database update fails, we maintain session consistency // Even if database update fails, we maintain session consistency
} else { } 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) }, scenario.delay || testConfig.defaultDelay || 1000)
@@ -391,7 +385,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
headers: { 'Content-Type': 'application/json' } headers: { 'Content-Type': 'application/json' }
}) })
} catch (error) { } 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) => { onInit: (payload: Payload) => {
logWebhookEvent('Test Provider', 'Test payment provider initialized', undefined, payload) logWebhookEvent('Test Provider', 'Test payment provider initialized')
// 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')
}
// Clean up old sessions periodically (older than 1 hour) // Clean up old sessions periodically (older than 1 hour)
setInterval(() => { setInterval(() => {
@@ -458,7 +445,7 @@ export const testProvider = (testConfig: TestProviderConfig) => {
}) })
}, 10 * 60 * 1000) // Clean every 10 minutes }, 10 * 60 * 1000) // Clean every 10 minutes
}, },
initPayment: (payload, payment) => { initPayment: async (payload, payment) => {
// Validate required fields // Validate required fields
if (!payment.amount) { if (!payment.amount) {
throw new Error('Amount is required') throw new Error('Amount is required')
@@ -575,10 +562,9 @@ async function processTestPayment(
) )
if (dbResult.success) { 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 { } else {
const logger = createContextLogger(payload, 'Test Provider') console.error('[Test Provider] Failed to update payment in database:', dbResult.error)
logger.error('Failed to update payment in database:', dbResult.error)
// Update session status to indicate database error, but don't throw // Update session status to indicate database error, but don't throw
// This allows the UI to still show the intended test result // This allows the UI to still show the intended test result
session.status = 'failed' session.status = 'failed'
@@ -586,8 +572,7 @@ async function processTestPayment(
} }
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown processing error' const errorMessage = error instanceof Error ? error.message : 'Unknown processing error'
const logger = createContextLogger(payload, 'Test Provider') console.error('[Test Provider] Failed to process payment:', errorMessage)
logger.error('Failed to process payment:', errorMessage)
session.status = 'failed' session.status = 'failed'
throw error // Re-throw to be handled by the caller throw error // Re-throw to be handled by the caller
} }
@@ -928,12 +913,12 @@ function generateTestPaymentUI(
setTimeout(() => pollStatus(), 2000); setTimeout(() => pollStatus(), 2000);
} }
} catch (error) { } catch (error) {
console.error('[Test Provider] Failed to poll status:', error); console.error('Failed to poll status:', error);
} }
} }
${testModeIndicators.consoleWarnings !== false ? ` ${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> </script>
</body> </body>

View File

@@ -4,7 +4,6 @@ import type { BillingPluginConfig } from '../plugin/config'
import type { ProviderData } from './types' import type { ProviderData } from './types'
import { defaults } from '../plugin/config' import { defaults } from '../plugin/config'
import { extractSlug, toPayloadId } from '../plugin/utils' import { extractSlug, toPayloadId } from '../plugin/utils'
import { createContextLogger } from '../utils/logger'
/** /**
* Common webhook response utilities * Common webhook response utilities
@@ -12,14 +11,9 @@ import { createContextLogger } from '../utils/logger'
*/ */
export const webhookResponses = { export const webhookResponses = {
success: () => Response.json({ received: true }, { status: 200 }), 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 // Log error internally but don't expose details
if (payload) { console.error('[Webhook] Error:', message)
const logger = createContextLogger(payload, 'Webhook')
logger.error('Error:', message)
} else {
console.error('[Webhook] Error:', message)
}
return Response.json({ error: 'Invalid request' }, { status }) return Response.json({ error: 'Invalid request' }, { status })
}, },
missingBody: () => Response.json({ received: true }, { status: 200 }), missingBody: () => Response.json({ received: true }, { status: 200 }),
@@ -69,8 +63,7 @@ export async function updatePaymentStatus(
}) as Payment }) as Payment
if (!currentPayment) { if (!currentPayment) {
const logger = createContextLogger(payload, 'Payment Update') console.error(`[Payment Update] Payment ${paymentId} not found`)
logger.error(`Payment ${paymentId} not found`)
return false return false
} }
@@ -81,8 +74,7 @@ export async function updatePaymentStatus(
const transactionID = await payload.db.beginTransaction() const transactionID = await payload.db.beginTransaction()
if (!transactionID) { if (!transactionID) {
const logger = createContextLogger(payload, 'Payment Update') console.error(`[Payment Update] Failed to begin transaction`)
logger.error('Failed to begin transaction')
return false return false
} }
@@ -97,8 +89,7 @@ export async function updatePaymentStatus(
// Check if version still matches // Check if version still matches
if ((paymentInTransaction.version || 1) !== currentVersion) { if ((paymentInTransaction.version || 1) !== currentVersion) {
// Version conflict detected - payment was modified by another process // Version conflict detected - payment was modified by another process
const logger = createContextLogger(payload, 'Payment Update') console.warn(`[Payment Update] Version conflict for payment ${paymentId} (expected version: ${currentVersion}, got: ${paymentInTransaction.version})`)
logger.warn(`Version conflict for payment ${paymentId} (expected version: ${currentVersion}, got: ${paymentInTransaction.version})`)
await payload.db.rollbackTransaction(transactionID) await payload.db.rollbackTransaction(transactionID)
return false return false
} }
@@ -125,8 +116,7 @@ export async function updatePaymentStatus(
throw error throw error
} }
} catch (error) { } catch (error) {
const logger = createContextLogger(payload, 'Payment Update') console.error(`[Payment Update] Failed to update payment ${paymentId}:`, error)
logger.error(`Failed to update payment ${paymentId}:`, error)
return false return false
} }
} }
@@ -162,19 +152,13 @@ export async function updateInvoiceOnPaymentSuccess(
export function handleWebhookError( export function handleWebhookError(
provider: string, provider: string,
error: unknown, error: unknown,
context?: string, context?: string
payload?: Payload
): Response { ): Response {
const message = error instanceof Error ? error.message : 'Unknown error' 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 // Log detailed error internally for debugging
if (payload) { console.error(`${fullContext} Error:`, error)
const logger = createContextLogger(payload, fullContext)
logger.error('Error:', error)
} else {
console.error(`[${fullContext}] Error:`, error)
}
// Return generic response to avoid information disclosure // Return generic response to avoid information disclosure
return Response.json({ return Response.json({
@@ -189,15 +173,9 @@ export function handleWebhookError(
export function logWebhookEvent( export function logWebhookEvent(
provider: string, provider: string,
event: string, event: string,
details?: any, details?: any
payload?: Payload
): void { ): void {
if (payload) { console.log(`[${provider} Webhook] ${event}`, details ? JSON.stringify(details) : '')
const logger = createContextLogger(payload, `${provider} Webhook`)
logger.info(event, details ? JSON.stringify(details) : '')
} else {
console.log(`[${provider} Webhook] ${event}`, details ? JSON.stringify(details) : '')
}
} }
/** /**

View File

@@ -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),
}
}