// Create a Helcim customer import jwt from 'jsonwebtoken' import Member from '../../models/member.js' import { connectDB } from '../../utils/mongoose.js' const HELCIM_API_BASE = 'https://api.helcim.com/v2' export default defineEventHandler(async (event) => { try { await connectDB() const config = useRuntimeConfig(event) const body = await readBody(event) // Validate required fields if (!body.name || !body.email) { throw createError({ statusCode: 400, statusMessage: 'Name and email are required' }) } // Check if member already exists const existingMember = await Member.findOne({ email: body.email }) if (existingMember) { throw createError({ statusCode: 409, statusMessage: 'A member with this email already exists' }) } // Get token directly from environment if not in config const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN if (!helcimToken) { throw createError({ statusCode: 500, statusMessage: 'Helcim API token not configured' }) } // Debug: Log token (first few chars only) console.log('Using Helcim token:', helcimToken.substring(0, 10) + '...') // Test the connection first with native fetch try { const testResponse = await fetch('https://api.helcim.com/v2/connection-test', { method: 'GET', headers: { 'accept': 'application/json', 'api-token': helcimToken } }) if (!testResponse.ok) { throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`) } const testData = await testResponse.json() console.log('Connection test passed:', testData) } catch (testError) { console.error('Connection test failed:', testError) throw createError({ statusCode: 401, statusMessage: `Helcim API connection failed: ${testError.message}` }) } // Create customer in Helcim using native fetch const customerResponse = await fetch(`${HELCIM_API_BASE}/customers`, { method: 'POST', headers: { 'accept': 'application/json', 'content-type': 'application/json', 'api-token': helcimToken }, body: JSON.stringify({ customerType: 'PERSON', contactName: body.name, email: body.email }) }) if (!customerResponse.ok) { const errorText = await customerResponse.text() console.error('Customer creation failed:', customerResponse.status, errorText) throw createError({ statusCode: customerResponse.status, statusMessage: `Failed to create customer: ${errorText}` }) } const customerData = await customerResponse.json() // Create member in database const member = await Member.create({ email: body.email, name: body.name, circle: body.circle, contributionTier: body.contributionTier, helcimCustomerId: customerData.id, status: 'pending_payment' }) // Generate JWT token for the session const token = jwt.sign( { memberId: member._id, email: body.email, helcimCustomerId: customerData.id }, process.env.JWT_SECRET, { expiresIn: '24h' } ) // Set the session cookie server-side console.log('Setting auth-token cookie for member:', member.email) console.log('NODE_ENV:', process.env.NODE_ENV) setCookie(event, 'auth-token', token, { httpOnly: true, // Server-only for security secure: false, // Don't require HTTPS in development sameSite: 'lax', maxAge: 60 * 60 * 24, // 24 hours path: '/', domain: undefined // Let browser set domain automatically }) console.log('Cookie set successfully') return { success: true, customerId: customerData.id, customerCode: customerData.customerCode, token, member: { id: member._id, email: member.email, name: member.name, circle: member.circle, contributionTier: member.contributionTier, status: member.status } } } catch (error) { console.error('Error creating Helcim customer:', error) throw createError({ statusCode: error.statusCode || 500, statusMessage: error.message || 'Failed to create customer' }) } })