- Fix consulting history to show continuous time range (09:00 - 11:00) instead of listing individual slots - Add foreign key relationships for consulting_slots (order_id and user_id) - Fix handle-order-paid to query profiles(email, name) instead of full_name - Add completed consulting sessions with recordings to Member Access page - Add user_id foreign key constraint to consulting_slots table - Add orders foreign key constraint for consulting_slots relationship 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
149 lines
5.3 KiB
TypeScript
149 lines
5.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, user_id, total_amount")
|
|
.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(),
|
|
// 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, "- Calling handle-order-paid");
|
|
|
|
// Call handle-order-paid edge function directly to process the order
|
|
try {
|
|
const handlePaidUrl = `${SUPABASE_URL}/functions/v1/handle-order-paid`;
|
|
await fetch(handlePaidUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${PAKASIR_WEBHOOK_SECRET || 'anonymous'}`,
|
|
},
|
|
body: JSON.stringify({
|
|
order_id: order.id,
|
|
user_id: order.user_id,
|
|
total_amount: order.total_amount,
|
|
payment_method: payload.payment_method || "unknown",
|
|
payment_provider: "pakasir",
|
|
}),
|
|
});
|
|
console.log("[WEBHOOK] Called handle-order-paid successfully");
|
|
} catch (error) {
|
|
console.error("[WEBHOOK] Failed to call handle-order-paid:", error);
|
|
// Don't fail the webhook response if handle-order-paid fails
|
|
}
|
|
|
|
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" },
|
|
});
|
|
}
|
|
});
|