Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save dexit/b8873b4bf0a783b902bcfd7d1dfb36f7 to your computer and use it in GitHub Desktop.

Select an option

Save dexit/b8873b4bf0a783b902bcfd7d1dfb36f7 to your computer and use it in GitHub Desktop.
supabase-hubspot-hmac-webhook-edge-function-deno.ts Explanation: The function checks if payload.events is an array before attempting to loop through it. This ensures that it only processes events if they exist. For each event in the events array, it logs the event details into the webhook_logs table. If there are no events found in the payload, …
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createHmac } from "node:crypto";
import { createClient } from "jsr:@supabase/supabase-js";
Deno.serve(async (req: Request) => {
const secret = Deno.env.get("HUBSPOT_SECRET")!;
const signature = req.headers.get("x-hub-signature")!;
const body = await req.text();
const hmac = createHmac("sha256", secret).update(body).digest("hex");
if (hmac !== signature) {
return new Response("Unauthorized", { status: 401 });
}
const payload = JSON.parse(body);
const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
// Check if events exist in the payload
if (Array.isArray(payload.events)) {
for (const event of payload.events) {
console.log("Processing event:", event);
// Log the event to the webhook_logs table
const { error } = await supabase
.from("webhook_logs")
.insert([
{
subscription_id: event.subscriptionId,
event_id: event.eventId,
portal_id: event.portalId,
app_id: event.appId,
occurred_at: event.occurredAt,
subscription_type: event.subscriptionType,
attempt_number: event.attemptNumber,
object_id: event.objectId,
propertyname: event.propertyName,
propertyvalue: event.propertyValue,
change_source: event.changeSource,
source_id: event.sourceId,
header_data: JSON.stringify(req.headers),
body_data: body,
response: null,
response_code: null,
error: null,
signature_data: signature,
},
]);
if (error) {
console.error("Error logging event:", error);
}
}
} else {
console.warn("No events found in the payload.");
}
return new Response(null, { status: 204 });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment