Skip to content

Payment System Setup

VetheonGames edited this page Sep 28, 2025 · 1 revision

Source-License Payment System Setup Guide

Overview

This guide covers the complete setup of the Source-License payment processing system with Stripe and PayPal webhooks for production deployment.

Architecture Summary

The payment system consists of:

  1. Payment Processors - Handle Stripe and PayPal API interactions
  2. Webhook Handlers - Process payment events automatically
  3. Payment Logger - Comprehensive logging and monitoring
  4. Subscription Management - Automated license renewals
  5. Security Layer - Signature verification and fraud prevention

Environment Configuration

Required Environment Variables

# Payment Gateway Settings
# Stripe
STRIPE_PUBLISHABLE_KEY=pk_live_your_stripe_publishable_key
STRIPE_SECRET_KEY=sk_live_your_stripe_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret

# PayPal
PAYPAL_CLIENT_ID=your_paypal_client_id
PAYPAL_CLIENT_SECRET=your_paypal_client_secret
PAYPAL_ENVIRONMENT=production  # or sandbox for testing
PAYPAL_WEBHOOK_ID=your_paypal_webhook_id

# Application Settings
APP_ENV=production
APP_HOST=yourdomain.com
HTTPS=true

# Logging & Monitoring
LOG_FORMAT=json
LOG_LEVEL=info
MONITORING_WEBHOOK_URL=https://your-monitoring-service.com/webhook

Webhook Endpoints Setup

1. Stripe Webhook Configuration

  1. Login to Stripe Dashboard

    • Go to Developers → Webhooks
    • Click "Add endpoint"
  2. Endpoint Configuration

    • URL: https://yourdomain.com/webhooks/stripe
    • Events to send:
      • charge.succeeded
      • charge.failed
      • charge.refunded
      • customer.subscription.created
      • customer.subscription.deleted
      • customer.subscription.updated
      • invoice.payment_succeeded
      • invoice.payment_failed
  3. Security

    • Copy the webhook signing secret
    • Set as STRIPE_WEBHOOK_SECRET environment variable

2. PayPal Webhook Configuration

  1. Login to PayPal Developer Console

    • Go to Applications → Create App
    • Enable webhook features
  2. Webhook Configuration

    • URL: https://yourdomain.com/webhooks/paypal
    • Events to send:
      • PAYMENT.SALE.COMPLETED
      • PAYMENT.SALE.DENIED
      • PAYMENT.SALE.REFUNDED
      • BILLING.SUBSCRIPTION.CREATED
      • BILLING.SUBSCRIPTION.CANCELLED
      • BILLING.SUBSCRIPTION.SUSPENDED
      • BILLING.SUBSCRIPTION.ACTIVATED
  3. Security

    • Copy the webhook ID
    • Set as PAYPAL_WEBHOOK_ID environment variable

Database Schema Requirements

The system requires the following tables with these key fields:

Orders Table

-- Required fields for webhook integration
- payment_intent_id (Stripe payment intent)
- transaction_id (PayPal transaction)
- idempotency_key (duplicate prevention)
- payment_method ('stripe' or 'paypal')

Licenses Table

-- Required fields for automatic management
- customer_email (for webhook matching)
- status ('active', 'suspended', 'revoked')
- expires_at (automatic extension)

Subscriptions Table

-- Required fields for recurring payments
- external_subscription_id (Stripe/PayPal subscription ID)
- status ('active', 'canceled', 'past_due')
- current_period_start, current_period_end
- auto_renew (boolean)
- last_payment_at

Webhook Event Processing

Automatic License Management

Successful Payments

  • Stripe: charge.succeeded
  • PayPal: PAYMENT.SALE.COMPLETED
  • Action: Activate/extend license, update subscription status

Failed Payments

  • Stripe: charge.failed
  • PayPal: PAYMENT.SALE.DENIED
  • Action: Send notification, enter grace period (subscriptions)

Refunds

  • Stripe: charge.refunded
  • PayPal: PAYMENT.SALE.REFUNDED
  • Action: Revoke license, cancel subscription

Subscription Changes

  • Creation: Activate license, set up billing cycle
  • Cancellation: Revoke license immediately
  • Suspension: Suspend license (temporary)

