ghostguild-org/server/api/helcim/update-billing.post.js

71 lines
No EOL
2.1 KiB
JavaScript

// Update customer billing address
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
export default defineEventHandler(async (event) => {
try {
const config = useRuntimeConfig(event)
const body = await readBody(event)
// Validate required fields
if (!body.customerId || !body.billingAddress) {
throw createError({
statusCode: 400,
statusMessage: 'Customer ID and billing address are required'
})
}
const { billingAddress } = body
// Validate billing address fields
if (!billingAddress.street || !billingAddress.city || !billingAddress.country || !billingAddress.postalCode) {
throw createError({
statusCode: 400,
statusMessage: 'Complete billing address is required'
})
}
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
// Update customer billing address in Helcim
const response = await fetch(`${HELCIM_API_BASE}/customers/${body.customerId}`, {
method: 'PATCH',
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'api-token': helcimToken
},
body: JSON.stringify({
billingAddress: {
name: billingAddress.name,
street1: billingAddress.street,
city: billingAddress.city,
province: billingAddress.province || billingAddress.state,
country: billingAddress.country,
postalCode: billingAddress.postalCode
}
})
})
if (!response.ok) {
const errorText = await response.text()
console.error('Billing address update failed:', response.status, errorText)
throw createError({
statusCode: response.status,
statusMessage: `Failed to update billing address: ${errorText}`
})
}
const customerData = await response.json()
return {
success: true,
customer: customerData
}
} catch (error) {
console.error('Error updating billing address:', error)
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.message || 'Failed to update billing address'
})
}
})