68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
|
|
export async function POST(req: Request) {
|
|
try {
|
|
const apiKey = process.env.KLAVIYO_PRIVATE_API_KEY;
|
|
if (!apiKey) {
|
|
return NextResponse.json(
|
|
{ error: "Klaviyo not configured." },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
const body = await req.json();
|
|
const { email, eventName, properties } = body;
|
|
if (!email || !eventName) {
|
|
return NextResponse.json(
|
|
{ error: "email and eventName are required." },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const res = await fetch("https://a.klaviyo.com/api/events/", {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Klaviyo-API-Key ${apiKey}`,
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json",
|
|
Revision: "2024-02-15",
|
|
},
|
|
body: JSON.stringify({
|
|
data: {
|
|
type: "event",
|
|
attributes: {
|
|
profile: {
|
|
data: {
|
|
type: "profile",
|
|
attributes: { email },
|
|
},
|
|
},
|
|
metric: {
|
|
data: {
|
|
type: "metric",
|
|
attributes: { name: eventName },
|
|
},
|
|
},
|
|
properties: properties || {},
|
|
},
|
|
},
|
|
}),
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (!res.ok) {
|
|
return NextResponse.json(
|
|
{ error: data?.errors?.[0]?.detail || "Klaviyo error." },
|
|
{ status: res.status }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json({ event: data.data });
|
|
} catch (err: any) {
|
|
return NextResponse.json(
|
|
{ error: err?.message || "Klaviyo event failed." },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|