HTTP
402 - Payment Required
Hitting a 402 Payment Required means the server requires payment to access the resource—subscription expired, credit limit reached, or payment method failed. This client-side error (4xx) is reserved for future use but commonly implemented by APIs requiring payment. Most common when accessing premium content without active subscription, but also appears when free tier limits are exceeded, payment methods are invalid, or billing issues block access.
#Common Causes
- →Frontend: User tries to access premium content without subscription. Free tier quota exceeded. Payment method expired or invalid. Subscription renewal failed. Account billing issue.
- →Backend: Subscription validation middleware checks payment status. Payment gateway reports failed transaction. Billing system marks account as unpaid. Free tier limit enforcement. Credit limit exceeded.
- →Infrastructure: API gateway enforces payment tiers. Load balancer routes based on subscription status. CDN restricts premium content access. Payment service integration fails.
✓Solutions
- 1Step 1: Diagnose - Check DevTools Network tab Response body—402 responses usually include payment information. Review subscription status in user account. Check payment method validity.
- 2Step 2: Diagnose - Server logs show payment validation failures. Review subscription database records. Check payment gateway transaction logs. Examine billing system status.
- 3Step 3: Fix - Client-side: Redirect user to payment page. Show subscription upgrade prompts. Display payment method update forms. Handle payment flow completion.
- 4Step 4: Fix - Server-side: Return 402 with payment URL in headers. Implement subscription validation logic. Integrate payment gateway properly. Handle payment webhooks.
- 5Step 5: Fix - Infrastructure: Configure API gateway payment tiers. Set up payment service integration. Review CDN access control rules. Monitor payment processing.
</>Code Examples
Fetch API: Handle 402 Payment Required
1// Client-side: Handle 402 by redirecting to payment
2async function fetchPremiumContent() {
3 const response = await fetch('/api/premium-content', {
4 method: 'GET',
5 headers: { 'Authorization': `Bearer ${token}` },
6 });
7
8 if (response.status === 402) {
9 const errorData = await response.json();
10 const paymentUrl = response.headers.get('X-Payment-Url') ||
11 errorData.paymentUrl ||
12 '/payment';
13 const redirectUrl = encodeURIComponent(window.location.pathname);
14
15 // Redirect to payment page
16 window.location.href = `${paymentUrl}?redirect=${redirectUrl}`;
17 return null;
18 }
19
20 return response.json();
21}
22
23// Show subscription upgrade prompt
24async function checkSubscription() {
25 const response = await fetch('/api/subscription/status');
26
27 if (response.status === 402) {
28 showSubscriptionModal({
29 title: 'Subscription Required',
30 message: 'This feature requires a premium subscription.',
31 actionUrl: '/subscribe',
32 });
33 return null;
34 }
35
36 return response.json();
37}Express.js: Payment Validation Middleware
1// Server-side: Implement payment validation
2const express = require('express');
3const app = express();
4
5// Payment validation middleware
6const requirePayment = async (req, res, next) => {
7 const userId = req.user?.id;
8
9 if (!userId) {
10 return res.status(401).json({ error: 'Unauthorized' });
11 }
12
13 // Check subscription status
14 const subscription = await db.subscriptions.findByUserId(userId);
15
16 if (!subscription || subscription.status !== 'active') {
17 return res.status(402)
18 .set('X-Payment-Url', '/payment/subscribe')
19 .json({
20 error: 'Payment Required',
21 message: 'This resource requires an active subscription',
22 paymentUrl: '/payment/subscribe',
23 subscriptionStatus: subscription?.status || 'none',
24 });
25 }
26
27 // Check if free tier limit exceeded
28 const usage = await db.usage.getCurrentMonth(userId);
29 if (subscription.tier === 'free' && usage.count >= subscription.limit) {
30 return res.status(402)
31 .set('X-Payment-Url', '/payment/upgrade')
32 .json({
33 error: 'Payment Required',
34 message: 'Free tier limit exceeded',
35 paymentUrl: '/payment/upgrade',
36 limit: subscription.limit,
37 used: usage.count,
38 });
39 }
40
41 next();
42};
43
44// Protected premium endpoint
45app.get('/api/premium-content', requirePayment, async (req, res) => {
46 const content = await db.content.findPremium();
47 res.json(content);
48});Nginx: Payment-Based Routing
1# Nginx: Route based on subscription status (via backend)
2server {
3 listen 80;
4 server_name api.example.com;
5
6 location /api/premium/ {
7 # Backend handles payment validation
8 proxy_pass http://backend;
9 proxy_set_header Host $host;
10 proxy_set_header X-Real-IP $remote_addr;
11 proxy_set_header Authorization $http_authorization;
12
13 # Pass payment URL header to client
14 proxy_pass_header X-Payment-Url;
15 }
16
17 # Payment endpoints (no authentication required)
18 location /payment/ {
19 proxy_pass http://payment-service;
20 proxy_set_header Host $host;
21 }
22}↗Related Errors
Provider Information
This error code is specific to HTTP services. For more information, refer to the official HTTP documentation.