Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

wip handle charge succeed

Kiran Kae93c931af14
diff --git a/apps/web/app/api/(campaign)/stripe-app/webhook/route.ts b/apps/web/app/api/(campaign)/stripe-app/webhook/route.ts
index ed731d0b8d..f6ed30542f 100644
--- a/apps/web/app/api/(campaign)/stripe-app/webhook/route.ts
+++ b/apps/web/app/api/(campaign)/stripe-app/webhook/route.ts
@@ -1,21 +1,83 @@
import { stripe } from "@/lib/stripe";
+import { getClickEvent, recordConversion } from "@/lib/tinybird";
+import type Stripe from "stripe";
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
+// "customer.created"
+const SUPPORTED_STRIPE_EVENTS = ["charge.succeeded"];
+
export const POST = async (req: Request) => {
const buf = await req.text();
- const sig = req.headers.get("Stripe-Signature") as string;
+ const sig = req.headers.get("Stripe-Signature");
- if (!sig || !webhookSecret) return;
+ if (!sig || !webhookSecret) {
+ return new Response("Invalid request", {
+ status: 400,
+ });
+ }
try {
const event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
- console.log(event);
+
+ if (!SUPPORTED_STRIPE_EVENTS.includes(event.type)) {
+ // Ignore unsupported events
+ return new Response("OK", {
+ status: 200,
+ });
+ }
+
+ switch (event.type) {
+ case "charge.succeeded":
+ await handleChargeSucceeded(event);
+ break;
+ }
+
+ return new Response("OK", {
+ status: 200,
+ });
} catch (error: any) {
console.log("Stripe webhook error:", error);
}
+};
+
+// Handle the "charge.succeeded" event
+async function handleChargeSucceeded(event: Stripe.Event) {
+ const charge = event.data.object as Stripe.Charge;
+
+ console.log("event", charge);
+
+ if (!charge.customer) {
+ return;
+ }
- return new Response("OK", {
- status: 200,
+ // Find customer details using charge.customer
+ const customer = (await stripe.customers.retrieve(
+ charge.customer as string,
+ )) as Stripe.Customer;
+ const customerKey = customer.metadata?.customerKey || null;
+
+ if (!customerKey) {
+ return;
+ }
+
+ console.log("customer", customer);
+
+ // Check customerKey exists in TB
+
+ // TODO: Update clickId
+ const clickEvent = await getClickEvent({ clickId: "jlNZlZKVa2X6ZCcZ" });
+
+ if (!clickEvent || clickEvent.data.length === 0) {
+ return;
+ }
+
+ await recordConversion({
+ ...clickEvent.data[0],
+ metadata: "",
+ customer_key: customerKey,
+ event_name: "",
+ event_type: "sale",
+ timestamp: new Date(Date.now()).toISOString(),
});
-};
+}