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 files as requested.
[skip gpt_engineer]
  • Loading branch information
lovable-dev[bot] committed Dec 30, 2024
1 parent f677778 commit ba38816
Show file tree
Hide file tree
Showing 3 changed files with 133 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/components/landing/WaitlistForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { supabase } from "@/integrations/supabase/client"
import { useToast } from "@/hooks/use-toast"
import { WaitlistFormFields } from "./waitlist/WaitlistFormFields"
import { SuccessToast } from "./waitlist/SuccessToast"
import { useMailerLite } from "@/hooks/use-mailerlite"

interface WaitlistFormData {
email: string
Expand All @@ -14,13 +15,15 @@ interface WaitlistFormData {
export const WaitlistForm = () => {
const [isLoading, setIsLoading] = useState(false)
const { toast } = useToast()
const { subscribeToMailerLite } = useMailerLite()
const { register, handleSubmit, reset, formState: { errors } } = useForm<WaitlistFormData>()

const onSubmit = async (data: WaitlistFormData) => {
console.log('Submitting form with data:', data)
setIsLoading(true)
try {
const { error } = await supabase
// D'abord, on inscrit dans Supabase
const { error: supabaseError } = await supabase
.from('waitlist')
.insert([
{
Expand All @@ -30,9 +33,9 @@ export const WaitlistForm = () => {
}
])

if (error) {
console.error('Supabase error details:', error)
if (error.code === '23505') {
if (supabaseError) {
console.error('Supabase error details:', supabaseError)
if (supabaseError.code === '23505') {
toast({
variant: "destructive",
title: "Email déjà inscrit",
Expand All @@ -48,6 +51,13 @@ export const WaitlistForm = () => {
return
}

// Ensuite, on inscrit dans MailerLite
await subscribeToMailerLite({
email: data.email,
firstName: data.firstName,
teachingLevel: data.teachingLevel
})

console.log('Form submitted successfully')

// Fermer la popup immédiatement en utilisant l'API Dialog de Radix
Expand Down
33 changes: 33 additions & 0 deletions src/hooks/use-mailerlite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { supabase } from "@/integrations/supabase/client"

interface SubscribeToMailerLiteParams {
email: string
firstName: string
teachingLevel?: string
}

export const useMailerLite = () => {
const subscribeToMailerLite = async ({
email,
firstName,
teachingLevel
}: SubscribeToMailerLiteParams) => {
try {
const { data, error } = await supabase.functions.invoke('subscribe-to-mailerlite', {
body: { email, firstName, teachingLevel }
})

if (error) {
console.error("Error subscribing to MailerLite:", error)
throw error
}

return data
} catch (error: any) {
console.error("Error subscribing to MailerLite:", error)
throw error
}
}

return { subscribeToMailerLite }
}
86 changes: 86 additions & 0 deletions supabase/functions/subscribe-to-mailerlite/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts"

const MAILERLITE_API_KEY = Deno.env.get('MAILERLITE_API_KEY')

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

interface SubscribeRequest {
email: string
firstName: string
teachingLevel?: string
}

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

try {
const { email, firstName, teachingLevel } = await req.json() as SubscribeRequest

console.log('Subscribing to MailerLite:', { email, firstName, teachingLevel })

if (!MAILERLITE_API_KEY) {
throw new Error('MAILERLITE_API_KEY is not configured')
}

const response = await fetch('https://connect.mailerlite.com/api/subscribers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${MAILERLITE_API_KEY}`,
},
body: JSON.stringify({
email,
fields: {
name: firstName,
teaching_level: teachingLevel || '',
},
groups: ['101841124559586439'] // ID du groupe "Waitlist" dans MailerLite
}),
})

const data = await response.json()

if (!response.ok) {
console.error('MailerLite API error:', data)

// Si l'email existe déjà
if (response.status === 409) {
return new Response(
JSON.stringify({ error: 'Cette adresse email est déjà inscrite.' }),
{
status: 409,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
}
)
}

throw new Error(data.message || 'Erreur lors de l\'inscription à la newsletter')
}

console.log('Successfully subscribed to MailerLite:', data)

return new Response(
JSON.stringify({ success: true, data }),
{ headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
)

} catch (error) {
console.error('Error in subscribe-to-mailerlite function:', error)
return new Response(
JSON.stringify({
error: error.message || 'Une erreur est survenue lors de l\'inscription'
}),
{
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' }
}
)
}
})

0 comments on commit ba38816

Please sign in to comment.