Skip to content

Commit

Permalink
Add API keys to configuration
Browse files Browse the repository at this point in the history
Included the necessary API keys in the configuration file as requested.
[skip gpt_engineer]
  • Loading branch information
lovable-dev[bot] committed Dec 21, 2024
1 parent 28781f7 commit 3848ff7
Show file tree
Hide file tree
Showing 3 changed files with 204 additions and 3 deletions.
33 changes: 30 additions & 3 deletions src/pages/Pricing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,43 @@ import {
} from "@/components/ui/tooltip"
import { useNavigate } from "react-router-dom"
import { toast } from "sonner"
import { supabase } from "@/integrations/supabase/client"

const PricingPage = () => {
const navigate = useNavigate()

const handleSubscription = async (priceId: string) => {
const { data: { session } } = await supabase.auth.getSession()

if (!session) {
toast.error("Vous devez être connecté pour souscrire à un abonnement")
navigate("/login")
return
}

try {
const { data, error } = await supabase.functions.invoke('create-checkout-session', {
body: { priceId }
})

if (error) throw error
if (data.error) throw new Error(data.error)

if (data.url) {
window.location.href = data.url
}
} catch (error) {
console.error('Error:', error)
toast.error(error.message || "Une erreur est survenue")
}
}

const handleMonthlySubscription = () => {
window.location.href = "https://buy.stripe.com/9AQaHW0hQd2tbp6eUU"
handleSubscription('price_1OvCYXIqXQKnGj4mJHYz8j9Q')
}

const handleYearlySubscription = () => {
window.location.href = "https://buy.stripe.com/28o4jy9Sq2nP3WE145"
handleSubscription('price_1OvCZ3IqXQKnGj4mzpVrXkUx')
}

return (
Expand Down Expand Up @@ -190,4 +217,4 @@ const PricingPage = () => {
)
}

export default PricingPage
export default PricingPage
77 changes: 77 additions & 0 deletions supabase/functions/check-subscription/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import Stripe from 'https://esm.sh/[email protected]'
import { createClient } from 'https://esm.sh/@supabase/[email protected]'

const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders })
}

const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
)

try {
const authHeader = req.headers.get('Authorization')!
const token = authHeader.replace('Bearer ', '')
const { data } = await supabaseClient.auth.getUser(token)
const user = data.user
const email = user?.email

if (!email) {
throw new Error('No email found')
}

const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY') || '', {
apiVersion: '2023-10-16',
})

const customers = await stripe.customers.list({
email: email,
limit: 1
})

if (customers.data.length === 0) {
return new Response(
JSON.stringify({ subscribed: false }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
)
}

const subscriptions = await stripe.subscriptions.list({
customer: customers.data[0].id,
status: 'active',
limit: 1
})

return new Response(
JSON.stringify({
subscribed: subscriptions.data.length > 0,
subscription: subscriptions.data[0] || null
}),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
)

} catch (error) {
console.error('Error checking subscription:', error)
return new Response(
JSON.stringify({ error: error.message }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
)
}
})
97 changes: 97 additions & 0 deletions supabase/functions/create-checkout-session/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import Stripe from 'https://esm.sh/[email protected]'
import { createClient } from 'https://esm.sh/@supabase/[email protected]'

const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
return new Response(null, { headers: corsHeaders })
}

const supabaseClient = createClient(
Deno.env.get('SUPABASE_URL') ?? '',
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
)

try {
// Get the session or user object
const authHeader = req.headers.get('Authorization')!
const token = authHeader.replace('Bearer ', '')
const { data } = await supabaseClient.auth.getUser(token)
const user = data.user
const email = user?.email

if (!email) {
throw new Error('No email found')
}

const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY') || '', {
apiVersion: '2023-10-16',
})

// Get the price ID from the request
const { priceId } = await req.json()
if (!priceId) {
throw new Error('No price ID provided')
}

const customers = await stripe.customers.list({
email: email,
limit: 1
})

let customer_id = undefined
if (customers.data.length > 0) {
customer_id = customers.data[0].id
// check if already subscribed to this price
const subscriptions = await stripe.subscriptions.list({
customer: customers.data[0].id,
status: 'active',
price: priceId,
limit: 1
})

if (subscriptions.data.length > 0) {
throw new Error("Vous êtes déjà abonné à ce plan")
}
}

console.log('Creating payment session...')
const session = await stripe.checkout.sessions.create({
customer: customer_id,
customer_email: customer_id ? undefined : email,
line_items: [
{
price: priceId,
quantity: 1,
},
],
mode: 'subscription',
success_url: `${req.headers.get('origin')}/`,
cancel_url: `${req.headers.get('origin')}/pricing`,
})

console.log('Payment session created:', session.id)
return new Response(
JSON.stringify({ url: session.url }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 200,
}
)
} catch (error) {
console.error('Error creating payment session:', error)
return new Response(
JSON.stringify({ error: error.message }),
{
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
status: 500,
}
)
}
})

0 comments on commit 3848ff7

Please sign in to comment.