Security Features

  1. Signature Verification

    • All webhooks verified with provider signatures
    • Invalid signatures rejected with 400 status
  2. Duplicate Prevention

    • Idempotency keys prevent duplicate processing
    • Database constraints prevent race conditions
  3. Comprehensive Logging

    • All events logged with structured data
    • Security events sent to monitoring systems
    • Payment statistics tracked automatically

Testing the Integration

1. Run Webhook Tests

# Make the test script executable
chmod +x test_webhooks.rb

# Run tests against local development server
./test_webhooks.rb

# Run tests against production (be careful!)
./test_webhooks.rb --url https://yourdomain.com

2. Test with Stripe CLI

# Install Stripe CLI
stripe listen --forward-to localhost:4567/webhooks/stripe

# Trigger test events
stripe trigger charge.succeeded
stripe trigger customer.subscription.created

3. PayPal Webhook Testing

Use PayPal's webhook simulator in the developer console to send test events to your endpoint.

Monitoring and Logging

Log Files

  • logs/payments.log - Payment events
  • logs/webhooks.log - Webhook processing
  • logs/licenses.log - License lifecycle events
  • logs/security.log - Security events

Monitoring Integration

The system can send critical events to external monitoring services:

# Set monitoring webhook URL
MONITORING_WEBHOOK_URL=https://your-service.com/webhook

# Events automatically sent:
# - Payment failures
# - Webhook signature failures
# - Duplicate payment attempts
# - Subscription cancellations

Health Checks

Monitor these endpoints:

  • /health - Basic application health
  • /ready - Comprehensive readiness check
  • /webhooks/health - Webhook system status

Production Deployment Checklist

Pre-deployment

  • Environment variables configured
  • Database schema updated
  • Webhook endpoints configured in payment providers
  • SSL certificates installed
  • Monitoring systems configured

Post-deployment

  • Test webhook endpoints with providers
  • Verify signature verification works
  • Test complete payment flows
  • Monitor logs for errors
  • Set up alerting for failed webhooks

Security Considerations

  • Webhook endpoints only accessible via HTTPS
  • Rate limiting configured for webhook endpoints
  • Database backups scheduled
  • Monitoring alerts configured
  • Log retention policies set

Troubleshooting Common Issues

Webhook Not Receiving Events

  1. Check URL accessibility from internet
  2. Verify SSL certificate validity
  3. Check webhook configuration in provider dashboard
  4. Review application logs for errors

Signature Verification Failures

  1. Verify webhook secret is correct
  2. Check clock synchronization
  3. Ensure raw payload is used for verification
  4. Review headers being sent

License Not Updating

  1. Check license lookup logic in webhook handlers
  2. Verify customer email matching
  3. Review database constraints
  4. Check transaction rollbacks in logs

Performance Issues

  1. Monitor webhook response times (< 10 seconds)
  2. Check database query performance
  3. Review logging overhead
  4. Consider webhook queuing for high volume

Support and Maintenance

Regular Tasks

  • Monitor webhook success rates
  • Review security logs weekly
  • Update payment processor SDKs
  • Test webhook endpoints monthly

Performance Monitoring

  • Track webhook response times
  • Monitor payment success rates
  • Review license activation metrics
  • Analyze subscription churn rates

API Integration Examples

Processing a Stripe Payment

# Create payment intent
result = PaymentProcessor.create_payment_intent(order, 'stripe')

# Process payment after customer confirmation
result = PaymentProcessor.process_payment(order, 'stripe', {
  payment_method_id: params[:payment_method_id],
  idempotency_key: "order_#{order.id}_#{Time.now.to_i}"
})

Processing a PayPal Payment

# Create PayPal order
result = PaymentProcessor.create_payment_intent(order, 'paypal')

# Redirect customer to approval_url
redirect result[:approval_url]

# Capture payment after approval
result = PaymentProcessor.process_payment(order, 'paypal', {
  order_id: params[:paypal_order_id]
})

This comprehensive setup ensures your Source-License payment system is production-ready with robust webhook processing, security, and monitoring capabilities.

Clone this wiki locally