87 lines
2.8 KiB
TypeScript
87 lines
2.8 KiB
TypeScript
// routes/api/create/payment_method.ts
|
|
import { define } from "../../../utils.ts";
|
|
import { createPaymentMethod } from "../../../services/paymentService.ts";
|
|
import { SessionCookie } from "../../auth/callback.ts";
|
|
|
|
export const handler = define.handlers({
|
|
async POST(ctx) {
|
|
try {
|
|
const stateData: SessionCookie = ctx.state.data;
|
|
const { user_id } = stateData;
|
|
|
|
const contentType = ctx.req.headers.get("content-type") || "";
|
|
let data: Record<string, string | boolean> = {};
|
|
let sender: string | null = null;
|
|
let isJsonRequest = false;
|
|
|
|
// Handle both JSON and form data
|
|
if (contentType.includes("application/json")) {
|
|
isJsonRequest = true;
|
|
const jsonData = await ctx.req.json();
|
|
data = jsonData;
|
|
} else {
|
|
const formData = await ctx.req.formData();
|
|
sender = formData.get("sender")?.toString() || null;
|
|
|
|
data = {
|
|
bank_name: formData.get("bank_name")?.toString() || "",
|
|
account_type: formData.get("account_type")?.toString() || "",
|
|
routing_number_encrypted:
|
|
formData.get("routing_number_encrypted")?.toString() || "",
|
|
account_number_encrypted:
|
|
formData.get("account_number_encrypted")?.toString() || "",
|
|
is_default: formData.get("is_default") === "true",
|
|
};
|
|
}
|
|
|
|
const bank_name = data.bank_name as string;
|
|
const account_type = data.account_type as string;
|
|
const routing_number_encrypted = data.routing_number_encrypted as string;
|
|
const account_number_encrypted = data.account_number_encrypted as string;
|
|
const is_default = data.is_default as boolean || false;
|
|
|
|
const result = await createPaymentMethod(
|
|
user_id,
|
|
bank_name,
|
|
"",
|
|
account_type,
|
|
routing_number_encrypted,
|
|
account_number_encrypted,
|
|
is_default,
|
|
);
|
|
|
|
// Return appropriate response based on request type
|
|
if (isJsonRequest) {
|
|
return new Response(
|
|
JSON.stringify({
|
|
success: true,
|
|
payment_method: result[0],
|
|
}),
|
|
{
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
},
|
|
);
|
|
} else {
|
|
// Redirect back to the sender URL
|
|
const senderPath = sender?.toString() || "/";
|
|
let redirectUrl = senderPath;
|
|
try {
|
|
if (senderPath.startsWith("/")) {
|
|
const url = new URL(ctx.req.url);
|
|
redirectUrl = url.origin + senderPath;
|
|
}
|
|
} catch (_) {
|
|
// fallback: just use senderPath
|
|
}
|
|
return Response.redirect(redirectUrl, 303);
|
|
}
|
|
} catch (e) {
|
|
return new Response(JSON.stringify({ error: e }), {
|
|
status: 500,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
},
|
|
});
|