import { serve } from "https://deno.land/std@0.190.0/http/server.ts"; import { createClient } from "https://esm.sh/@supabase/supabase-js@2.49.1"; const corsHeaders = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type, x-pakasir-signature, x-callback-token", }; // TODO: Set these in your Supabase Edge Function secrets 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")!; // Email template placeholder - will be replaced with real provider later const ORDER_PAID_EMAIL_TEMPLATE = Deno.env.get("ORDER_PAID_EMAIL_TEMPLATE") || JSON.stringify({ subject: "Pembayaran Berhasil - {{order_id}}", body: "Terima kasih! Pembayaran untuk pesanan {{order_id}} sebesar Rp {{amount}} telah berhasil. Anda sekarang memiliki akses ke: {{products}}." }); interface PakasirWebhookPayload { amount: number; order_id: string; project: string; status: string; payment_method?: string; completed_at?: string; } // Placeholder email function - logs for now, will be replaced with real provider async function sendOrderPaidEmail( userEmail: string, order: { id: string; total_amount: number }, products: string[] ): Promise { try { const template = JSON.parse(ORDER_PAID_EMAIL_TEMPLATE); const subject = template.subject .replace("{{order_id}}", order.id.substring(0, 8)) .replace("{{amount}}", order.total_amount.toLocaleString("id-ID")); const body = template.body .replace("{{order_id}}", order.id.substring(0, 8)) .replace("{{amount}}", order.total_amount.toLocaleString("id-ID")) .replace("{{products}}", products.join(", ")); console.log("[EMAIL] Would send to:", userEmail); console.log("[EMAIL] Subject:", subject); console.log("[EMAIL] Body:", body); // TODO: Replace with actual email provider call (e.g., Resend, SendGrid) // await emailProvider.send({ to: userEmail, subject, body }); } catch (error) { console.error("[EMAIL] Error preparing email:", error); } } 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, user_id, total_amount, 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 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(), }) .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); // Get order items to grant access const { data: orderItems, error: itemsError } = await supabase .from("order_items") .select("product_id, product:products(title)") .eq("order_id", order.id); if (itemsError) { console.error("[WEBHOOK] Failed to fetch order items:", itemsError); } const productTitles: string[] = []; // Grant user_access for each product if (orderItems && orderItems.length > 0) { for (const item of orderItems) { const productId = item.product_id; // Supabase joins can return array or single object depending on relationship const productData = Array.isArray(item.product) ? item.product[0] : item.product; // Check if access already exists const { data: existingAccess } = await supabase .from("user_access") .select("id") .eq("user_id", order.user_id) .eq("product_id", productId) .maybeSingle(); if (!existingAccess) { const { error: accessError } = await supabase .from("user_access") .insert({ user_id: order.user_id, product_id: productId, }); if (accessError) { console.error("[WEBHOOK] Failed to grant access for product:", productId, accessError); } else { console.log("[WEBHOOK] Granted access for product:", productId); } } if (productData?.title) { productTitles.push(productData.title); } } } // Get user email for notification const { data: profile } = await supabase .from("profiles") .select("email") .eq("id", order.user_id) .single(); // Send email notification (placeholder) if (profile?.email) { await sendOrderPaidEmail(profile.email, order, productTitles); } 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" }, }); } });