Skip to content

Open source CapCut alternative.

TypeScript

feat(site): report signups and purchases to Meta

David Leaf81f485579c
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
index ea85b382..fe137eb1 100644
--- a/site/src/app/api/billing/checkout/route.ts
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { auth } from "@/lib/auth";
import { introCouponId } from "@/lib/billing/intro-offer";
import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";
+import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";
import { proPriceId } from "@/lib/billing/pro-subscription";
import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
import { contextFromRequest } from "@/lib/config/effective";
@@ -63,6 +64,7 @@ export const POST = withDonkeyAuth(async (request) => {
client_reference_id: session.user.id,
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
+ metadata: metaCheckoutMetadata(request.headers),
mode: "subscription",
subscription_data: {
metadata: {
@@ -81,5 +83,6 @@ export const POST = withDonkeyAuth(async (request) => {
);
}
+ trackCheckoutStarted(checkout.id, "Pro", request.headers, session.user);
return NextResponse.json({ url: checkout.url });
});
diff --git a/site/src/app/api/billing/credits/checkout/route.ts b/site/src/app/api/billing/credits/checkout/route.ts
index 1bf3e922..aeccd3d7 100644
--- a/site/src/app/api/billing/credits/checkout/route.ts
+++ b/site/src/app/api/billing/credits/checkout/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/lib/auth";
+import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";
import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
import { creditCountLabel, creditsPerDollar } from "@/lib/credits/format-credits";
import {
@@ -74,7 +75,7 @@ export const POST = withDonkeyAuth(async (request) => {
quantity: 1,
},
],
- metadata,
+ metadata: { ...metadata, ...metaCheckoutMetadata(request.headers) },
mode: "payment",
payment_intent_data: { metadata, setup_future_usage: "off_session" },
success_url: `${origin}/app/settings?topup=success`,
@@ -87,5 +88,6 @@ export const POST = withDonkeyAuth(async (request) => {
);
}
+ trackCheckoutStarted(checkout.id, "Credits", request.headers, session.user);
return NextResponse.json({ url: checkout.url });
});
diff --git a/site/src/app/api/billing/webhook/route.ts b/site/src/app/api/billing/webhook/route.ts
index bd7ae195..811af21a 100644
--- a/site/src/app/api/billing/webhook/route.ts
+++ b/site/src/app/api/billing/webhook/route.ts
@@ -7,6 +7,7 @@ import {
handleCreditTopUpCheckout,
handleCreditTopUpPaymentSucceeded,
} from "@/lib/billing/credit-purchases";
+import { trackCheckoutPurchase } from "@/lib/billing/meta-checkout";
import {
subscriptionIsPro,
syncProSubscription,
@@ -64,6 +65,13 @@ export async function POST(request: Request) {
// A one-time credit top-up (mode=payment) has no subscription.
await handleCreditTopUpCheckout(stripe, checkoutSession);
}
+ trackCheckoutPurchase(checkoutSession);
+ break;
+ }
+ case "checkout.session.async_payment_succeeded": {
+ // A delayed payment method settled; the credits land through
+ // payment_intent.succeeded, and the purchase is reported here.
+ trackCheckoutPurchase(event.data.object);
break;
}
case "payment_intent.succeeded": {
diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.ts
index 0b177386..d697251f 100644
--- a/site/src/lib/auth.ts
+++ b/site/src/lib/auth.ts
@@ -4,6 +4,7 @@ import { nextCookies } from "better-auth/next-js";
import { bearer } from "better-auth/plugins";
import { AUTH_COOKIE_DOMAIN, AUTH_SUBDOMAINS, DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { trackSignup } from "@/lib/meta/signup";
import { provisionSignupGrants } from "@/lib/onboarding/signup-grants";
import { prisma } from "@/lib/prisma";
import { emailPasswordDisabledPaths, emailPasswordGuard, emailPasswordOptions } from "@/lib/email-password-auth";
@@ -67,13 +68,15 @@ export const auth = betterAuth({
// creation. The request's headers carry the network the signup came
// from.
after: async (user, context) => {
+ const headers = context?.headers ?? context?.request?.headers;
await provisionSignupGrants(
{
email: user.email,
id: user.id,
},
- context?.headers ?? context?.request?.headers,
+ headers,
);
+ trackSignup(user, headers);
},
},
},
diff --git a/site/src/lib/billing/meta-checkout.ts b/site/src/lib/billing/meta-checkout.ts
new file mode 100644
index 00000000..c66748f8
--- /dev/null
+++ b/site/src/lib/billing/meta-checkout.ts
@@ -0,0 +1,84 @@
+import type Stripe from "stripe";
+
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { metaBrowser, type MetaBrowser, trackMetaEvent } from "@/lib/meta/conversions";
+
+// A purchase completes in Stripe's webhook, far from the browser that paid.
+// The checkout session carries that browser's ids, address, and user agent in
+// its metadata, and the webhook reports the purchase with them.
+
+// Stripe caps a metadata value at 500 characters.
+const STRIPE_METADATA_MAX = 500;
+
+const METADATA_KEYS = {
+ fbc: "metaFbc",
+ fbp: "metaFbp",
+ ip: "metaIp",
+ userAgent: "metaUserAgent",
+} as const satisfies Record<keyof MetaBrowser, string>;
+
+// Checkouts open from the editor and its settings; Meta needs a page on the site.
+const CHECKOUT_PAGE = `${DONKEYCUT_CANONICAL}/app/settings`;
+
+// Stripe amounts are in the currency's minor unit; Donkey charges in dollars.
+const CENTS_PER_DOLLAR = 100;
+
+// A checkout converts once it is paid, or needs no payment at all (a Pro
+// checkout under a full discount). An async method settles later, through
+// checkout.session.async_payment_succeeded.
+const CONVERTED: ReadonlySet<Stripe.Checkout.Session["payment_status"]> = new Set(["paid", "no_payment_required"]);
+
+export type CheckoutProduct = "Pro" | "Credits";
+
+/** The browser behind a checkout request, as checkout session metadata. */
+export function metaCheckoutMetadata(headers: Headers): Record<string, string> {
+ const browser = metaBrowser(headers);
+ const metadata: Record<string, string> = {};
+ for (const [field, key] of Object.entries(METADATA_KEYS)) {
+ const value = browser[field as keyof MetaBrowser];
+ if (value) {
+ metadata[key] = value.slice(0, STRIPE_METADATA_MAX);
+ }
+ }
+ return metadata;
+}
+
+/** Reports a checkout the account just opened. */
+export function trackCheckoutStarted(
+ checkoutId: string,
+ product: CheckoutProduct,
+ headers: Headers,
+ user: { id: string; email: string },
+): void {
+ trackMetaEvent({
+ browser: metaBrowser(headers),
+ content: product,
+ id: `checkout-start-${checkoutId}`,
+ name: "InitiateCheckout",
+ url: CHECKOUT_PAGE,
+ user,
+ });
+}
+
+/** Reports a paid checkout as a purchase, with the browser it opened in. */
+export function trackCheckoutPurchase(session: Stripe.Checkout.Session): void {
+ if (!CONVERTED.has(session.payment_status) || !session.client_reference_id) {
+ return;
+ }
+
+ const metadata = session.metadata ?? {};
+ trackMetaEvent({
+ browser: {
+ fbc: metadata[METADATA_KEYS.fbc],
+ fbp: metadata[METADATA_KEYS.fbp],
+ ip: metadata[METADATA_KEYS.ip],
+ userAgent: metadata[METADATA_KEYS.userAgent],
+ },
+ content: session.mode === "subscription" ? "Pro" : "Credits",
+ id: `checkout-${session.id}`,
+ name: "Purchase",
+ url: CHECKOUT_PAGE,
+ user: { email: session.customer_details?.email, id: session.client_reference_id },
+ value: { amount: (session.amount_total ?? 0) / CENTS_PER_DOLLAR, currency: session.currency ?? "usd" },
+ });
+}
diff --git a/site/src/lib/billing/webhook-events.ts b/site/src/lib/billing/webhook-events.ts
index f32a5747..45419e0b 100644
--- a/site/src/lib/billing/webhook-events.ts
+++ b/site/src/lib/billing/webhook-events.ts
@@ -1,6 +1,7 @@
// The Stripe events the webhook handles: what the endpoint in Stripe is
// subscribed to (scripts/stripe-webhook-events.ts).
export const STRIPE_WEBHOOK_EVENTS = [
+ "checkout.session.async_payment_succeeded",
"checkout.session.completed",
"customer.subscription.created",
"customer.subscription.deleted",
diff --git a/site/src/lib/meta/signup.ts b/site/src/lib/meta/signup.ts
new file mode 100644
index 00000000..5225f1f1
--- /dev/null
+++ b/site/src/lib/meta/signup.ts
@@ -0,0 +1,17 @@
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { metaBrowser, trackMetaEvent } from "@/lib/meta/conversions";
+
+// A signup finishes on the auth callback, whose address names the provider;
+// Meta gets the page it started on.
+const SIGN_UP_PAGE = `${DONKEYCUT_CANONICAL}/sign-up`;
+
+/** Reports a new account, matched through the browser that created it. */
+export function trackSignup(user: { id: string; email: string }, headers: Headers | undefined): void {
+ trackMetaEvent({
+ browser: headers ? metaBrowser(headers) : {},
+ id: `signup-${user.id}`,
+ name: "CompleteRegistration",
+ url: SIGN_UP_PAGE,
+ user,
+ });
+}