McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Handle Paystack Webhooks in Supabase Edge Functions
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 22, 2026

Handle Paystack Webhooks in Supabase Edge Functions

Create a Supabase Edge Function at supabase/functions/webhook/index.ts. Read the raw body with await req.text(), compute HMAC SHA512 using crypto.subtle with your PAYSTACK_SECRET_KEY from Deno.env, compare against the x-paystack-signature header, return 200 immediately, then update your Supabase database with the service role key.

In this article

  1. 1. Webhook Edge Function
  2. 2. Setup and Deploy
  3. 3. Learn More

Webhook Edge Function

// supabase/functions/webhook/index.ts
import { serve } from "https://deno.land/std@0.208.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

async function verifyPaystackSignature(
  body: string,
  signature: string,
  secretKey: string
): Promise<boolean> {
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(secretKey),
    { name: "HMAC", hash: "SHA-512" },
    false,
    ["sign"]
  );

  const sig = await crypto.subtle.sign(
    "HMAC",
    key,
    new TextEncoder().encode(body)
  );

  const hash = Array.from(new Uint8Array(sig))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");

  return hash === signature;
}

serve(async (req) => {
  if (req.method !== "POST") {
    return new Response("Method not allowed", { status: 405 });
  }

  const signature = req.headers.get("x-paystack-signature") ?? "";
  const secretKey = Deno.env.get("PAYSTACK_SECRET_KEY") ?? "";

  // Read raw body before parsing
  const body = await req.text();

  const valid = await verifyPaystackSignature(body, signature, secretKey);
  if (!valid) {
    return new Response("Invalid signature", { status: 400 });
  }

  // Return 200 immediately — Paystack retries on slow responses
  const response = new Response("ok", { status: 200 });

  // Parse and process after returning
  const event = JSON.parse(body);

  const supabase = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
  );

  // Idempotency: skip if already processed
  const { data: existing } = await supabase
    .from("webhook_events")
    .select("id")
    .eq("event_id", event.data?.id)
    .maybeSingle();

  if (existing) return response;

  if (event.event === "charge.success") {
    const reference = event.data.reference;
    const amount = event.data.amount / 100;

    await supabase
      .from("orders")
      .update({
        status: "paid",
        paid_at: new Date().toISOString(),
        amount_paid: amount,
      })
      .eq("reference", reference);
  }

  if (event.event === "transfer.success") {
    const transferCode = event.data.transfer_code;
    await supabase
      .from("transfers")
      .update({ status: "success" })
      .eq("transfer_code", transferCode);
  }

  // Record processed event
  await supabase.from("webhook_events").insert({
    event_id: event.data?.id,
    event_type: event.event,
    processed_at: new Date().toISOString(),
  });

  return response;
});

Setup and Deploy

# Create the function
supabase functions new webhook

# Set your Paystack secret key
supabase secrets set PAYSTACK_SECRET_KEY=sk_live_xxxxxxxxxxxx

# Deploy
supabase functions deploy webhook

After deploying, set the webhook URL in your Paystack dashboard:

https://<your-project-ref>.supabase.co/functions/v1/webhook

Create the idempotency table in Supabase:

create table webhook_events (
  id uuid default gen_random_uuid() primary key,
  event_id text unique not null,
  event_type text not null,
  processed_at timestamptz not null
);

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Learn More

This guide is part of the Paystack integration guides by language and framework series.

Next: Build Paystack Subscriptions in Supabase Edge Functions

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Use crypto.subtle (Web Crypto API) to compute HMAC SHA512 in Deno. Node.js crypto is not available.
  • ✓Read the raw request body with await req.text() before parsing JSON, so the signature check is accurate.
  • ✓Return 200 to Paystack before updating your database. Long-running responses cause Paystack to retry.
  • ✓Use the Supabase service role key to bypass RLS when updating the database from a webhook handler.
  • ✓Store processed event IDs in a webhooks_processed table to prevent double-handling retries.
  • ✓Deploy with: supabase functions deploy webhook. Set the URL as your Paystack webhook endpoint.

Frequently Asked Questions

Why use crypto.subtle instead of Node.js crypto in Supabase Edge Functions?
Supabase Edge Functions run Deno, not Node.js. The Node.js crypto module is not available. Deno provides the Web Crypto API (crypto.subtle) which is the standard web platform API for cryptographic operations including HMAC SHA512.
How do I read the raw request body for signature verification in Deno?
Use await req.text() to read the body as a string before calling JSON.parse(). If you call req.json() first, the body stream is consumed and you cannot read it again. Always read raw text first, then parse manually.
Can Supabase Edge Functions receive Paystack webhooks without authentication?
Yes. Webhook endpoints should be publicly accessible — Paystack does not send auth headers that match Supabase anon/service keys. Use the x-paystack-signature HMAC check as your authentication mechanism. Do not require JWT tokens on webhook functions.
How do I test Paystack webhooks locally with Supabase Edge Functions?
Run supabase functions serve webhook. Expose it with ngrok: ngrok http 54321. Then use the Paystack webhook simulator in the dashboard or send a test POST with curl. Your Edge Function must be running locally and the ngrok URL must be reachable.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Supabase Edge Functions

Supabase Edge Functions run Deno TypeScript at the edge. Use them as your Paystack backend to initialize transactions, verify payments, and handle webhooks without deploying a separate server.

Read more

Verify Paystack Payments in Supabase Edge Functions

Verify Paystack payments using Supabase Edge Functions written in Deno TypeScript. This guide covers calling the verify endpoint, validating amounts, updating your Supabase database after confirmation, and calling the function from your frontend.

Read more

Build Paystack Subscriptions in Supabase Edge Functions

Add recurring billing to a Supabase project using Paystack subscriptions and Edge Functions. This guide covers creating a subscription checkout Edge Function with a plan code, handling subscription lifecycle webhooks, and querying subscription status from the database.

Read more

Idempotent Paystack Webhook Handlers: The Complete Pattern

A complete guide to building idempotent Paystack webhook handlers. Covers why Paystack sends duplicate events, using transaction references as idempotency keys, database-level deduplication with a processed_events table, and the full production-ready pattern in Node.js.

Read more

Why You Must Return 200 Immediately from a Paystack Webhook

The number one Paystack webhook reliability rule: return 200 before doing anything else. This guide explains why Paystack has a timeout, what happens when you break the rule, and how to implement the respond-first-then-queue pattern in Node.js.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.