Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Report Base Plan subscriptions to Meta as a Purchase when advertising is allowed (#966)
Carter Smithb3ac14d11e53
diff --git a/src/server/billing/customer-status-sync.ts b/src/server/billing/customer-status-sync.tsindex f3564a7c..af0fcd32 100644--- a/src/server/billing/customer-status-sync.ts+++ b/src/server/billing/customer-status-sync.ts@@ -2,6 +2,8 @@ import { eq, sql } from "drizzle-orm";import { db } from "@/db";import { billingCustomerStatus } from "@/db/schema";import { autumn } from "@/server/billing/autumn";+import { captureMetaPurchase } from "@/server/referrals/meta";+import { AUTUMN_PAID_PLAN_ID } from "@/shared/billing";import {deriveBillingCustomerStatusSnapshot,type BillingCustomerStatusSnapshot,@@ -25,13 +27,27 @@ export async function syncAutumnCustomerStatus(customerId: string) {// pay), so a missing row is a customer from before the table existed, whose// next renewal or top-up must not read as a new subscription.const previous = await getPreviousSnapshot(customerId);+ const events = previous+ ? deriveBillingLifecycleEvents(previous, snapshot)+ : [];await syncBillingStatusToLoops({snapshot,- events: previous ? deriveBillingLifecycleEvents(previous, snapshot) : [],+ events,previousSyncedAt: previous?.syncedAt ?? null,});await upsertBillingCustomerStatus(snapshot);+ // After the write, so a retried webhook (which sees no change) can't+ // report the subscription twice. YC Plan subscriptions aren't reported.+ if (+ events.some(+ (event) =>+ event.name === "subscription_started" &&+ event.planId === AUTUMN_PAID_PLAN_ID,+ )+ ) {+ await captureMetaPurchase(customerId);+ }return snapshot;}diff --git a/src/server/referrals/meta.test.ts b/src/server/referrals/meta.test.tsindex d1550745..b224e05d 100644--- a/src/server/referrals/meta.test.ts+++ b/src/server/referrals/meta.test.ts@@ -1,38 +1,55 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { captureMetaSignup } from "./meta";+import {+ captureMetaPurchase,+ captureMetaSignup,+ pinMetaCheckout,+} from "./meta";+const kv = vi.hoisted(() => new Map<string, string>());vi.mock("cloudflare:workers", () => ({- env: { META_PIXEL_ID: "123", META_CONVERSIONS_API_TOKEN: "token" },+ env: {+ META_PIXEL_ID: "123",+ META_CONVERSIONS_API_TOKEN: "token",+ KV: {+ get: async (key: string): Promise<unknown> => {+ const value = kv.get(key);+ return value === undefined ? null : JSON.parse(value);+ },+ put: async (key: string, value: string) => void kv.set(key, value),+ delete: async (key: string) => void kv.delete(key),+ },+ },waitUntil: (promise: Promise<unknown>) => promise,}));vi.mock("@/server/lib/posthog", () => ({ captureServerError: vi.fn() }));-const fetchMock = vi.fn();+const fetchMock = vi.fn<typeof fetch>();-function signupRequest(headers: Record<string, string>) {+function browserRequest(headers: Record<string, string>) {return new Request("https://app.openseo.so/api/auth/sign-up/email", {headers: { cookie: "_fbp=fb.1.1.1", ...headers },});}-describe("captureMetaSignup", () => {- beforeEach(() => {- fetchMock.mockResolvedValue(new Response("{}"));- vi.stubGlobal("fetch", fetchMock);- });+beforeEach(() => {+ kv.clear();+ fetchMock.mockResolvedValue(new Response("{}"));+ vi.stubGlobal("fetch", fetchMock);+});+describe("captureMetaSignup", () => {it("sends nothing to Meta without advertising permission", () => {// An EU visitor who hasn't opted in, and a US visitor sending GPC. The// full set of region and saved-choice cases is in privacy-choices.test.ts.- captureMetaSignup(signupRequest({ "cf-ipcountry": "DE" }));- captureMetaSignup(signupRequest({ "cf-ipcountry": "US", "sec-gpc": "1" }));+ captureMetaSignup(browserRequest({ "cf-ipcountry": "DE" }));+ captureMetaSignup(browserRequest({ "cf-ipcountry": "US", "sec-gpc": "1" }));expect(fetchMock).not.toHaveBeenCalled();});it("reports the signup once advertising is allowed", () => {// EU visitor who opted in to advertising but not partner referrals.captureMetaSignup(- signupRequest({+ browserRequest({"cf-ipcountry": "DE",cookie: "_fbp=fb.1.1.1; openseo_privacy=a0.d0.m1",}),@@ -40,3 +57,24 @@ describe("captureMetaSignup", () => {expect(fetchMock).toHaveBeenCalledOnce();});});++describe("captureMetaPurchase", () => {+ it("reports a pinned checkout's subscription", async () => {+ await pinMetaCheckout("org-1", browserRequest({ "cf-ipcountry": "US" }));+ await captureMetaPurchase("org-1");+ expect(fetchMock).toHaveBeenCalledOnce();+ expect(fetchMock.mock.calls[0]?.[1]?.body).toEqual(+ expect.stringContaining('"event_name":"Purchase"'),+ );+ });++ it("sends nothing when the buyer's last checkout didn't allow advertising", async () => {+ await pinMetaCheckout("org-1", browserRequest({ "cf-ipcountry": "US" }));+ await pinMetaCheckout(+ "org-1",+ browserRequest({ "cf-ipcountry": "US", "sec-gpc": "1" }),+ );+ await captureMetaPurchase("org-1");+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/src/server/referrals/meta.ts b/src/server/referrals/meta.tsindex bb9c7028..f481f2d5 100644--- a/src/server/referrals/meta.ts+++ b/src/server/referrals/meta.ts@@ -1,56 +1,152 @@import { env, waitUntil } from "cloudflare:workers";import { parseCookies } from "better-auth/cookies";+import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";import { captureServerError } from "@/server/lib/posthog";import { requestPrivacyChoices } from "@/shared/privacy-choices";-// Meta ad signup attribution (hosted only). Sent only when the visitor's-// advertising (Meta) choice allows it, read here from the privacy cookie,-// location and GPC header, and the pixel on openseo.so left its cookies.-// Deliberately no name or email.+// Meta ad conversions (hosted only): a signup, and a subscription to the base+// plan. Sent only when the visitor's advertising (Meta) choice allows it, read+// from the privacy cookie, location and GPC header of their own request, and+// the pixel on openseo.so left its cookies. Deliberately no name or email.+//+// The subscription is confirmed by Autumn's webhook, which carries no browser+// cookies. So starting a checkout pins the buyer's Meta ids to the+// organization, under the same check, and the webhook sends the Purchase from+// the pin. The pin expires in a day, so account erasure needn't touch it.const META_GRAPH_API_URL = "https://graph.facebook.com/v23.0";+const META_CHECKOUT_KV_PREFIX = "meta:checkout:";+// Autumn checkout links expire after an hour, and the webhook follows+// payment within seconds.+const CHECKOUT_PIN_TTL_SECONDS = 24 * 60 * 60;-/** Must never fail the signup. */-export function captureMetaSignup(request: Request | null | undefined) {- const pixelId = env.META_PIXEL_ID;- const accessToken = env.META_CONVERSIONS_API_TOKEN;- if (!pixelId || !accessToken || !request) return;- if (!requestPrivacyChoices(request).advertising) return;+type MetaVisit = {+ eventSourceUrl: string;+ userData: {+ client_ip_address?: string;+ client_user_agent?: string;+ fbp?: string;+ fbc?: string;+ };+};+/** The visitor's Meta identifiers, or null when their advertising choice+ * doesn't allow Meta or the pixel left no cookies. */+function requestUserData(request: Request): MetaVisit["userData"] | null {+ if (!requestPrivacyChoices(request).advertising) return null;const headers = request.headers;const cookies = parseCookies(headers.get("cookie") ?? "");const fbp = cookies.get("_fbp");const fbc = cookies.get("_fbc");- if (!fbp && !fbc) return;+ if (!fbp && !fbc) return null;+ return {+ client_ip_address: headers.get("cf-connecting-ip") ?? undefined,+ client_user_agent: headers.get("user-agent") ?? undefined,+ fbp,+ fbc,+ };+}++function isMetaConfigured() {+ return Boolean(env.META_PIXEL_ID && env.META_CONVERSIONS_API_TOKEN);+}+function sendMetaEvent(+ name: "CompleteRegistration" | "Purchase",+ visit: MetaVisit,+ customData?: { currency: string; value: number },+) {const event = {- event_name: "CompleteRegistration",+ event_name: name,event_time: Math.floor(Date.now() / 1000),action_source: "website",- event_source_url: new URL("/sign-up", request.url).href,- user_data: {- client_ip_address: headers.get("cf-connecting-ip") ?? undefined,- client_user_agent: headers.get("user-agent") ?? undefined,- fbp,- fbc,- },+ event_source_url: visit.eventSourceUrl,+ user_data: visit.userData,+ custom_data: customData,};waitUntil(- fetch(`${META_GRAPH_API_URL}/${pixelId}/events`, {+ fetch(`${META_GRAPH_API_URL}/${env.META_PIXEL_ID}/events`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ data: [event], access_token: accessToken }),+ body: JSON.stringify({+ data: [event],+ access_token: env.META_CONVERSIONS_API_TOKEN,+ }),signal: AbortSignal.timeout(10_000),}).then((response) => {if (!response.ok) {- throw new Error(`Meta signup tracking failed (${response.status})`);+ throw new Error(`Meta ${name} tracking failed (${response.status})`);}}).catch(async (error: unknown) => {- console.error("Meta signup tracking failed", { error });- await captureServerError(error, { source: "meta_signup" });+ console.error(`Meta ${name} tracking failed`, { error });+ await captureServerError(error, {+ source: "meta_conversion",+ event_name: name,+ });}),);}++/** Must never fail the signup. */+export function captureMetaSignup(request: Request | null | undefined) {+ if (!isMetaConfigured() || !request) return;+ const userData = requestUserData(request);+ if (!userData) return;+ sendMetaEvent("CompleteRegistration", {+ eventSourceUrl: new URL("/sign-up", request.url).href,+ userData,+ });+}++/** Pins the buyer's Meta ids for the organization's checkout, or clears an+ * earlier pin when advertising is no longer allowed. Must never fail the+ * checkout. */+export async function pinMetaCheckout(+ organizationId: string,+ request: Request,+) {+ if (!isMetaConfigured()) return;+ const key = `${META_CHECKOUT_KV_PREFIX}${organizationId}`;+ try {+ const userData = requestUserData(request);+ if (!userData) {+ await env.KV.delete(key);+ return;+ }+ const pin: MetaVisit = {+ eventSourceUrl: new URL("/subscribe", request.url).href,+ userData,+ };+ await env.KV.put(key, JSON.stringify(pin), {+ expirationTtl: CHECKOUT_PIN_TTL_SECONDS,+ });+ } catch (error) {+ console.error("Meta checkout pin failed", { organizationId, error });+ }+}++/** Reports a new base plan subscription for an organization whose checkout+ * was pinned. Must never fail the webhook. */+export async function captureMetaPurchase(organizationId: string) {+ if (!isMetaConfigured()) return;+ try {+ const pin = await env.KV.get<MetaVisit>(+ `${META_CHECKOUT_KV_PREFIX}${organizationId}`,+ "json",+ );+ if (!pin) return;+ sendMetaEvent("Purchase", pin, {+ currency: "USD",+ value: BASE_PLAN_OFFER.priceUsd,+ });+ } catch (error) {+ console.error("Meta purchase tracking failed", { organizationId, error });+ await captureServerError(error, {+ source: "meta_conversion",+ customer_id: organizationId,+ });+ }+}diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.tsindex b71e25b1..14bac037 100644--- a/src/serverFunctions/billing.ts+++ b/src/serverFunctions/billing.ts@@ -22,6 +22,7 @@ import {isHostedServerAuthMode,} from "@/server/lib/runtime-env";import { getPublicOrigin } from "@/server/mcp/public-origin";+import { pinMetaCheckout } from "@/server/referrals/meta";import { requireAuthenticatedContext } from "@/serverFunctions/middleware";export const getBillingAccount = createServerFn({ method: "POST" })@@ -39,12 +40,17 @@ export const createPlanCheckout = createServerFn({ method: "POST" })redirectTo: z.string(),}),)- .handler(({ data, context }) =>- createPlanCheckoutUrl(context, {+ .handler(async ({ data, context }) => {+ const request = getRequest();+ const url = await createPlanCheckoutUrl(context, {...data,- origin: getPublicOrigin(getRequest()),- }),- );+ origin: getPublicOrigin(request),+ });+ // The buyer's browser is only here, not at the webhook that confirms the+ // subscription, so the Meta ad conversion is set up now.+ await pinMetaCheckout(context.organizationId, request);+ return url;+ });export const createTopUpCheckout = createServerFn({ method: "POST" }).middleware(requireAuthenticatedContext)diff --git a/src/shared/privacy-choices.ts b/src/shared/privacy-choices.tsindex b71b7d76..3d6e962e 100644--- a/src/shared/privacy-choices.ts+++ b/src/shared/privacy-choices.ts@@ -11,7 +11,7 @@ export type PrivacyChoices = {/** Partner referral attribution (Dub's referral cookie). */referrals: boolean;/** Meta ad measurement: the Meta Pixel on openseo.so and the app's signup- * event to Meta's Conversions API. */+ * and subscription events to Meta's Conversions API. */advertising: boolean;};diff --git a/web/src/components/privacy-choices.tsx b/web/src/components/privacy-choices.tsxindex 28d88447..5041d385 100644--- a/web/src/components/privacy-choices.tsx+++ b/web/src/components/privacy-choices.tsx@@ -110,7 +110,7 @@ export function PrivacyChoices() {return (<Prompt onAnswer={(advertising) => save({ ...choices, advertising })}>You came from one of our ads on Facebook or Instagram. Can Meta measure- whether it led to a sign-up?+ whether it led to a sign-up or subscription?</Prompt>);}@@ -181,7 +181,7 @@ function ChoicesForm({description={gpc? "Off because your browser sends Global Privacy Control."- : "Lets Meta measure which of our ads lead to sign-ups (Meta Pixel)."+ : "Lets Meta measure which of our ads lead to sign-ups and subscriptions (Meta Pixel)."}checked={draft.advertising && !gpc}disabled={gpc}