-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhooks.ts
104 lines (86 loc) · 2.68 KB
/
webhooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import express from "express";
import { WebhookRequest } from "./server";
import { stripe } from "./lib/stripe";
import { getPayloadClient } from "./get-payload";
import { Product } from "./payload-types";
import type Stripe from "stripe";
import { Resend } from "resend";
import { ReceiptEmailHtml } from "./components/emails/ReceiptEmail";
export const stripeWebhookHandler = async (req: express.Request, res: express.Response) => {
// Validate that request only comes from strip
// update _isPaid field for the order
// send receipt email
const resend = new Resend(process.env.RESEND_API_KEY);
const webhookRequest = req as any as WebhookRequest;
const body = webhookRequest.rawBody;
const signature = req.headers["stripe-signature"] || "";
let event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET || ""
);
} catch (err) {
return res
.status(400)
.send(`Webhook Error: ${err instanceof Error ? err.message : "Unknown Error"}`);
}
const session = event.data.object as Stripe.Checkout.Session;
if (!session?.metadata?.userId || !session?.metadata?.orderId) {
return res.status(400).send(`Webhook Error: No user present in metadata`);
}
if (event.type === "checkout.session.completed") {
const payload = await getPayloadClient();
const { docs: users } = await payload.find({
collection: "users",
where: {
id: {
equals: session.metadata.userId,
},
},
});
const [user] = users;
if (!user) return res.status(404).json({ error: "No such user exists." });
const { docs: orders } = await payload.find({
collection: "orders",
depth: 2,
where: {
id: {
equals: session.metadata.orderId,
},
},
});
const [order] = orders;
if (!order) return res.status(404).json({ error: "No such order exists." });
await payload.update({
collection: "orders",
data: {
_isPaid: true,
},
where: {
id: {
equals: session.metadata.orderId,
},
},
});
// send receipt
try {
const data = await resend.emails.send({
from: "DigitalHippo <[email protected]>",
to: [user.email],
subject: "Thanks for your order! This is your receipt.",
html: ReceiptEmailHtml({
date: new Date(),
email: user.email,
orderId: session.metadata.orderId,
products: order.products as Product[],
}),
});
res.status(200).json({ data });
} catch (error) {
res.status(500).json({ error });
}
}
return res.status(200).send();
};