BREAKING CHANGE: Complete refactor of payment handling New Architecture: 1. pakasir-webhook (120 lines -> was 535 lines) - Only verifies signature and updates order status - Removed: SMTP, email templates, notification logic 2. Database Trigger (NEW) - Automatically fires when payment_status = 'paid' - Calls handle-order-paid edge function - Works for webhook AND manual admin updates 3. handle-order-paid (NEW edge function) - Grants user access for products - Creates Google Meet events for consulting - Sends notifications via send-email-v2 - Triggers webhooks Benefits: - Single Responsibility: Each function has one clear purpose - Trigger works for both webhook and manual admin actions - Easier to debug and maintain - Reusable notification system Migration required: Run 20241223_payment_trigger.sql 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
123 lines
4.3 KiB
TypeScript
123 lines
4.3 KiB
TypeScript
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(),
|
|
})
|
|
.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" },
|
|
});
|
|
}
|
|
});
|