Discord Notification for new Stripe Subscription

This endpoint gets webhooks from Stripe when we get a new subscriber to Val Town pro. It get's the customer's email address and let's the team know.

TODO

  • Send the user a thank you email from me
  • Get the user's name and val town username
  • Get a list of the user's vals
Readme
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
/** @jsxImportSource https://esm.sh/react */
import { email } from "https://esm.town/v/std/email?v=11";
import { discordWebhook } from "https://esm.town/v/stevekrouse/discordWebhook";
import { html } from "https://esm.town/v/stevekrouse/html";
import { thisValURL } from "https://esm.town/v/stevekrouse/thisValURL";
import { renderToString } from "npm:react-dom/server";
import Stripe from "npm:stripe";
const stripe = new Stripe(Deno.env.get("stripe_sk_customer_readonly") as string, {
apiVersion: "2020-08-27",
});
function getStripeCustomer(customerId) {
return stripe.customers.retrieve(customerId);
}
let welcomeEmail = renderToString(
<div style={{ maxWidth: "500px", fontFamily: "sans-serif" }}>
<p>
I just want to thank you for becoming a paying customer of Val Town. It's your support like yours that enables us to build the future of coding.
</p>
<p>If I can ever do anything for you, let me know! And if you have any feedback please send it my way.</p>
<p>Best,</p>
<p>Steve</p>
<p>Val Town | CEO</p>
<p>
ps - this email is <a href={thisValURL()}>a val</a>
</p>
</div>,
);
export let newStripeEvent = async (req: Request) => {
if (req.method === "GET") return html(welcomeEmail);
const signature = req.headers.get("Stripe-Signature");
const body = await req.text();
const webhookSecret = Deno.env.get("STRIPE_WEBHOOK_SECRET");
let event;
try {
event = await stripe.webhooks.constructEventAsync(
body,
signature,
webhookSecret,
);
} catch (err) {
return new Response(`Webhook Error: ${err.message}`, { status: 400 });
}
const customer = await getStripeCustomer(event.data.object.customer);
const customerEmail = customer.email;
discordWebhook({
url: Deno.env.get("discordUserEvents"),
content: `<@&1081224342110736394> New Subscription 🥳 ${customerEmail}`,
});
await email({
to: customerEmail,
subject: "Thank you!",
html: welcomeEmail,
from: { name: "Steve Krouse", email: "stevekrouse.company@valtown.email" },
cc: { name: "Team", email: "team@val.town" },
});
return Response.json("ok");
};
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.