Edge Functions

Handling Stripe Webhooks


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

1
// Follow this setup guide to integrate the Deno language server with your editor:
2
// https://deno.land/manual/getting_started/setup_your_environment
3
// This enables autocomplete, go to definition, etc.
4
5
// Import via bare specifier thanks to the import_map.json file.
6
import Stripe from 'https://esm.sh/stripe@14?target=denonext'
7
8
const stripe = new Stripe(Deno.env.get('STRIPE_API_KEY') as string, {
9
// This is needed to use the Fetch API rather than relying on the Node http
10
// package.
11
apiVersion: '2024-11-20'
12
})
13
// This is needed in order to use the Web Crypto API in Deno.
14
const cryptoProvider = Stripe.createSubtleCryptoProvider()
15
16
console.log('Hello from Stripe Webhook!')
17
18
Deno.serve(async (request) => {
19
const signature = request.headers.get('Stripe-Signature')
20
21
// First step is to verify the event. The .text() method must be used as the
22
// verification relies on the raw request body rather than the parsed JSON.
23
const body = await request.text()
24
let receivedEvent
25
try {
26
receivedEvent = await stripe.webhooks.constructEventAsync(
27
body,
28
signature!,
29
Deno.env.get('STRIPE_WEBHOOK_SIGNING_SECRET')!,
30
undefined,
31
cryptoProvider
32
)
33
} catch (err) {
34
return new Response(err.message, { status: 400 })
35
}
36
console.log(`🔔 Event received: ${receivedEvent.id}`)
37
return new Response(JSON.stringify({ ok: true }), { status: 200 })
38
});
View source