feat: Implement Stripe subscription management with dynamic display of payment success and subscription details.
This commit is contained in:
@@ -1,22 +1,59 @@
|
||||
'use client';
|
||||
|
||||
import Image from 'next/image';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
interface TransactionDetail {
|
||||
label: string;
|
||||
value: string;
|
||||
bold?: boolean;
|
||||
}
|
||||
|
||||
const TRANSACTION_DETAILS: TransactionDetail[] = [
|
||||
{ label: 'Transaction ID', value: 'REQ-89234475', bold: true },
|
||||
{ label: 'Amount Paid', value: '$499.00', bold: true },
|
||||
{ label: 'Date', value: 'Oct 24, 2024', bold: true },
|
||||
];
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { stripeService, AgentSubscription } from '@/services/stripe.service';
|
||||
|
||||
export function PaymentSuccessForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const sessionId = searchParams.get('session_id');
|
||||
|
||||
const [subscription, setSubscription] = useState<AgentSubscription | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadSubscription();
|
||||
}, []);
|
||||
|
||||
const loadSubscription = async () => {
|
||||
try {
|
||||
const sub = await stripeService.getSubscription();
|
||||
setSubscription(sub);
|
||||
} catch (error) {
|
||||
console.error('Failed to load subscription:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateStr: string | null | undefined) => {
|
||||
if (!dateStr) return 'N/A';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
};
|
||||
|
||||
const formatAmount = (amount: number) => {
|
||||
return `$${(amount / 100).toFixed(2)}`;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-[#e58625]" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const transactionDetails = [
|
||||
{ label: 'Transaction ID', value: sessionId ? sessionId.slice(0, 16) + '...' : 'N/A', bold: true },
|
||||
{ label: 'Amount Paid', value: subscription?.plan ? formatAmount(subscription.plan.amount) : '$499.00', bold: true },
|
||||
{ label: 'Date', value: formatDate(subscription?.createdAt || new Date().toISOString()), bold: true },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -74,7 +111,7 @@ export function PaymentSuccessForm() {
|
||||
|
||||
{/* Detail Rows */}
|
||||
<div className="space-y-5 mb-6">
|
||||
{TRANSACTION_DETAILS.map((detail) => (
|
||||
{transactionDetails.map((detail) => (
|
||||
<div key={detail.label} className="flex items-center justify-between">
|
||||
<span className="font-serif text-[15px] text-[#00293D]/50">
|
||||
{detail.label}
|
||||
@@ -95,7 +132,7 @@ export function PaymentSuccessForm() {
|
||||
Next Renewal Date
|
||||
</span>
|
||||
<span className="font-serif font-bold text-[14px] text-[#e58625]">
|
||||
Oct 24, 2025
|
||||
{formatDate(subscription?.currentPeriodEnd)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -114,6 +151,7 @@ export function PaymentSuccessForm() {
|
||||
Go To Dashboard
|
||||
</button>
|
||||
<button
|
||||
onClick={() => router.push('/agent/settings/billings')}
|
||||
className="flex-1 bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] py-4 rounded-[15px] hover:bg-[#d47920] transition-colors flex items-center justify-center gap-2"
|
||||
>
|
||||
<Image
|
||||
@@ -122,7 +160,7 @@ export function PaymentSuccessForm() {
|
||||
width={20}
|
||||
height={20}
|
||||
/>
|
||||
Download Receipt
|
||||
View Subscription
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { stripeService, AgentSubscription } from '@/services/stripe.service';
|
||||
|
||||
interface PlanFeature {
|
||||
icon: string;
|
||||
@@ -17,7 +18,81 @@ const PLAN_FEATURES: PlanFeature[] = [
|
||||
];
|
||||
|
||||
export function SubscriptionForm() {
|
||||
const router = useRouter();
|
||||
const [subscription, setSubscription] = useState<AgentSubscription | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [actionLoading, setActionLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadSubscription();
|
||||
}, []);
|
||||
|
||||
const loadSubscription = async () => {
|
||||
try {
|
||||
const subData = await stripeService.getSubscription();
|
||||
setSubscription(subData);
|
||||
} catch (error) {
|
||||
console.error('Failed to load subscription data:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleGetPremium = async () => {
|
||||
setActionLoading(true);
|
||||
try {
|
||||
// Fetch plan ID on-demand when user clicks the button
|
||||
const plans = await stripeService.getPlans();
|
||||
if (!plans.length) {
|
||||
alert('No subscription plans available. Please try again later.');
|
||||
return;
|
||||
}
|
||||
const { url } = await stripeService.createCheckoutSession(plans[0].id);
|
||||
window.location.href = url;
|
||||
} catch (error: any) {
|
||||
console.error('Failed to create checkout session:', error);
|
||||
alert(error.response?.data?.message || 'Failed to start checkout. Please try again.');
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManageSubscription = async () => {
|
||||
setActionLoading(true);
|
||||
try {
|
||||
const { url } = await stripeService.createPortalSession();
|
||||
window.location.href = url;
|
||||
} catch (error) {
|
||||
console.error('Failed to open billing portal:', error);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancelSubscription = async () => {
|
||||
if (!confirm('Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.')) {
|
||||
return;
|
||||
}
|
||||
setActionLoading(true);
|
||||
try {
|
||||
await stripeService.cancelSubscription();
|
||||
await loadSubscription();
|
||||
} catch (error) {
|
||||
console.error('Failed to cancel subscription:', error);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateStr: string | null) => {
|
||||
if (!dateStr) return '';
|
||||
return new Date(dateStr).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
});
|
||||
};
|
||||
|
||||
const isActive = subscription?.status === 'ACTIVE';
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -31,6 +106,46 @@ export function SubscriptionForm() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Active Subscription Status */}
|
||||
{isActive && (
|
||||
<div className="mb-8 border border-green-300 bg-green-50 rounded-[10px] p-6">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<div className="w-3 h-3 bg-green-500 rounded-full" />
|
||||
<h3 className="font-fractul font-bold text-[18px] text-[#00293D]">
|
||||
Active Subscription
|
||||
</h3>
|
||||
</div>
|
||||
<p className="font-serif text-[14px] text-[#00293D] mb-1">
|
||||
Plan: <strong>{subscription.plan?.name}</strong>
|
||||
</p>
|
||||
{subscription.currentPeriodEnd && (
|
||||
<p className="font-serif text-[14px] text-[#00293D] mb-1">
|
||||
{subscription.cancelAtPeriodEnd
|
||||
? `Cancels on: ${formatDate(subscription.currentPeriodEnd)}`
|
||||
: `Renews on: ${formatDate(subscription.currentPeriodEnd)}`}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-3 mt-4">
|
||||
<button
|
||||
onClick={handleManageSubscription}
|
||||
disabled={actionLoading}
|
||||
className="bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
|
||||
>
|
||||
{actionLoading ? 'Loading...' : 'Manage Subscription'}
|
||||
</button>
|
||||
{!subscription.cancelAtPeriodEnd && (
|
||||
<button
|
||||
onClick={handleCancelSubscription}
|
||||
disabled={actionLoading}
|
||||
className="border border-red-400 text-red-500 font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px] hover:bg-red-50 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Cancel Subscription
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Annual Membership Plans */}
|
||||
<div className="mb-8">
|
||||
<h2 className="font-fractul font-bold text-[20px] text-[#00293D] mb-4">
|
||||
@@ -74,12 +189,19 @@ export function SubscriptionForm() {
|
||||
</div>
|
||||
|
||||
{/* CTA Button */}
|
||||
{isActive ? (
|
||||
<span className="inline-block bg-green-100 text-green-700 font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px]">
|
||||
Current Plan
|
||||
</span>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => router.push('/agent/settings/billings/checkout')}
|
||||
className="bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] px-10 py-4 rounded-[15px] hover:bg-[#d47920] transition-colors"
|
||||
onClick={handleGetPremium}
|
||||
disabled={actionLoading || loading}
|
||||
className="bg-[#e58625] border border-[#e58625] text-white font-fractul font-bold text-[14px] px-10 py-4 rounded-[15px] hover:bg-[#d47920] transition-colors disabled:opacity-50"
|
||||
>
|
||||
Get Premium Access
|
||||
{actionLoading ? 'Processing...' : 'Get Premium Access'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right Side - Features + Illustration */}
|
||||
|
||||
@@ -95,6 +95,7 @@ const publicEndpoints = [
|
||||
'/auth/2fa/verify-backup',
|
||||
'/agent-types',
|
||||
'/cms',
|
||||
'/stripe/plans',
|
||||
];
|
||||
|
||||
// Check if URL is a public endpoint
|
||||
|
||||
@@ -63,3 +63,7 @@ export { cmsService } from './cms.service';
|
||||
export { notificationService } from './notification.service';
|
||||
export { notificationsApiService } from './notifications-api.service';
|
||||
export type { AppNotification } from './notifications-api.service';
|
||||
|
||||
// Stripe Service
|
||||
export { stripeService } from './stripe.service';
|
||||
export type { SubscriptionPlan, AgentSubscription, PaymentRecord } from './stripe.service';
|
||||
|
||||
76
src/services/stripe.service.ts
Normal file
76
src/services/stripe.service.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import api from './api';
|
||||
|
||||
export interface SubscriptionPlan {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
stripePriceId: string;
|
||||
amount: number;
|
||||
currency: string;
|
||||
interval: string;
|
||||
features: string | null;
|
||||
isActive: boolean;
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
export interface AgentSubscription {
|
||||
id: string;
|
||||
userId: string;
|
||||
planId: string;
|
||||
stripeCustomerId: string;
|
||||
stripeSubscriptionId: string | null;
|
||||
status: string;
|
||||
currentPeriodStart: string | null;
|
||||
currentPeriodEnd: string | null;
|
||||
cancelAtPeriodEnd: boolean;
|
||||
canceledAt: string | null;
|
||||
plan: SubscriptionPlan;
|
||||
}
|
||||
|
||||
export interface PaymentRecord {
|
||||
id: string;
|
||||
subscriptionId: string | null;
|
||||
userId: string;
|
||||
stripePaymentIntentId: string | null;
|
||||
stripeInvoiceId: string | null;
|
||||
amount: number;
|
||||
currency: string;
|
||||
status: string;
|
||||
receiptUrl: string | null;
|
||||
createdAt: string;
|
||||
subscription: AgentSubscription | null;
|
||||
}
|
||||
|
||||
class StripeApiService {
|
||||
async getPlans(): Promise<SubscriptionPlan[]> {
|
||||
const response = await api.get('/stripe/plans');
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async getSubscription(): Promise<AgentSubscription | null> {
|
||||
const response = await api.get('/stripe/subscription');
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async createCheckoutSession(planId: string): Promise<{ url: string }> {
|
||||
const response = await api.post('/stripe/create-checkout-session', { planId });
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async createPortalSession(): Promise<{ url: string }> {
|
||||
const response = await api.post('/stripe/create-portal-session', {});
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async cancelSubscription(): Promise<AgentSubscription> {
|
||||
const response = await api.post('/stripe/cancel-subscription');
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async getPaymentHistory(): Promise<PaymentRecord[]> {
|
||||
const response = await api.get('/stripe/payments');
|
||||
return response.data.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const stripeService = new StripeApiService();
|
||||
Reference in New Issue
Block a user