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';
|
'use client';
|
||||||
|
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter, useSearchParams } from 'next/navigation';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
interface TransactionDetail {
|
import { stripeService, AgentSubscription } from '@/services/stripe.service';
|
||||||
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 },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function PaymentSuccessForm() {
|
export function PaymentSuccessForm() {
|
||||||
const router = useRouter();
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -74,7 +111,7 @@ export function PaymentSuccessForm() {
|
|||||||
|
|
||||||
{/* Detail Rows */}
|
{/* Detail Rows */}
|
||||||
<div className="space-y-5 mb-6">
|
<div className="space-y-5 mb-6">
|
||||||
{TRANSACTION_DETAILS.map((detail) => (
|
{transactionDetails.map((detail) => (
|
||||||
<div key={detail.label} className="flex items-center justify-between">
|
<div key={detail.label} className="flex items-center justify-between">
|
||||||
<span className="font-serif text-[15px] text-[#00293D]/50">
|
<span className="font-serif text-[15px] text-[#00293D]/50">
|
||||||
{detail.label}
|
{detail.label}
|
||||||
@@ -95,7 +132,7 @@ export function PaymentSuccessForm() {
|
|||||||
Next Renewal Date
|
Next Renewal Date
|
||||||
</span>
|
</span>
|
||||||
<span className="font-serif font-bold text-[14px] text-[#e58625]">
|
<span className="font-serif font-bold text-[14px] text-[#e58625]">
|
||||||
Oct 24, 2025
|
{formatDate(subscription?.currentPeriodEnd)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -114,6 +151,7 @@ export function PaymentSuccessForm() {
|
|||||||
Go To Dashboard
|
Go To Dashboard
|
||||||
</button>
|
</button>
|
||||||
<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"
|
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
|
<Image
|
||||||
@@ -122,7 +160,7 @@ export function PaymentSuccessForm() {
|
|||||||
width={20}
|
width={20}
|
||||||
height={20}
|
height={20}
|
||||||
/>
|
/>
|
||||||
Download Receipt
|
View Subscription
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import Image from 'next/image';
|
import Image from 'next/image';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useEffect, useState } from 'react';
|
||||||
|
import { stripeService, AgentSubscription } from '@/services/stripe.service';
|
||||||
|
|
||||||
interface PlanFeature {
|
interface PlanFeature {
|
||||||
icon: string;
|
icon: string;
|
||||||
@@ -17,7 +18,81 @@ const PLAN_FEATURES: PlanFeature[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export function SubscriptionForm() {
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -31,6 +106,46 @@ export function SubscriptionForm() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</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 */}
|
{/* Annual Membership Plans */}
|
||||||
<div className="mb-8">
|
<div className="mb-8">
|
||||||
<h2 className="font-fractul font-bold text-[20px] text-[#00293D] mb-4">
|
<h2 className="font-fractul font-bold text-[20px] text-[#00293D] mb-4">
|
||||||
@@ -74,12 +189,19 @@ export function SubscriptionForm() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* CTA Button */}
|
{/* CTA Button */}
|
||||||
<button
|
{isActive ? (
|
||||||
onClick={() => router.push('/agent/settings/billings/checkout')}
|
<span className="inline-block bg-green-100 text-green-700 font-fractul font-bold text-[14px] px-6 py-3 rounded-[15px]">
|
||||||
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"
|
Current Plan
|
||||||
>
|
</span>
|
||||||
Get Premium Access
|
) : (
|
||||||
</button>
|
<button
|
||||||
|
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"
|
||||||
|
>
|
||||||
|
{actionLoading ? 'Processing...' : 'Get Premium Access'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Right Side - Features + Illustration */}
|
{/* Right Side - Features + Illustration */}
|
||||||
|
|||||||
@@ -95,6 +95,7 @@ const publicEndpoints = [
|
|||||||
'/auth/2fa/verify-backup',
|
'/auth/2fa/verify-backup',
|
||||||
'/agent-types',
|
'/agent-types',
|
||||||
'/cms',
|
'/cms',
|
||||||
|
'/stripe/plans',
|
||||||
];
|
];
|
||||||
|
|
||||||
// Check if URL is a public endpoint
|
// Check if URL is a public endpoint
|
||||||
|
|||||||
@@ -63,3 +63,7 @@ export { cmsService } from './cms.service';
|
|||||||
export { notificationService } from './notification.service';
|
export { notificationService } from './notification.service';
|
||||||
export { notificationsApiService } from './notifications-api.service';
|
export { notificationsApiService } from './notifications-api.service';
|
||||||
export type { AppNotification } 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