Landing/src/pages/api/subscribe.ts
Sergejs Kozinecs 691be8ca12 WIP: Cleaning
2026-07-29 14:30:08 +03:00

61 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { APIRoute } from "astro";
// Говорим Astro, что этот эндпоинт НЕ должен пререндериться в статику
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
try {
const data = await request.json();
const { email, name, phone } = data;
if (!email) {
return new Response(JSON.stringify({ message: "Email required" }), {
status: 400,
});
}
const listmonkUrl = import.meta.env.LISTMONK_URL;
const username = import.meta.env.LISTMONK_USER;
const password = import.meta.env.LISTMONK_PASS;
const authHeader =
"Basic " + Buffer.from(`${username}:${password}`).toString("base64");
const response = await fetch(`${listmonkUrl}/api/subscribers`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: authHeader,
},
body: JSON.stringify({
email: email,
name: name || "",
status: "enabled",
lists: [6], // Ваш ID 6
attribs: {
phone: phone || "",
},
}),
});
const resData = await response.json();
if (!response.ok) {
return new Response(
JSON.stringify({ message: resData.message || "Error subscribing" }),
{
status: response.status,
},
);
}
return new Response(JSON.stringify({ success: true, data: resData }), {
status: 200,
});
} catch (error: any) {
return new Response(
JSON.stringify({ message: error.message || "Server error" }),
{ status: 500 },
);
}
};