Add comprehensive Stripe webhook testing system

- Enhanced stripe_webhook_view with detailed logging and request tracking
- Created stripe_webhook_test.html for dedicated Stripe webhook testing
- Added stripe_webhook_test_view for Stripe-specific testing interface
- Logs all webhook events (both Stripe and test) with timestamps, IPs, headers
- Includes direct links to Stripe dashboard and test payment creation
- Separates Stripe events from test events with visual indicators
- Real-time monitoring of webhook delivery success/failure

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Claude 2025-07-12 15:47:32 +05:30
parent 16d07168d0
commit 4b168ec1f0
3 changed files with 612 additions and 3 deletions

View File

@ -17,6 +17,7 @@ urlpatterns = [
path('wallet/demo/check-balance/', views.wallet_demo_check_balance, name='wallet_demo_check_balance'),
path('stripe/webhook/', views.stripe_webhook_view, name='stripe_webhook'),
path('webhook-test/', views.webhook_test_view, name='webhook_test'),
path('stripe-webhook-test/', views.stripe_webhook_test_view, name='stripe_webhook_test'),
path('simple-webhook-test/', views.simple_webhook_test, name='simple_webhook_test'),
path('webhook-logs/', views.get_webhook_logs, name='webhook_logs'),
path('api/agents/', views.agents_api_view, name='agents_api'),

View File

@ -228,6 +228,11 @@ def webhook_test_view(request):
return render(request, 'core/webhook_test.html')
def stripe_webhook_test_view(request):
"""Stripe-specific webhook testing page"""
return render(request, 'core/stripe_webhook_test.html')
# Store webhook logs in memory for the test page
webhook_logs = []
@ -272,9 +277,33 @@ def get_webhook_logs(request):
@csrf_exempt
def stripe_webhook_view(request):
"""Handle Stripe webhook events"""
print(f"🎯 Stripe webhook received! Method: {request.method}")
print(f"🎯 Headers: {dict(request.META)}")
"""Handle Stripe webhook events with comprehensive logging"""
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
# Log everything for debugging
print(f"🎯 [{timestamp}] Stripe webhook received!")
print(f"🎯 Method: {request.method}")
print(f"🎯 Content-Type: {request.content_type}")
print(f"🎯 Remote IP: {request.META.get('REMOTE_ADDR', 'unknown')}")
print(f"🎯 User Agent: {request.META.get('HTTP_USER_AGENT', 'unknown')}")
print(f"🎯 Full headers: {dict(request.META)}")
# Store in webhook logs for the test page
webhook_log_entry = {
'timestamp': timestamp,
'method': request.method,
'headers': dict(request.META),
'body': request.body.decode('utf-8') if request.body else '',
'content_type': request.content_type,
'source': 'stripe_webhook',
'ip_address': request.META.get('REMOTE_ADDR', 'unknown'),
'user_agent': request.META.get('HTTP_USER_AGENT', 'unknown')
}
# Add to webhook logs
webhook_logs.append(webhook_log_entry)
if len(webhook_logs) > 50:
webhook_logs.pop(0)
if request.method != 'POST':
print(f"❌ Invalid method: {request.method}")
@ -284,9 +313,15 @@ def stripe_webhook_view(request):
sig_header = request.META.get('HTTP_STRIPE_SIGNATURE')
print(f"📦 Payload length: {len(payload)} bytes")
print(f"📦 Payload preview: {payload[:200]}...")
print(f"🔐 Signature header: {sig_header is not None}")
print(f"🔐 Full signature header: {sig_header}")
# Always return success first to see if Stripe is reaching us
if not sig_header:
print(f"⚠️ No Stripe signature - might be a test request")
return JsonResponse({'status': 'received', 'message': 'No signature verification'})
stripe_handler = StripePaymentHandler()
result = stripe_handler.handle_webhook(payload, sig_header)

View File

@ -0,0 +1,573 @@
{% extends 'base.html' %}
{% load static %}
{% block title %}Stripe Webhook Testing{% endblock %}
{% block extra_css %}
<style>
.test-page {
background: var(--gradient-hero);
min-height: calc(100vh - 80px);
padding: clamp(20px, 5vw, 40px);
}
.test-container {
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
align-items: start;
}
.test-card {
background: rgba(255, 255, 255, 0.95);
border-radius: 16px;
padding: 24px;
border: 1px solid rgba(255, 255, 255, 0.3);
backdrop-filter: blur(20px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}
.test-title {
font-size: 24px;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 10px;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
background: #e74c3c;
animation: pulse 2s infinite;
}
.status-indicator.connected {
background: #27ae60;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
.webhook-url {
background: #f8fafc;
border: 2px solid #e2e8f0;
border-radius: 8px;
padding: 15px;
margin: 15px 0;
font-family: 'Courier New', monospace;
font-size: 13px;
word-break: break-all;
position: relative;
}
.copy-btn {
position: absolute;
top: 8px;
right: 8px;
background: var(--primary-blue);
color: white;
border: none;
border-radius: 4px;
padding: 5px 10px;
font-size: 11px;
cursor: pointer;
}
.test-buttons {
display: flex;
gap: 12px;
margin: 20px 0;
flex-wrap: wrap;
}
.test-btn {
flex: 1;
min-width: 120px;
padding: 10px 16px;
border: 2px solid var(--primary-blue);
background: transparent;
color: var(--primary-blue);
border-radius: 6px;
font-weight: 600;
font-size: 13px;
cursor: pointer;
transition: all 0.2s ease;
}
.test-btn:hover {
background: var(--primary-blue);
color: white;
transform: translateY(-1px);
}
.test-btn.primary {
background: var(--primary-blue);
color: white;
}
.test-btn.primary:hover {
background: var(--primary-dark);
}
.webhook-logs {
background: #1a1a1a;
color: #00ff00;
border-radius: 8px;
padding: 15px;
margin: 15px 0;
font-family: 'Courier New', monospace;
font-size: 12px;
line-height: 1.4;
max-height: 400px;
overflow-y: auto;
position: relative;
}
.log-entry {
margin: 2px 0;
padding: 2px 0;
border-left: 3px solid transparent;
padding-left: 8px;
}
.log-stripe {
border-left-color: #00ff00;
background: rgba(0, 255, 0, 0.05);
}
.log-test {
border-left-color: #74c0fc;
background: rgba(116, 192, 252, 0.05);
}
.log-timestamp {
color: #888;
margin-right: 8px;
}
.log-success {
color: #00ff00;
}
.log-error {
color: #ff6b6b;
}
.log-info {
color: #74c0fc;
}
.log-warning {
color: #ffd43b;
}
.status-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
margin: 20px 0;
}
.status-item {
background: #f8fafc;
border-radius: 8px;
padding: 12px;
text-align: center;
font-size: 14px;
}
.status-value {
font-size: 24px;
font-weight: 700;
color: var(--primary-blue);
margin-bottom: 5px;
}
.instructions {
background: #e3f2fd;
border-radius: 8px;
padding: 15px;
margin: 20px 0;
font-size: 14px;
line-height: 1.6;
}
.clear-logs {
position: absolute;
top: 8px;
right: 8px;
background: #444;
color: #fff;
border: none;
border-radius: 4px;
padding: 4px 8px;
font-size: 10px;
cursor: pointer;
}
.stripe-dashboard-link {
display: inline-block;
background: #635bff;
color: white;
text-decoration: none;
padding: 8px 16px;
border-radius: 6px;
font-weight: 600;
font-size: 13px;
margin: 10px 0;
transition: background 0.2s;
}
.stripe-dashboard-link:hover {
background: #5a54d6;
color: white;
text-decoration: none;
}
</style>
{% endblock %}
{% block content %}
<div class="test-page">
<div class="test-container">
<!-- Stripe Webhook Configuration -->
<div class="test-card">
<h2 class="test-title">
⚡ Stripe Webhook Config
<div class="status-indicator" id="configStatus"></div>
</h2>
<div class="instructions">
<strong>📋 Setup Instructions:</strong><br>
1. Copy the webhook URL below<br>
2. Go to Stripe Dashboard → Webhooks<br>
3. Create new endpoint with this URL<br>
4. Select "checkout.session.completed" event<br>
5. Test with payment below
</div>
<div class="webhook-url">
<strong>Stripe Webhook URL:</strong><br>
<span id="stripeWebhookUrl">https://netcop.up.railway.app/stripe/webhook/</span>
<button class="copy-btn" onclick="copyUrl('stripeWebhookUrl')">📋 Copy</button>
</div>
<div class="webhook-url">
<strong>Simple Test URL:</strong><br>
<span id="simpleWebhookUrl">https://netcop.up.railway.app/simple-webhook-test/</span>
<button class="copy-btn" onclick="copyUrl('simpleWebhookUrl')">📋 Copy</button>
</div>
<a href="https://dashboard.stripe.com/test/webhooks" target="_blank" class="stripe-dashboard-link">
🔗 Open Stripe Dashboard
</a>
<div class="status-grid">
<div class="status-item">
<div class="status-value" id="stripeEvents">0</div>
<div>Stripe Events</div>
</div>
<div class="status-item">
<div class="status-value" id="testEvents">0</div>
<div>Test Events</div>
</div>
</div>
<div class="test-buttons">
<button class="test-btn" onclick="testStripeWebhook()">🧪 Test Stripe Endpoint</button>
<button class="test-btn" onclick="testSimpleWebhook()">📡 Test Simple Endpoint</button>
<button class="test-btn" onclick="refreshLogs()">🔄 Refresh</button>
<button class="test-btn" onclick="clearLogs()">🗑️ Clear</button>
</div>
</div>
<!-- Payment Testing -->
<div class="test-card">
<h2 class="test-title">
💳 Payment Testing
<div class="status-indicator" id="paymentStatus"></div>
</h2>
<div class="instructions">
<strong>💡 Test Payment Flow:</strong><br>
1. Click "Create Test Payment"<br>
2. Use test card: 4242 4242 4242 4242<br>
3. Watch for webhook events in logs<br>
4. Check if Stripe delivers the webhook
</div>
<div class="test-buttons">
<button class="test-btn primary" onclick="createTestPayment(10)">💳 Pay 10 AED</button>
<button class="test-btn primary" onclick="createTestPayment(50)">💳 Pay 50 AED</button>
</div>
<div id="paymentInfo" style="display: none; margin-top: 15px; padding: 15px; background: #e3f2fd; border-radius: 8px; font-size: 13px;">
<strong>Payment Link Created:</strong><br>
<a href="#" id="paymentLink" target="_blank" style="color: var(--primary-blue); font-weight: 600;">🔗 Complete Payment</a>
</div>
<h3 style="margin-top: 25px;">📊 Webhook Activity</h3>
<div class="webhook-logs" id="webhookLogs">
<button class="clear-logs" onclick="clearLogs()">Clear</button>
<div class="log-entry log-info">
<span class="log-timestamp">[INIT]</span> Webhook monitoring started...
</div>
<div class="log-entry log-success">
<span class="log-timestamp">[READY]</span> Waiting for Stripe events...
</div>
</div>
</div>
</div>
</div>
<script>
let pollingInterval = null;
let stripeEventCount = 0;
let testEventCount = 0;
// Initialize
document.addEventListener('DOMContentLoaded', function() {
startPolling();
updateConfigStatus(true);
logMessage('Stripe webhook testing initialized', 'success');
});
function copyUrl(elementId) {
const url = document.getElementById(elementId).textContent;
navigator.clipboard.writeText(url).then(() => {
logMessage(`URL copied: ${url}`, 'success');
});
}
function testStripeWebhook() {
logMessage('Testing Stripe webhook endpoint...', 'info');
fetch('/stripe/webhook/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Test-Source': 'webhook-test-page'
},
body: JSON.stringify({
test: true,
type: 'test_webhook',
timestamp: new Date().toISOString()
})
})
.then(response => response.json())
.then(data => {
logMessage(`Stripe endpoint response: ${JSON.stringify(data)}`, 'success');
testEventCount++;
updateEventCounts();
})
.catch(error => {
logMessage(`Stripe endpoint error: ${error.message}`, 'error');
});
}
function testSimpleWebhook() {
logMessage('Testing simple webhook endpoint...', 'info');
fetch('/simple-webhook-test/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Test-Source': 'webhook-test-page'
},
body: JSON.stringify({
test: true,
type: 'simple_test',
timestamp: new Date().toISOString()
})
})
.then(response => response.text())
.then(data => {
logMessage(`Simple endpoint response: ${data}`, 'success');
testEventCount++;
updateEventCounts();
})
.catch(error => {
logMessage(`Simple endpoint error: ${error.message}`, 'error');
});
}
function createTestPayment(amount) {
logMessage(`Creating test payment for ${amount} AED...`, 'info');
fetch('/wallet/demo/test-payment/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCsrfToken()
},
body: JSON.stringify({ amount: amount })
})
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById('paymentLink').href = data.payment_url;
document.getElementById('paymentInfo').style.display = 'block';
logMessage(`Payment created: ${data.session_id}`, 'success');
logMessage('Complete payment to trigger webhook...', 'info');
updatePaymentStatus(true);
} else {
logMessage(`Payment creation failed: ${data.error}`, 'error');
}
})
.catch(error => {
logMessage(`Payment error: ${error.message}`, 'error');
});
}
function refreshLogs() {
logMessage('Refreshing webhook logs...', 'info');
fetch('/webhook-logs/')
.then(response => response.json())
.then(data => {
displayLogs(data.logs);
logMessage(`Logs refreshed - ${data.logs.length} total entries`, 'success');
})
.catch(error => {
logMessage(`Log refresh error: ${error.message}`, 'error');
});
}
function displayLogs(logs) {
const container = document.getElementById('webhookLogs');
// Keep clear button and initial messages
const existingContent = container.innerHTML.split('<div class="log-entry')[0];
container.innerHTML = existingContent;
// Reset counters
stripeEventCount = 0;
testEventCount = 0;
if (logs.length === 0) {
const entry = document.createElement('div');
entry.className = 'log-entry log-info';
entry.innerHTML = '<span class="log-timestamp">[INFO]</span> No webhook events received yet';
container.appendChild(entry);
} else {
logs.forEach(log => {
const entry = document.createElement('div');
const isStripe = log.source === 'stripe_webhook' ||
(log.headers && log.headers['HTTP_USER_AGENT'] && log.headers['HTTP_USER_AGENT'].includes('Stripe'));
if (isStripe) {
entry.className = 'log-entry log-success log-stripe';
stripeEventCount++;
} else {
entry.className = 'log-entry log-info log-test';
testEventCount++;
}
const source = isStripe ? '[STRIPE]' : '[TEST]';
const bodyPreview = log.body ?
(log.body.length > 80 ? log.body.substring(0, 80) + '...' : log.body) :
'empty';
const ip = log.ip_address || 'unknown';
entry.innerHTML = `
<span class="log-timestamp">[${log.timestamp}]</span>
${source} ${log.method} from ${ip}<br>
<small style="color: #aaa; margin-left: 60px;">Body: ${bodyPreview}</small>
`;
container.appendChild(entry);
});
}
updateEventCounts();
container.scrollTop = container.scrollHeight;
}
function clearLogs() {
const container = document.getElementById('webhookLogs');
container.innerHTML = `
<button class="clear-logs" onclick="clearLogs()">Clear</button>
<div class="log-entry log-info">
<span class="log-timestamp">[INIT]</span> Webhook monitoring started...
</div>
<div class="log-entry log-success">
<span class="log-timestamp">[READY]</span> Waiting for Stripe events...
</div>
`;
stripeEventCount = 0;
testEventCount = 0;
updateEventCounts();
logMessage('Logs cleared', 'info');
}
function startPolling() {
pollingInterval = setInterval(refreshLogs, 3000);
}
function updateConfigStatus(status) {
const indicator = document.getElementById('configStatus');
if (status) {
indicator.classList.add('connected');
} else {
indicator.classList.remove('connected');
}
}
function updatePaymentStatus(status) {
const indicator = document.getElementById('paymentStatus');
if (status) {
indicator.classList.add('connected');
} else {
indicator.classList.remove('connected');
}
}
function updateEventCounts() {
document.getElementById('stripeEvents').textContent = stripeEventCount;
document.getElementById('testEvents').textContent = testEventCount;
}
function logMessage(message, type = 'info') {
const container = document.getElementById('webhookLogs');
const timestamp = new Date().toLocaleTimeString();
const entry = document.createElement('div');
entry.className = `log-entry log-${type}`;
entry.innerHTML = `<span class="log-timestamp">[${timestamp}]</span> ${message}`;
container.appendChild(entry);
container.scrollTop = container.scrollHeight;
// Keep only last 50 entries
while (container.children.length > 52) {
container.removeChild(container.children[1]);
}
}
function getCsrfToken() {
const cookies = document.cookie.split(';');
for (let cookie of cookies) {
const [name, value] = cookie.trim().split('=');
if (name === 'csrftoken') {
return value;
}
}
return '';
}
// Cleanup
window.addEventListener('beforeunload', function() {
if (pollingInterval) {
clearInterval(pollingInterval);
}
});
</script>
{% endblock %}