Introduction
🎯 What does this module do?
The Payments module lets you process secure online payments - credit cards, PayPal, bank transfers - integrating with payment gateways like Stripe to handle transactions, refunds, and payment status tracking.
Think of it as your payment processor - customers enter payment details, you process charges securely through integrated gateways, and OneEntry tracks all payment transactions with complete history.
📖 Simple Explanation
Every e-commerce application needs secure payment processing:
- 💳 Accept Payments - Credit cards, debit cards, digital wallets
- 🔒 Secure Processing - PCI-compliant payment handling
- 🔄 Payment Status - Track pending, completed, failed, refunded
- 💰 Refunds - Process full or partial refunds
- 📊 Payment History - View all transactions
- 🔗 Gateway Integration - Stripe, PayPal, custom gateways
The problem with manual payment handling:
// ❌ Bad - Storing card details (NEVER DO THIS!)
const payment = {
cardNumber: '4111111111111111',
cvv: '123',
expiry: '12/25'
};
// SECURITY RISK: Never store raw card data!
Issues:
- 🔒 Security risk - Storing sensitive card data
- 📋 PCI compliance - Expensive certification required
- 💸 No refund tracking - Manual refund management
- 🔄 No payment history - Hard to track transactions
The Payments solution:
// ✅ Good - Secure tokenized payment
const payment = await Payments.processPayment({
orderId: order.id,
amount: 99.99,
currency: 'USD',
paymentMethod: 'card',
token: 'tok_from_stripe' // Tokenized, secure
});
// Payment automatically:
// - Processes securely via Stripe
// - Tracks payment status
// - Stores transaction history
// - Handles 3D Secure authentication
// - Supports refunds
Benefits:
- 🔒 PCI compliant - Secure tokenized payments
- 📊 Payment tracking - Complete transaction history
- 🔄 Automated refunds - Easy refund processing
- 💸 Multiple gateways - Stripe, PayPal, custom
✨ Key Concepts
What is a Payment?
A Payment is a financial transaction record containing:
- Payment Method - Card, PayPal, bank transfer
- Amount - Transaction amount and currency
- Order Reference - Associated order ID
- Payment Status - Pending, completed, failed, refunded
- Gateway Details - Stripe transaction ID, PayPal reference
- Customer Info - Billing details
- Timestamps - Created, processed, completed dates
Payment Structure
Each payment has this structure:
{
id: "pay_abc123", // Payment ID
orderId: "ORD-2024-001", // Associated order
amount: 99.99, // Payment amount
currency: "USD", // Currency code
status: "completed", // Payment status
paymentMethod: "credit_card", // Payment type
gateway: "stripe", // Payment gateway
gatewayTransactionId: "ch_xyz789", // Gateway reference
customer: {
name: "John Doe",
email: "john@example.com"
},
billingAddress: {
street: "123 Main St",
city: "New York",
state: "NY",
zip: "10001",
country: "USA"
},
cardDetails: { // Last 4 digits only
brand: "Visa",
last4: "4242",
expiryMonth: 12,
expiryYear: 2025
},
metadata: {
ipAddress: "192.168.1.1",
userAgent: "Mozilla/5.0..."
},
createdAt: "2024-01-15T10:30:00Z",
processedAt: "2024-01-15T10:30:05Z",
completedAt: "2024-01-15T10:30:10Z"
}
Payment Lifecycle
1. Customer enters payment details
↓
2. Payment form tokenizes card (Stripe.js)
↓
3. Token sent to your backend (secure)
↓
4. Backend calls Payments.processPayment()
↓
5. OneEntry forwards to gateway (Stripe)
↓
6. Gateway processes payment
↓
7. 3D Secure authentication (if required)
↓
8. Payment completed/failed
↓
9. Status updated in OneEntry
↓
10. Confirmation sent to customer
Payment Statuses
| Status | Meaning | When to Use |
|---|---|---|
| pending | Payment initiated, awaiting processing | Just created |
| processing | Payment being processed by gateway | In progress |
| completed | Payment successful | Charge succeeded |
| failed | Payment declined or error | Card declined, insufficient funds |
| refunded | Payment refunded to customer | Partial or full refund |
| cancelled | Payment cancelled before processing | Customer cancelled |
| requires_action | Needs 3D Secure authentication | SCA required |
Payment Methods
| Method | Description | Gateway Support |
|---|---|---|
| credit_card | Visa, Mastercard, Amex | Stripe, PayPal |
| debit_card | Debit cards | Stripe, PayPal |
| paypal | PayPal account | PayPal |
| bank_transfer | Wire transfer, ACH | Custom |
| apple_pay | Apple Pay wallet | Stripe |
| google_pay | Google Pay wallet | Stripe |
| cash_on_delivery | Pay on delivery | N/A |
Why Use Payments Module?
| Benefit | Description |
|---|---|
| PCI Compliance | Secure tokenized payment processing |
| Gateway Integration | Stripe, PayPal built-in |
| Payment Tracking | Complete transaction history |
| Refund Management | Easy full/partial refunds |
| Fraud Protection | Built-in fraud detection |
| 3D Secure | SCA authentication support |
| Multi-Currency | Support for multiple currencies |
📋 What You Need to Know
1. Never Store Raw Card Data
CRITICAL: Never store credit card numbers, CVV, or full expiry dates.
// ❌ NEVER DO THIS
const payment = {
cardNumber: '4111111111111111',
cvv: '123'
};
// ✅ Always use tokenization
const token = await stripe.createToken(cardElement);
const payment = await Payments.processPayment({
token: token.id // Secure token
});
Why?
- PCI DSS compliance requires secure handling
- Storing card data exposes you to liability
- OneEntry never stores raw card details
2. Payment Gateway Integration
OneEntry integrates with payment gateways through IntegrationCollections:
// Configure Stripe in OneEntry Admin Panel:
// IntegrationCollections → Stripe → API Keys
// Then process payments:
const payment = await Payments.processPayment({
gateway: 'stripe',
token: stripeToken
});
Supported gateways:
- Stripe (recommended)
- PayPal
- Custom gateways (via API)
3. 3D Secure Authentication
Modern payments require Strong Customer Authentication (SCA):
const payment = await Payments.processPayment({ /* ... */ });
if (payment.status === 'requires_action') {
// Customer needs to authenticate
const result = await stripe.confirmCardPayment(
payment.clientSecret
);
if (result.error) {
console.error('Authentication failed');
} else {
console.log('Payment completed');
}
}
4. Refund Management
Process full or partial refunds:
// Full refund
await Payments.refundPayment({
paymentId: payment.id,
amount: payment.amount,
reason: 'Customer return'
});
// Partial refund
await Payments.refundPayment({
paymentId: payment.id,
amount: 50.00, // Partial amount
reason: 'Partial return'
});
📊 Quick Reference Table
| Method | Description | Returns | Use Case |
|---|---|---|---|
processPayment() | Process new payment | Promise<Payment> | Charge customer |
getPayments() | Get all payments (paginated) | Promise<{ items: Payment[], total }> | Admin dashboard |
getPaymentById() | Get specific payment | Promise<Payment> | View transaction details |
refundPayment() | Refund payment | Promise<Refund> | Process refund |
getPaymentsByOrder() | Get payments for order | Promise<Payment[]> | Order payment history |
getPaymentStatus() | Check payment status | Promise<PaymentStatus> | Poll for completion |
Payment Structure:
interface Payment {
id: string;
orderId: string;
amount: number;
currency: string;
status: PaymentStatus;
paymentMethod: string;
gateway: string;
gatewayTransactionId: string;
customer: {
name: string;
email: string;
};
billingAddress: Address;
cardDetails: {
brand: string;
last4: string;
expiryMonth: number;
expiryYear: number;
};
metadata: Record<string, any>;
createdAt: string;
processedAt: string;
completedAt: string;
}
💡 Important Notes
⚠️ Security First
Critical security rules:
- 🔒 Never store raw card data - Use tokenization
- 🔒 Use HTTPS only - All payment pages must be SSL
- 🔒 Validate on server - Never trust client-side data
- 🔒 Log transactions - Keep audit trail
- 🔒 Handle PII carefully - Protect customer data
💳 PCI Compliance
OneEntry handles PCI compliance for you:
- ✅ Tokenized payment processing
- ✅ Secure gateway integration
- ✅ No raw card data storage
- ✅ Encrypted transmission
Your responsibility:
- Use HTTPS on payment pages
- Don't log sensitive data
- Follow security best practices
🔄 Payment Status Polling
For async payments, poll for status updates:
async function waitForPayment(paymentId) {
let attempts = 0;
const maxAttempts = 30;
while (attempts < maxAttempts) {
const payment = await Payments.getPaymentById(paymentId);
if (payment.status === 'completed') {
return payment;
} else if (payment.status === 'failed') {
throw new Error('Payment failed');
}
await new Promise(resolve => setTimeout(resolve, 2000)); // 2 seconds
attempts++;
}
throw new Error('Payment timeout');
}
💰 Refund Limitations
Important refund rules:
- Can only refund completed payments
- Partial refunds must not exceed original amount
- Some gateways have time limits (e.g., 180 days)
- Refunds are asynchronous (may take days)
🎓 Best Practices
✅ DO:
- Use tokenization - Always tokenize cards with Stripe.js
- Validate amounts - Check totals on server, not just client
- Handle errors gracefully - Clear error messages for users
- Log transactions - Keep audit trail of all payments
- Use webhooks - Listen for payment status updates
- Test with test keys - Use Stripe test mode before production
- Handle 3D Secure - Implement SCA authentication flow
- Store transaction IDs - Keep gateway references for disputes
❌ DON'T:
- Don't store card numbers - NEVER store raw card data
- Don't skip validation - Always validate on server
- Don't expose API keys - Keep secret keys server-side only
- Don't trust client amounts - Recalculate totals server-side
- Don't ignore failed payments - Handle failures gracefully
- Don't forget refund tracking - Track all refund requests
- Don't skip error handling - Always use try/catch
- Don't log sensitive data - No card numbers in logs
Definition of the Payments module
The Payments module is an essential part of e-commerce applications. It provides methods for managing payments.
More information about the module's user interface https://doc.oneentry.cloud/docs/category/payments
const { Payments } = defineOneEntry( "your-project-url", { "token": "your-app-token" });
🔗 Related Documentation
- Orders Module - Order management and checkout
- IntegrationCollections Module - Payment gateway configuration
- Products Module - Products available for purchase
- Stripe Documentation - Payment gateway integration