-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathroute.ts
More file actions
73 lines (65 loc) · 2.25 KB
/
Copy pathroute.ts
File metadata and controls
73 lines (65 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { NextRequest } from "next/server";
/**
* Receives lead-capture answers from the V3LeadCapture block and forwards them
* to JotForm's submissions API, keeping the API key server-side.
*
* Body: { jotFormId: string, fields: Record<qid, value> }
* Each `fields` key is a JotForm question id (qid); JotForm expects them encoded
* as `submission[{qid}]=value`. An array value is a multi-option field, encoded
* as `submission[{qid}][{index}]=value` (e.g. location → country + state).
*/
export async function POST(request: NextRequest) {
try {
const apiKey = process.env.JOTFORM_API_KEY;
if (!apiKey) {
return Response.json(
{ message: "JotForm is not configured." },
{ status: 500 }
);
}
const { jotFormId, fields } = await request.json();
if (!jotFormId || !fields || typeof fields !== "object") {
return Response.json(
{ message: "Missing jotFormId or fields." },
{ status: 400 }
);
}
const body = new URLSearchParams();
for (const [qid, value] of Object.entries(fields)) {
if (Array.isArray(value)) {
value.forEach((entry, index) => {
if (entry != null && entry !== "") {
body.append(`submission[${qid}][${index}]`, String(entry));
}
});
} else if (value != null && value !== "") {
body.append(`submission[${qid}]`, String(value));
}
}
const res = await fetch(
`https://api.jotform.com/form/${encodeURIComponent(
jotFormId
)}/submissions?apiKey=${encodeURIComponent(apiKey)}`,
{
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
}
);
if (!res.ok) {
const detail = await res.text();
console.error("JotForm submission failed:", res.status, detail);
return Response.json(
{ message: "Failed to submit lead." },
{ status: 502 }
);
}
return Response.json({ ok: true }, { status: 200 });
} catch (error) {
console.error("lead-capture error:", error);
return Response.json({ message: "Unexpected error." }, { status: 500 });
}
}
export async function GET() {
return Response.json({ message: "Unsupported method" }, { status: 405 });
}