Skip to main content

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

StatusMeaningWhen to Use
pendingPayment initiated, awaiting processingJust created
processingPayment being processed by gatewayIn progress
completedPayment successfulCharge succeeded
failedPayment declined or errorCard declined, insufficient funds
refundedPayment refunded to customerPartial or full refund
cancelledPayment cancelled before processingCustomer cancelled
requires_actionNeeds 3D Secure authenticationSCA required

Payment Methods

MethodDescriptionGateway Support
credit_cardVisa, Mastercard, AmexStripe, PayPal
debit_cardDebit cardsStripe, PayPal
paypalPayPal accountPayPal
bank_transferWire transfer, ACHCustom
apple_payApple Pay walletStripe
google_payGoogle Pay walletStripe
cash_on_deliveryPay on deliveryN/A

Why Use Payments Module?

BenefitDescription
PCI ComplianceSecure tokenized payment processing
Gateway IntegrationStripe, PayPal built-in
Payment TrackingComplete transaction history
Refund ManagementEasy full/partial refunds
Fraud ProtectionBuilt-in fraud detection
3D SecureSCA authentication support
Multi-CurrencySupport 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

MethodDescriptionReturnsUse Case
processPayment()Process new paymentPromise<Payment>Charge customer
getPayments()Get all payments (paginated)Promise<{ items: Payment[], total }>Admin dashboard
getPaymentById()Get specific paymentPromise<Payment>View transaction details
refundPayment()Refund paymentPromise<Refund>Process refund
getPaymentsByOrder()Get payments for orderPromise<Payment[]>Order payment history
getPaymentStatus()Check payment statusPromise<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:

  1. Use tokenization - Always tokenize cards with Stripe.js
  2. Validate amounts - Check totals on server, not just client
  3. Handle errors gracefully - Clear error messages for users
  4. Log transactions - Keep audit trail of all payments
  5. Use webhooks - Listen for payment status updates
  6. Test with test keys - Use Stripe test mode before production
  7. Handle 3D Secure - Implement SCA authentication flow
  8. Store transaction IDs - Keep gateway references for disputes

❌ DON'T:

  1. Don't store card numbers - NEVER store raw card data
  2. Don't skip validation - Always validate on server
  3. Don't expose API keys - Keep secret keys server-side only
  4. Don't trust client amounts - Recalculate totals server-side
  5. Don't ignore failed payments - Handle failures gracefully
  6. Don't forget refund tracking - Track all refund requests
  7. Don't skip error handling - Always use try/catch
  8. 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"
}
);