mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: use OAuth for stripe connect
This commit is contained in:
parent
93c0838fab
commit
0449d6f87c
9 changed files with 266 additions and 50 deletions
124
apps/web/app/payments/stripe/connect/oauth/page.tsx
Normal file
124
apps/web/app/payments/stripe/connect/oauth/page.tsx
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
'use client'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useLHSession } from '@components/Contexts/LHSessionContext'
|
||||
import { useOrg } from '@components/Contexts/OrgContext'
|
||||
import { getUriWithOrg } from '@services/config/config'
|
||||
import { Check, Loader2, AlertTriangle } from 'lucide-react'
|
||||
import { motion } from 'framer-motion'
|
||||
import toast from 'react-hot-toast'
|
||||
import { verifyStripeConnection } from '@services/payments/payments'
|
||||
import Image from 'next/image'
|
||||
import learnhouseIcon from 'public/learnhouse_bigicon_1.png'
|
||||
|
||||
function StripeConnectCallback() {
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const session = useLHSession() as any
|
||||
const [status, setStatus] = useState<'processing' | 'success' | 'error'>('processing')
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const verifyConnection = async () => {
|
||||
try {
|
||||
const code = searchParams.get('code')
|
||||
const state = searchParams.get('state')
|
||||
const orgId = state?.split('=')[1] // Extract org_id value after '='
|
||||
|
||||
if (!code || !orgId) {
|
||||
throw new Error('Missing required parameters')
|
||||
}
|
||||
|
||||
const response = await verifyStripeConnection(
|
||||
parseInt(orgId),
|
||||
code,
|
||||
session?.data?.tokens?.access_token
|
||||
)
|
||||
|
||||
// Wait for 1 second to show processing state
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
|
||||
setStatus('success')
|
||||
setMessage('Successfully connected to Stripe!')
|
||||
|
||||
// Close the window after 2 seconds of showing success
|
||||
setTimeout(() => {
|
||||
window.close()
|
||||
}, 2000)
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error verifying Stripe connection:', error)
|
||||
setStatus('error')
|
||||
setMessage('Failed to complete Stripe connection')
|
||||
toast.error('Failed to connect to Stripe')
|
||||
}
|
||||
}
|
||||
|
||||
if (session) {
|
||||
verifyConnection()
|
||||
}
|
||||
}, [session, router, searchParams])
|
||||
|
||||
return (
|
||||
<div className="h-screen w-full bg-[#f8f8f8] flex items-center justify-center">
|
||||
<div className="flex flex-col items-center">
|
||||
<div className="mb-10">
|
||||
<Image
|
||||
quality={100}
|
||||
width={50}
|
||||
height={50}
|
||||
src={learnhouseIcon}
|
||||
alt=""
|
||||
/>
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
className="bg-white p-8 rounded-xl nice-shadow max-w-md w-full mx-4"
|
||||
>
|
||||
<div className="flex flex-col items-center text-center space-y-4">
|
||||
{status === 'processing' && (
|
||||
<>
|
||||
<Loader2 className="h-12 w-12 text-blue-500 animate-spin" />
|
||||
<h2 className="text-xl font-semibold text-gray-800">
|
||||
Completing Stripe Connection
|
||||
</h2>
|
||||
<p className="text-gray-500">
|
||||
Please wait while we finish setting up your Stripe integration...
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<>
|
||||
<div className="bg-green-100 p-3 rounded-full">
|
||||
<Check className="h-8 w-8 text-green-600" />
|
||||
</div>
|
||||
<h2 className="text-xl font-semibold text-gray-800">{message}</h2>
|
||||
<p className="text-gray-500">
|
||||
You can now return to the dashboard to start using payments.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<>
|
||||
<div className="bg-red-100 p-3 rounded-full">
|
||||
<AlertTriangle className="h-8 w-8 text-red-600" />
|
||||
</div>
|
||||
<h2 className="text-xl font-semibold text-gray-800">{message}</h2>
|
||||
<p className="text-gray-500">
|
||||
Please try again or contact support if the problem persists.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default StripeConnectCallback
|
||||
|
|
@ -5,7 +5,7 @@ import { SiStripe } from '@icons-pack/react-simple-icons'
|
|||
import { useLHSession } from '@components/Contexts/LHSessionContext';
|
||||
import { getPaymentConfigs, initializePaymentConfig, updatePaymentConfig, deletePaymentConfig, updateStripeAccountID, getStripeOnboardingLink } from '@services/payments/payments';
|
||||
import FormLayout, { ButtonBlack, Input, Textarea, FormField, FormLabelAndMessage, Flex } from '@components/StyledElements/Form/Form';
|
||||
import { AlertTriangle, BarChart2, Check, Coins, CreditCard, Edit, ExternalLink, Info, Loader2, RefreshCcw, Trash2 } from 'lucide-react';
|
||||
import { AlertTriangle, BarChart2, Check, Coins, CreditCard, Edit, ExternalLink, Info, Loader2, RefreshCcw, Trash2, UnplugIcon } from 'lucide-react';
|
||||
import toast from 'react-hot-toast';
|
||||
import useSWR, { mutate } from 'swr';
|
||||
import Modal from '@components/StyledElements/Modal/Modal';
|
||||
|
|
@ -13,6 +13,7 @@ import ConfirmationModal from '@components/StyledElements/ConfirmationModal/Conf
|
|||
import { Button } from '@components/ui/button';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@components/ui/alert';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { getUriWithoutOrg } from '@services/config/config';
|
||||
|
||||
const PaymentsConfigurationPage: React.FC = () => {
|
||||
const org = useOrg() as any;
|
||||
|
|
@ -62,8 +63,8 @@ const PaymentsConfigurationPage: React.FC = () => {
|
|||
const handleStripeOnboarding = async () => {
|
||||
try {
|
||||
setIsOnboardingLoading(true);
|
||||
const { connect_url } = await getStripeOnboardingLink(org.id, access_token, window.location.href);
|
||||
router.push(connect_url);
|
||||
const { connect_url } = await getStripeOnboardingLink(org.id, access_token, getUriWithoutOrg('/payments/stripe/connect/oauth'));
|
||||
window.open(connect_url, '_blank');
|
||||
} catch (error) {
|
||||
console.error('Error getting onboarding link:', error);
|
||||
toast.error('Failed to start Stripe onboarding');
|
||||
|
|
@ -152,37 +153,30 @@ const PaymentsConfigurationPage: React.FC = () => {
|
|||
</div>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
{ (
|
||||
{(!stripeConfig.provider_specific_id || !stripeConfig.active) && (
|
||||
<Button
|
||||
onClick={handleStripeOnboarding}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-yellow-500 text-white text-sm rounded-full hover:bg-yellow-600 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed border-2 border-yellow-400 shadow-md"
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-green-500 text-white text-sm rounded-full hover:bg-green-600 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed border-2 border-green-400 shadow-md"
|
||||
disabled={isOnboardingLoading}
|
||||
>
|
||||
{isOnboardingLoading ? (
|
||||
<Loader2 className="animate-spin h-4 w-4" />
|
||||
) : (
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<UnplugIcon className="h-3 w-3" />
|
||||
)}
|
||||
<span className="font-semibold">Complete Onboarding</span>
|
||||
<span className="font-semibold">Connect with Stripe</span>
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={editConfig}
|
||||
className="flex items-center space-x-2 px-4 py-2 bg-white text-purple-700 text-sm rounded-full hover:bg-gray-100 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Edit size={16} />
|
||||
<span>Edit Configuration</span>
|
||||
</Button>
|
||||
<ConfirmationModal
|
||||
confirmationButtonText="Delete Configuration"
|
||||
confirmationMessage="Are you sure you want to delete the Stripe configuration? This action cannot be undone."
|
||||
dialogTitle="Delete Stripe Configuration"
|
||||
confirmationButtonText="Remove Connection"
|
||||
confirmationMessage="Are you sure you want to remove the Stripe connection? This action cannot be undone."
|
||||
dialogTitle="Remove Stripe Connection"
|
||||
dialogTrigger={
|
||||
<Button
|
||||
className="flex items-center space-x-2 bg-red-500 text-white text-sm rounded-full hover:bg-red-600 transition duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
<span>Delete Configuration</span>
|
||||
<span>Remove Connection</span>
|
||||
</Button>
|
||||
}
|
||||
functionToExecute={deleteConfig}
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export const config = {
|
|||
*/
|
||||
'/((?!api|_next|fonts|umami|examples|[\\w-]+\\.\\w+).*)',
|
||||
'/sitemap.xml',
|
||||
'/payments/stripe/connect/oauth',
|
||||
],
|
||||
}
|
||||
|
||||
|
|
@ -80,6 +81,27 @@ export default async function middleware(req: NextRequest) {
|
|||
return NextResponse.rewrite(new URL(`/editor${pathname}`, req.url))
|
||||
}
|
||||
|
||||
// Check if the request is for the Stripe callback URL
|
||||
if (req.nextUrl.pathname.startsWith('/payments/stripe/connect/oauth')) {
|
||||
const searchParams = req.nextUrl.searchParams
|
||||
const orgslug = searchParams.get('state')?.split('_')[0] // Assuming state parameter contains orgslug_randomstring
|
||||
|
||||
// Construct the new URL with the required parameters
|
||||
const redirectUrl = new URL('/payments/stripe/connect/oauth', req.url)
|
||||
|
||||
// Preserve all original search parameters
|
||||
searchParams.forEach((value, key) => {
|
||||
redirectUrl.searchParams.append(key, value)
|
||||
})
|
||||
|
||||
// Add orgslug if available
|
||||
if (orgslug) {
|
||||
redirectUrl.searchParams.set('orgslug', orgslug)
|
||||
}
|
||||
|
||||
return NextResponse.rewrite(redirectUrl)
|
||||
}
|
||||
|
||||
// Auth Redirects
|
||||
if (pathname == '/redirect_from_auth') {
|
||||
if (cookie_orgslug) {
|
||||
|
|
|
|||
|
|
@ -56,6 +56,15 @@ export async function getStripeOnboardingLink(orgId: number, access_token: strin
|
|||
return res;
|
||||
}
|
||||
|
||||
export async function verifyStripeConnection(orgId: number, code: string, access_token: string) {
|
||||
const result = await fetch(
|
||||
`${getAPIUrl()}payments/stripe/oauth/callback?code=${code}&org_id=${orgId}`,
|
||||
RequestBodyWithAuthHeader('GET', null, null, access_token)
|
||||
);
|
||||
const res = await errorHandling(result);
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function deletePaymentConfig(orgId: number, id: string, access_token: string) {
|
||||
const result = await fetch(
|
||||
`${getAPIUrl()}payments/${orgId}/config?id=${id}`,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue