import { serve } from "https://deno.land/std@0.190.0/http/server.ts"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2"; const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-pakasir-signature, x-callback-token", }; // Environment variables const PAKASIR_WEBHOOK_SECRET = Deno.env.get("PAKASIR_WEBHOOK_SECRET") || ""; const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!; const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!; interface PakasirWebhookPayload { amount: number; order_id: string; project: string; status: string; payment_method?: string; completed_at?: string; } serve(async (req) => { // Handle CORS preflight if (req.method === "OPTIONS") { return new Response(null, { headers: corsHeaders }); } try { // Verify webhook signature if configured const signature = req.headers.get("x-pakasir-signature") || req.headers.get("x-callback-token") || ""; if (PAKASIR_WEBHOOK_SECRET && signature !== PAKASIR_WEBHOOK_SECRET) { console.error("[WEBHOOK] Invalid signature"); return new Response(JSON.stringify({ error: "Invalid signature" }), { status: 401, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } const payload: PakasirWebhookPayload = await req.json(); console.log("[WEBHOOK] Received payload:", JSON.stringify(payload)); // Validate required fields if (!payload.order_id || !payload.status) { console.error("[WEBHOOK] Missing required fields"); return new Response(JSON.stringify({ error: "Missing required fields" }), { status: 400, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } // Only process completed payments if (payload.status !== "completed") { console.log("[WEBHOOK] Ignoring non-completed status:", payload.status); return new Response(JSON.stringify({ message: "Status not completed, ignored" }), { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } // Create Supabase client with service role for admin access const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY); // Find the order by payment_reference or id const { data: order, error: orderError } = await supabase .from("orders") .select("id, payment_status") .or(`payment_reference.eq.${payload.order_id},id.eq.${payload.order_id}`) .single(); if (orderError || !order) { console.error("[WEBHOOK] Order not found:", payload.order_id, orderError); return new Response(JSON.stringify({ error: "Order not found" }), { status: 404, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } // Skip if already paid if (order.payment_status === "paid") { console.log("[WEBHOOK] Order already paid:", order.id); return new Response(JSON.stringify({ message: "Order already paid" }), { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } // Update order status - this will trigger the database trigger const { error: updateError } = await supabase .from("orders") .update({ payment_status: "paid", status: "paid", payment_provider: "pakasir", payment_method: payload.payment_method || "unknown", updated_at: new Date().toISOString(), // Clear QR string after payment qr_string: null, qr_expires_at: null, }) .eq("id", order.id); if (updateError) { console.error("[WEBHOOK] Failed to update order:", updateError); return new Response(JSON.stringify({ error: "Failed to update order" }), { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } console.log("[WEBHOOK] Order updated to paid:", order.id, "- Trigger will handle the rest"); return new Response(JSON.stringify({ success: true, order_id: order.id }), { status: 200, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } catch (error) { console.error("[WEBHOOK] Unexpected error:", error); return new Response(JSON.stringify({ error: "Internal server error" }), { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" }, }); } });