Edge Functions

Handling Stripe Webhooks


Handling signed Stripe Webhooks with Edge Functions. View on GitHub.

index.ts

_38
// Follow this setup guide to integrate the Deno language server with your editor:
_38
// https://deno.land/manual/getting_started/setup_your_environment
_38
// This enables autocomplete, go to definition, etc.
_38
_38
// Import via bare specifier thanks to the import_map.json file.
_38
import Stripe from 'https://esm.sh/stripe@14?target=denonext'
_38
_38
const stripe = new Stripe(Deno.env.get('STRIPE_API_KEY') as string, {
_38
// This is needed to use the Fetch API rather than relying on the Node http
_38
// package.
_38
apiVersion: '2024-11-20'
_38
})
_38
// This is needed in order to use the Web Crypto API in Deno.
_38
const cryptoProvider = Stripe.createSubtleCryptoProvider()
_38
_38
console.log('Hello from Stripe Webhook!')
_38
_38
Deno.serve(async (request) => {
_38
const signature = request.headers.get('Stripe-Signature')
_38
_38
// First step is to verify the event. The .text() method must be used as the
_38
// verification relies on the raw request body rather than the parsed JSON.
_38
const body = await request.text()
_38
let receivedEvent
_38
try {
_38
receivedEvent = await stripe.webhooks.constructEventAsync(
_38
body,
_38
signature!,
_38
Deno.env.get('STRIPE_WEBHOOK_SIGNING_SECRET')!,
_38
undefined,
_38
cryptoProvider
_38
)
_38
} catch (err) {
_38
return new Response(err.message, { status: 400 })
_38
}
_38
console.log(`🔔 Event received: ${receivedEvent.id}`)
_38
return new Response(JSON.stringify({ ok: true }), { status: 200 })
_38
});

View source