import { waitUntil } from "@vercel/functions";
import { makeWebhookValidator } from "@whop/api";
import type { NextRequest } from "next/server";
// Initialize webhook validator with your webhook secret
const validateWebhook = makeWebhookValidator({
webhookSecret: process.env.WHOP_WEBHOOK_SECRET ?? "fallback",
});
// Handle webhook events
export async function POST(request: NextRequest): Promise<Response> {
try {
// Validate the webhook signature
const webhookData = await validateWebhook(request);
// Handle different webhook events
switch (webhookData.action) {
case "payment.succeeded":
const { id, final_amount, amount_after_fees, currency, user_id } =
webhookData.data;
// Process the successful payment
waitUntil(
handlePaymentSuccess(
user_id,
final_amount,
currency,
amount_after_fees
)
);
break;
case "payment.failed":
const { error, user_id: failedUserId } = webhookData.data;
waitUntil(handlePaymentFailure(failedUserId, error));
break;
// Add more webhook event handlers as needed
}
return new Response("OK", { status: 200 });
} catch (error) {
console.error("Webhook processing failed:", error);
return new Response("Webhook validation failed", { status: 400 });
}
}
// Handle successful payments
async function handlePaymentSuccess(
userId: string,
amount: number,
currency: string,
amountAfterFees: number
) {
try {
// Update your database
// Grant access to premium features
// Send confirmation email
// etc.
} catch (error) {
console.error("Failed to process successful payment:", error);
}
}
// Handle failed payments
async function handlePaymentFailure(userId: string, error: any) {
try {
// Update your database
// Notify the user
// etc.
} catch (error) {
console.error("Failed to process payment failure:", error);
}
}