The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
AppsFlyer integration (#3588)
Kiran Kb98ce3f1ab6f
diff --git a/apps/web/app/(ee)/api/appsflyer/webhook/route.ts b/apps/web/app/(ee)/api/appsflyer/webhook/route.tsnew file mode 100644index 0000000000..4456c23ca2--- /dev/null+++ b/apps/web/app/(ee)/api/appsflyer/webhook/route.ts@@ -0,0 +1,134 @@+import { trackLead } from "@/lib/api/conversions/track-lead";+import { trackSale } from "@/lib/api/conversions/track-sale";+import { isLocalDev } from "@/lib/api/environment";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getIP } from "@/lib/api/utils/get-ip";+import { withAxiom } from "@/lib/axiom/server";+import { APPSFLYER_IP_RANGES } from "@/lib/integrations/appsflyer/constants";+import { isIpInRange } from "@/lib/middleware/utils/is-ip-in-range";+import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";+import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";+import { prisma } from "@dub/prisma";+import { APPSFLYER_INTEGRATION_ID, getSearchParams } from "@dub/utils";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++const querySchema = z.object({+ appId: z.string(),+ partnerEventId: z.string(),+ eventValue: z.string().nullish(),+});++// GET /api/appsflyer/webhook – listen to Postback events from AppsFlyer+export const GET = withAxiom(async (req) => {+ try {+ if (!isLocalDev) {+ const ip = await getIP();+ const isAllowed = APPSFLYER_IP_RANGES.some((range) =>+ isIpInRange(ip, range),+ );++ if (!isAllowed) {+ throw new DubApiError({+ code: "forbidden",+ message: `IP address ${ip} is not allowed.`,+ });+ }+ }++ const queryParams = getSearchParams(req.url);++ const { appId, partnerEventId } = querySchema.parse(queryParams);++ if (!["lead", "sale"].includes(partnerEventId)) {+ return NextResponse.json("partnerEventId is not supported. Skipping...");+ }++ // Find the installation+ const installation = await prisma.installedIntegration.findFirst({+ where: {+ integrationId: APPSFLYER_INTEGRATION_ID,+ settings: {+ path: "$.appIds",+ array_contains: appId,+ },+ },+ select: {+ project: {+ select: {+ id: true,+ stripeConnectId: true,+ webhookEnabled: true,+ },+ },+ },+ });++ if (!installation) {+ throw new DubApiError({+ code: "bad_request",+ message: "AppsFlyer integration is not configured for this app.",+ });+ }++ // Track lead event+ if (partnerEventId === "lead") {+ const {+ clickId,+ eventName,+ customerExternalId,+ customerName,+ customerEmail,+ customerAvatar,+ } = trackLeadRequestSchema.parse(queryParams);++ await trackLead({+ clickId,+ eventName,+ customerExternalId,+ customerName,+ customerEmail,+ customerAvatar,+ eventQuantity: undefined,+ mode: undefined,+ metadata: null,+ workspace: installation.project,+ rawBody: queryParams,+ });++ return NextResponse.json("Lead event tracked successfully.");+ }++ // Track sale event+ if (partnerEventId === "sale") {+ const { eventName, customerExternalId, amount, currency, invoiceId } =+ trackSaleRequestSchema.parse({+ ...queryParams,+ ...(queryParams.amount && { amount: Number(queryParams.amount) }),+ });++ await trackSale({+ customerExternalId,+ amount,+ currency,+ eventName,+ paymentProcessor: "custom",+ invoiceId,+ leadEventName: undefined,+ metadata: null,+ workspace: installation.project,+ rawBody: queryParams,+ });++ return NextResponse.json("Sale event tracked successfully.");+ }++ return NextResponse.json("OK");+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+});++export const HEAD = () => {+ return new Response("OK");+};diff --git a/apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts b/apps/web/app/(ee)/api/cron/groups/create-default-links/route.tsindex b32b0fe44f..5cc10fd722 100644--- a/apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts+++ b/apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts@@ -4,6 +4,9 @@ import { generatePartnerLink } from "@/lib/api/partners/generate-partner-link";import { extractUtmParams } from "@/lib/api/utm/extract-utm-params";import { qstash } from "@/lib/cron";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { loadAppsFlyerParameters } from "@/lib/integrations/appsflyer/apply-parameters";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/schema";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";import { WorkspaceProps } from "@/lib/types";import { prisma } from "@dub/prisma";import {@@ -90,6 +93,13 @@ export async function POST(req: Request) {},});+ // Load AppsFlyer parameters if the default link is an AppsFlyer URL+ let appsFlyerParameters: AppsFlyerSettings["parameters"] = [];++ if (isAppsFlyerTrackingUrl(defaultLink.url)) {+ appsFlyerParameters = await loadAppsFlyerParameters(workspace.id);+ }+let hasMore = true;let currentCursor = cursor;let processedBatches = 0;@@ -150,6 +160,7 @@ export async function POST(req: Request) {partnerGroupDefaultLinkId: defaultLink.id,},userId,+ appsFlyerParameters,}),),)diff --git a/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts b/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.tsindex ea255fe225..7fa68b4697 100644--- a/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts+++ b/apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts@@ -3,6 +3,9 @@ import { bulkCreateLinks } from "@/lib/api/links";import { generatePartnerLink } from "@/lib/api/partners/generate-partner-link";import { qstash } from "@/lib/cron";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { loadAppsFlyerParameters } from "@/lib/integrations/appsflyer/apply-parameters";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/schema";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";import { WorkspaceProps } from "@/lib/types";import { MAX_DEFAULT_LINKS_PER_GROUP } from "@/lib/zod/schemas/groups";import { prisma } from "@dub/prisma";@@ -128,6 +131,19 @@ export async function POST(req: Request) {// Create the linksif (linksToCreate.length > 0) {+ // Load AppsFlyer parameters if the default link is an AppsFlyer URL+ let appsFlyerParameters: AppsFlyerSettings["parameters"] = [];++ const hasAppsFlyerUrl = partnerGroup.partnerGroupDefaultLinks.some((dl) =>+ isAppsFlyerTrackingUrl(dl.url),+ );++ if (hasAppsFlyerUrl) {+ appsFlyerParameters = await loadAppsFlyerParameters(+ program.workspace.id,+ );+ }+const processedLinks = (await Promise.allSettled(linksToCreate.map((link) => {@@ -159,6 +175,7 @@ export async function POST(req: Request) {partnerGroupDefaultLinkId: link.partnerGroupDefaultLinkId,},userId: userId ?? undefined,+ appsFlyerParameters,});}),)diff --git a/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts b/apps/web/app/(ee)/api/cron/groups/update-default-links/route.tsindex d6e36ed20d..5d5d64b428 100644--- a/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts+++ b/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts@@ -3,7 +3,14 @@ import { linkCache } from "@/lib/api/links/cache";import { extractUtmParams } from "@/lib/api/utm/extract-utm-params";import { qstash } from "@/lib/cron";import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import {+ applyAppsFlyerParameters,+ loadAppsFlyerParameters,+} from "@/lib/integrations/appsflyer/apply-parameters";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/schema";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";import { prisma } from "@dub/prisma";+import { Link } from "@dub/prisma/client";import {APP_DOMAIN_WITH_NGROK,constructURLFromUTMParams,@@ -50,6 +57,11 @@ export async function POST(req: Request) {utmTemplate: true,},},+ program: {+ select: {+ workspaceId: true,+ },+ },},});@@ -77,12 +89,21 @@ export async function POST(req: Request) {`Updating default links for the partners (defaultLinkId=${defaultLink.id}, groupId=${group.id}).`,);+ // Load AppsFlyer parameters if the default link is an AppsFlyer URL+ let appsFlyerParameters: AppsFlyerSettings["parameters"] = [];++ if (isAppsFlyerTrackingUrl(defaultLink.url)) {+ appsFlyerParameters = await loadAppsFlyerParameters(+ defaultLink.program.workspaceId,+ );+ }+let hasMore = true;let currentCursor = cursor;let processedBatches = 0;while (processedBatches < MAX_BATCH) {- const linksToUpdate = await prisma.link.findMany({+ const defaultPartnerLinks = await prisma.link.findMany({where: {...(currentCursor && {id: {@@ -95,36 +116,89 @@ export async function POST(req: Request) {orderBy: {id: "asc",},+ select: {+ id: true,+ url: true,+ domain: true,+ key: true,+ partner: {+ select: {+ name: true,+ },+ },+ },});- if (linksToUpdate.length === 0) {+ if (defaultPartnerLinks.length === 0) {hasMore = false;break;}- const updatedLinks = await prisma.link.updateMany({- where: {- id: {- in: linksToUpdate.map((link) => link.id),+ const linksToUpdate: {+ id: string;+ link: Pick<+ Link,+ | "url"+ | "utm_source"+ | "utm_medium"+ | "utm_campaign"+ | "utm_term"+ | "utm_content"+ >;+ }[] = [];++ for (const defaultPartnerLink of defaultPartnerLinks) {+ let url = constructURLFromUTMParams(+ defaultLink.url,+ extractUtmParams(group.utmTemplate),+ );++ // Inject AppsFlyer parameters with resolved macros+ if (+ appsFlyerParameters.length > 0 &&+ isAppsFlyerTrackingUrl(defaultLink.url)+ ) {+ url = applyAppsFlyerParameters({+ url,+ parameters: appsFlyerParameters,+ context: {+ partnerName:+ defaultPartnerLink.partner?.name || defaultPartnerLink.key,+ partnerLinkKey: defaultPartnerLink.key,+ },+ });+ }++ linksToUpdate.push({+ id: defaultPartnerLink.id,+ link: {+ url,+ ...extractUtmParams(group.utmTemplate, { excludeRef: true }),},- },- data: {- url: constructURLFromUTMParams(- defaultLink.url,- extractUtmParams(group.utmTemplate),+ });+ }++ if (linksToUpdate.length > 0) {+ await Promise.allSettled(+ linksToUpdate.map(({ id, link }) =>+ prisma.link.update({+ where: {+ id,+ },+ data: link,+ }),),- ...extractUtmParams(group.utmTemplate, { excludeRef: true }),- },- });+ );+ }console.log(- `Updated ${updatedLinks.count} links with url=${defaultLink.url} (via defaultLinkId=${defaultLink.id})`,+ `Updated ${linksToUpdate.length} links with url=${defaultLink.url} (via defaultLinkId=${defaultLink.id})`,);- await linkCache.expireMany(linksToUpdate);+ await linkCache.expireMany(defaultPartnerLinks);// Update cursor to the last processed record- currentCursor = linksToUpdate[linksToUpdate.length - 1].id;+ currentCursor = defaultPartnerLinks[defaultPartnerLinks.length - 1].id;processedBatches++;}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsxindex c8afa696c9..de0111ad6b 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx@@ -2,12 +2,15 @@import { getIntegrationInstallUrl } from "@/lib/actions/get-integration-install-url";import { clientAccessCheck } from "@/lib/client-access-check";+import { installAppsFlyerAction } from "@/lib/integrations/appsflyer/install";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/ui/settings";import { HubSpotSettings } from "@/lib/integrations/hubspot/ui/settings";import { SegmentSettings } from "@/lib/integrations/segment/ui/settings";import { SlackSettings } from "@/lib/integrations/slack/ui/settings";import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";import { StripeIntegrationSettings } from "@/lib/integrations/stripe/ui/settings";import { ZapierSettings } from "@/lib/integrations/zapier/ui/settings";+import { getPlanCapabilities } from "@/lib/plan-capabilities";import useWorkspace from "@/lib/swr/use-workspace";import { InstalledIntegrationInfoProps } from "@/lib/types";import { IntegrationLogo } from "@/ui/integrations/integration-logo";@@ -43,6 +46,7 @@ import {Trash,} from "@dub/ui/icons";import {+ APPSFLYER_INTEGRATION_ID,cn,DUB_WORKSPACE_ID,formatDate,@@ -64,6 +68,7 @@ const integrationSettings = {[SEGMENT_INTEGRATION_ID]: SegmentSettings,[HUBSPOT_INTEGRATION_ID]: HubSpotSettings,[STRIPE_INTEGRATION_ID]: StripeIntegrationSettings,+ [APPSFLYER_INTEGRATION_ID]: AppsFlyerSettings,};export default function IntegrationPageClient({@@ -93,6 +98,18 @@ export default function IntegrationPageClient({},});+ const { execute: executeInstallAppsFlyer, isPending: isInstallingAppsFlyer } =+ useAction(installAppsFlyerAction, {+ onSuccess: () => {+ toast.success("AppsFlyer integration enabled successfully.");+ },+ onError: ({ error }) => {+ toast.error(+ error.serverError || "Failed to enable AppsFlyer integration.",+ );+ },+ });+const { UninstallIntegrationModal, setShowUninstallIntegrationModal } =useUninstallIntegrationModal({integration,@@ -137,6 +154,8 @@ export default function IntegrationPageClient({return variants[mode];}, [integration.id, integration.installed, integration.settings]);+ const { canInstallAdvancedIntegrations } = getPlanCapabilities(plan);+return (<MaxWidthWrapper className="grid max-w-screen-lg grid-cols-1 gap-6">{integration.installed && <UninstallIntegrationModal />}@@ -307,6 +326,13 @@ export default function IntegrationPageClient({integration.id !== SEGMENT_INTEGRATION_ID && (<ButtononClick={() => {+ if (integration.id === APPSFLYER_INTEGRATION_ID) {+ executeInstallAppsFlyer({+ workspaceId: workspaceId!,+ });+ return;+ }+const { installUrl } = integration;if (installUrl) {@@ -320,21 +346,21 @@ export default function IntegrationPageClient({integrationSlug: integration.slug,});}}- loading={isPending}+ loading={isPending || isInstallingAppsFlyer}text="Enable"variant="primary"className="h-9 px-3"icon={<ConnectedDots className="size-4" />}disabledTooltip={- integration.id === HUBSPOT_INTEGRATION_ID &&- plan &&- ["free", "pro"].includes(plan) ? (+ [HUBSPOT_INTEGRATION_ID, APPSFLYER_INTEGRATION_ID].includes(+ integration.id,+ ) && !canInstallAdvancedIntegrations ? (<TooltipContent- title="Hubspot integration is only available on Business plans and above. Upgrade to get started."- cta="Upgrade to Business"- href={`/${slug}/settings/billing/upgrade`}+ title="This integration is only available on Advanced and Enterprise plans."+ cta="Upgrade to Advanced"+ href={`/${slug}/settings/billing/upgrade?plan=advanced`}/>- ) : null+ ) : undefined}/>)}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page.tsxindex d81925bdb9..9fa309b260 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page.tsx@@ -1,5 +1,8 @@import { prisma } from "@dub/prisma";-import { HUBSPOT_INTEGRATION_ID } from "@dub/utils/src";+import {+ APPSFLYER_INTEGRATION_ID,+ HUBSPOT_INTEGRATION_ID,+} from "@dub/utils/src";import { redirect } from "next/navigation";import IntegrationPageClient from "./page-client";@@ -46,7 +49,7 @@ export default async function IntegrationPage(props: {redirect(`/${params.slug}/settings/integrations`);}- if (integration.guideUrl) {+ if (integration.guideUrl && integration.id !== APPSFLYER_INTEGRATION_ID) {redirect(integration.guideUrl);}diff --git a/apps/web/lib/api/partners/create-partner-default-links.ts b/apps/web/lib/api/partners/create-partner-default-links.tsindex 82a7ecb65b..0662470eaa 100644--- a/apps/web/lib/api/partners/create-partner-default-links.ts+++ b/apps/web/lib/api/partners/create-partner-default-links.ts@@ -1,3 +1,6 @@+import { loadAppsFlyerParameters } from "@/lib/integrations/appsflyer/apply-parameters";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/schema";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";import {CreatePartnerProps,ProgramProps,@@ -43,6 +46,17 @@ export async function createPartnerDefaultLinks({const hasMoreThanOneDefaultLink = defaultLinks.length > 1;+ // Check if any default link URL is an AppsFlyer URL and load settings once+ const hasAppsFlyerUrl = defaultLinks.some((dl) =>+ isAppsFlyerTrackingUrl(dl.url),+ );++ let appsFlyerParameters: AppsFlyerSettings["parameters"] = [];++ if (hasAppsFlyerUrl) {+ appsFlyerParameters = await loadAppsFlyerParameters(workspace.id);+ }+const processedLinks = (await Promise.allSettled(defaultLinks.map((defaultLink) => {@@ -68,13 +82,13 @@ export async function createPartnerDefaultLinks({partnerGroupDefaultLinkId: defaultLink.id,},userId,+ appsFlyerParameters,});}),)).filter(isFulfilled).map(({ value }) => value);-return await bulkCreateLinks({links: processedLinks,skipRedisCache: true,diff --git a/apps/web/lib/api/partners/generate-partner-link.ts b/apps/web/lib/api/partners/generate-partner-link.tsindex 1bdac55c58..8e9e853eec 100644--- a/apps/web/lib/api/partners/generate-partner-link.ts+++ b/apps/web/lib/api/partners/generate-partner-link.ts@@ -1,4 +1,7 @@import { ErrorCodes } from "@/lib/api/errors";+import { applyAppsFlyerParameters } from "@/lib/integrations/appsflyer/apply-parameters";+import { AppsFlyerSettings } from "@/lib/integrations/appsflyer/schema";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";import {CreatePartnerProps,ProcessedLinkProps,@@ -81,6 +84,7 @@ interface GeneratePartnerLinkInput {partnerGroupDefaultLinkId?: string | null;};userId?: string;+ appsFlyerParameters?: AppsFlyerSettings["parameters"];}// Generates and processes a partner link without creating it@@ -90,6 +94,7 @@ export const generatePartnerLink = async ({partner,link,userId,+ appsFlyerParameters,}: GeneratePartnerLinkInput) => {const { name, email, username } = partner;@@ -138,6 +143,23 @@ export const generatePartnerLink = async ({processedLink = result.link as ProcessedLinkProps;error = result.error;code = result.code as ErrorCodes;++ // Apply AppsFlyer parameters if any+ if (+ processedLink &&+ appsFlyerParameters?.length &&+ isAppsFlyerTrackingUrl(processedLink.url)+ ) {+ processedLink.url = applyAppsFlyerParameters({+ url: processedLink.url,+ parameters: appsFlyerParameters,+ context: {+ partnerName: partner.name || currentKey,+ partnerLinkKey: currentKey,+ },+ });+ }+break;}diff --git a/apps/web/lib/integrations/appsflyer/apply-parameters.ts b/apps/web/lib/integrations/appsflyer/apply-parameters.tsnew file mode 100644index 0000000000..b83c5eaa63--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/apply-parameters.ts@@ -0,0 +1,70 @@+import { prisma } from "@dub/prisma";+import { APPSFLYER_INTEGRATION_ID } from "@dub/utils";+import { AppsFlyerSettings, appsFlyerSettingsSchema } from "./schema";++interface AppsFlyerParameterContext {+ partnerName: string;+ partnerLinkKey: string;+}++const macroReplacements: Record<string, keyof AppsFlyerParameterContext> = {+ "{{PARTNER_NAME}}": "partnerName",+ "{{PARTNER_LINK_KEY}}": "partnerLinkKey",+};++// Resolve macros in parameter values and append them to a URL+export function applyAppsFlyerParameters({+ url,+ parameters,+ context,+}: {+ url: string;+ parameters: { key: string; value: string }[];+ context: AppsFlyerParameterContext;+}) {+ const urlObj = new URL(url);++ for (const { key, value } of parameters) {+ let resolvedValue = value;++ for (const [macro, contextKey] of Object.entries(macroReplacements)) {+ resolvedValue = resolvedValue.replaceAll(+ macro,+ context[contextKey] ?? "",+ );+ }++ urlObj.searchParams.set(key, resolvedValue);+ }++ return urlObj.toString();+}++// Load AppsFlyer parameters from the workspace's installed integration settings+export async function loadAppsFlyerParameters(+ workspaceId: string,+): Promise<AppsFlyerSettings["parameters"]> {+ const installedIntegration = await prisma.installedIntegration.findFirst({+ where: {+ projectId: workspaceId,+ integrationId: APPSFLYER_INTEGRATION_ID,+ },+ select: {+ settings: true,+ },+ });++ if (!installedIntegration?.settings) {+ return [];+ }++ const parsed = appsFlyerSettingsSchema.safeParse(+ installedIntegration.settings,+ );++ if (!parsed.success) {+ return [];+ }++ return [...parsed.data.requiredParameters, ...parsed.data.parameters];+}diff --git a/apps/web/lib/integrations/appsflyer/constants.ts b/apps/web/lib/integrations/appsflyer/constants.tsnew file mode 100644index 0000000000..ee9193c1c0--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/constants.ts@@ -0,0 +1,57 @@+export const APPSFLYER_DEFAULT_SETTINGS = {+ appIds: [],+ parameters: [],+};++export const APPSFLYER_HARDCODED_PARAMETERS = [+ {+ key: "pid",+ value: "dubinc_int",+ description: "Partner ID",+ },+ {+ key: "clickid",+ value: "{dub_id}",+ description: "Dub click ID",+ },+ {+ key: "af_ua",+ value: "{userAgent}",+ description: "User agent",+ },+ {+ key: "af_ip",+ value: "{ipAddress}",+ description: "IP address",+ },+];++export const APPSFLYER_REQUIRED_PARAMETERS = [+ {+ key: "c",+ value: "{{PARTNER_NAME}}",+ description: "Campaign name",+ },+ {+ key: "af_siteid",+ value: "{{PARTNER_LINK_KEY}}",+ description: "Site ID",+ },+];++export const APPSFLYER_IP_RANGES = ["45.92.116.0/22", "194.28.46.0/23"];++export const APPSFLYER_MACROS = [+ {+ macro: "{{PARTNER_NAME}}",+ description: "The partner's name (e.g. 'John Doe')",+ },+ {+ macro: "{{PARTNER_LINK_KEY}}",+ description: "The partner's link key (e.g. 'john-doe')",+ },+] as const;++export const APPSFLYER_MACRO_VALUES: readonly string[] = APPSFLYER_MACROS.map(+ (m) => m.macro,+);diff --git a/apps/web/lib/integrations/appsflyer/install.ts b/apps/web/lib/integrations/appsflyer/install.tsnew file mode 100644index 0000000000..f8d555ba40--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/install.ts@@ -0,0 +1,32 @@+"use server";++import { authActionClient } from "@/lib/actions/safe-action";+import { getPlanCapabilities } from "@/lib/plan-capabilities";+import { APPSFLYER_INTEGRATION_ID } from "@dub/utils";+import { revalidatePath } from "next/cache";+import * as z from "zod/v4";+import { installIntegration } from "../install";++const schema = z.object({+ workspaceId: z.string(),+});++export const installAppsFlyerAction = authActionClient+ .inputSchema(schema)+ .action(async ({ ctx }) => {+ const { workspace, user } = ctx;++ if (!getPlanCapabilities(workspace.plan).canInstallAdvancedIntegrations) {+ throw new Error(+ "AppsFlyer integration is only available on Advanced and Enterprise plans.",+ );+ }++ await installIntegration({+ integrationId: APPSFLYER_INTEGRATION_ID,+ userId: user.id,+ workspaceId: workspace.id,+ });++ revalidatePath(`/${workspace.slug}/settings/integrations/appsflyer`);+ });diff --git a/apps/web/lib/integrations/appsflyer/macro-template.ts b/apps/web/lib/integrations/appsflyer/macro-template.tsnew file mode 100644index 0000000000..acf72a3a78--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/macro-template.ts@@ -0,0 +1,21 @@+import { APPSFLYER_MACRO_VALUES } from "./constants";++const MACRO_TOKEN_RE = /\{\{[^}]+\}\}/g;++/** Every `{{...}}` substring must be a known AppsFlyer macro. */+export function isValidAppsFlyerMacroTemplate(value: string): boolean {+ const matches = value.match(MACRO_TOKEN_RE) ?? [];+ return matches.every((token) => APPSFLYER_MACRO_VALUES.includes(token));+}++/**+ * Validates a free-form custom parameter value (any `{{...}}` tokens must be known macros).+ * @throws Error when validation fails.+ */+export function assertAppsFlyerMacroValueParses(value: string): void {+ if (!isValidAppsFlyerMacroTemplate(value)) {+ throw new Error(+ `Invalid macro in value. Use only: ${APPSFLYER_MACRO_VALUES.join(", ")}`,+ );+ }+}diff --git a/apps/web/lib/integrations/appsflyer/schema.ts b/apps/web/lib/integrations/appsflyer/schema.tsnew file mode 100644index 0000000000..011dba0e32--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/schema.ts@@ -0,0 +1,39 @@+import * as z from "zod/v4";+import { APPSFLYER_MACRO_VALUES } from "./constants";+import { isValidAppsFlyerMacroTemplate } from "./macro-template";++export const appsFlyerMacroExactValueSchema = z.string().refine(+ (v) => APPSFLYER_MACRO_VALUES.includes(v),+ {+ message: `Value must be one of: ${APPSFLYER_MACRO_VALUES.join(", ")}`,+ },+);++/** Free-form value; every `{{...}}` token must be a known macro. */+export const appsFlyerMacroTemplateValueSchema = z.string().refine(+ (v) => isValidAppsFlyerMacroTemplate(v),+ {+ message: `Invalid macro in value. Use only: ${APPSFLYER_MACRO_VALUES.join(", ")}`,+ },+);++export const appsFlyerRequiredParameterSchema = z.object({+ key: z.string().min(1),+ value: appsFlyerMacroExactValueSchema,+});++export const appsFlyerCustomParameterSchema = z.object({+ key: z.string().min(1),+ value: appsFlyerMacroTemplateValueSchema,+});++export const appsFlyerSettingsSchema = z.object({+ appIds: z.array(z.string()).default([]),+ requiredParameters: z.array(appsFlyerRequiredParameterSchema).default([+ { key: "c", value: "{{PARTNER_NAME}}" },+ { key: "af_siteid", value: "{{PARTNER_LINK_KEY}}" },+ ]),+ parameters: z.array(appsFlyerCustomParameterSchema).default([]),+});++export type AppsFlyerSettings = z.infer<typeof appsFlyerSettingsSchema>;diff --git a/apps/web/lib/integrations/appsflyer/ui/settings.tsx b/apps/web/lib/integrations/appsflyer/ui/settings.tsxnew file mode 100644index 0000000000..d8691908ac--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/ui/settings.tsx@@ -0,0 +1,443 @@+"use client";++import useWorkspace from "@/lib/swr/use-workspace";+import { InstalledIntegrationInfoProps } from "@/lib/types";+import { Button, Combobox, ComboboxOption, Input } from "@dub/ui";+import { Plus, Xmark } from "@dub/ui/icons";+import { ChevronDown } from "lucide-react";+import { useAction } from "next-safe-action/hooks";+import { useEffect, useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import {+ APPSFLYER_DEFAULT_SETTINGS,+ APPSFLYER_HARDCODED_PARAMETERS,+ APPSFLYER_MACROS,+ APPSFLYER_REQUIRED_PARAMETERS,+} from "../constants";+import { assertAppsFlyerMacroValueParses } from "../macro-template";+import { appsFlyerSettingsSchema } from "../schema";+import { updateAppsFlyerSettingsAction } from "../update-settings";++type AppsFlyerFormBaseline = {+ appIds: string[];+ requiredParameters: { key: string; value: string }[];+ parameters: { key: string; value: string }[];+};++function cloneFormBaseline(data: AppsFlyerFormBaseline): AppsFlyerFormBaseline {+ return {+ appIds: [...data.appIds],+ requiredParameters: data.requiredParameters.map((p) => ({ ...p })),+ parameters: data.parameters.map((p) => ({ ...p })),+ };+}++type AppsFlyerMacroMeta = { description: string };++const REQUIRED_MACRO_COMBO_OPTIONS: ComboboxOption<AppsFlyerMacroMeta>[] =+ APPSFLYER_MACROS.map((m) => ({+ value: m.macro,+ label: m.macro,+ meta: { description: m.description },+ }));++function AppsFlyerRequiredMacroCombobox({+ value,+ onValueChange,+ ariaLabel,+}: {+ value: string;+ onValueChange: (value: string) => void;+ ariaLabel: string;+}) {+ const selected =+ REQUIRED_MACRO_COMBO_OPTIONS.find((o) => o.value === value) ?? null;++ return (+ <Combobox+ options={REQUIRED_MACRO_COMBO_OPTIONS}+ selected={selected}+ setSelected={(opt) => {+ if (opt) onValueChange(opt.value);+ }}+ placeholder="Select macro"+ matchTriggerWidth+ hideSearch+ caret={+ <ChevronDown className="text-content-muted size-3.5 shrink-0 transition-transform duration-75 group-data-[state=open]:rotate-180" />+ }+ popoverProps={{+ contentClassName: "rounded-md p-0.5",+ }}+ optionClassName="px-2 py-1.5 text-xs leading-tight"+ optionDescription={(option) => option.meta?.description}+ buttonProps={{+ "aria-label": ariaLabel,+ className:+ "h-8 w-full max-w-none justify-between gap-1.5 px-2 py-0 text-xs font-normal shadow-none",+ }}+ labelProps={{+ className: "font-mono",+ }}+ />+ );+}++export const AppsFlyerSettings = ({+ installed,+ settings,+}: InstalledIntegrationInfoProps) => {+ const { id: workspaceId } = useWorkspace();++ const appsFlyerSettings = appsFlyerSettingsSchema.parse({+ ...APPSFLYER_DEFAULT_SETTINGS,+ ...(settings as any),+ });++ const [appIds, setAppIds] = useState(appsFlyerSettings.appIds);+ const [requiredParameters, setRequiredParameters] = useState(+ appsFlyerSettings.requiredParameters,+ );+ const [parameters, setParameters] = useState(appsFlyerSettings.parameters);++ const [baseline, setBaseline] = useState<AppsFlyerFormBaseline>(() =>+ cloneFormBaseline(appsFlyerSettings),+ );++ const pendingBaselineRef = useRef<AppsFlyerFormBaseline | null>(null);++ const settingsSignature = JSON.stringify(settings ?? null);++ useEffect(() => {+ const parsed = appsFlyerSettingsSchema.parse({+ ...APPSFLYER_DEFAULT_SETTINGS,+ ...(settings as any),+ });+ const next = cloneFormBaseline(parsed);+ setBaseline(next);+ setAppIds(next.appIds);+ setRequiredParameters(next.requiredParameters);+ setParameters(next.parameters);+ }, [settingsSignature]);++ const isDirty = useMemo(() => {+ const current: AppsFlyerFormBaseline = {+ appIds,+ requiredParameters,+ parameters,+ };+ return JSON.stringify(current) !== JSON.stringify(baseline);+ }, [appIds, requiredParameters, parameters, baseline]);++ const { executeAsync: executeUpdate, isPending: isUpdating } = useAction(+ updateAppsFlyerSettingsAction,+ {+ async onSuccess() {+ const next = pendingBaselineRef.current;+ if (next) {+ setBaseline(next);+ setAppIds(next.appIds);+ setRequiredParameters(next.requiredParameters);+ setParameters(next.parameters);+ pendingBaselineRef.current = null;+ }+ toast.success("AppsFlyer settings updated successfully.");+ },+ onError({ error }) {+ pendingBaselineRef.current = null;+ toast.error(+ error.serverError || "Failed to update AppsFlyer settings.",+ );+ },+ },+ );++ const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {+ e.preventDefault();+ if (!workspaceId || !isDirty) return;++ const filteredAppIds = appIds+ .map((id) => id.trim())+ .filter((id) => id.length > 0);+ const normalizedRequired = requiredParameters.map((p) => ({+ key: p.key.trim(),+ value: p.value.trim(),+ }));+ const filteredParameters = parameters+ .map((p) => ({+ key: p.key.trim(),+ value: p.value.trim(),+ }))+ .filter((p) => p.key.length > 0 && p.value.length > 0);++ for (const p of filteredParameters) {+ try {+ assertAppsFlyerMacroValueParses(p.value);+ } catch (err) {+ toast.error(+ err instanceof Error+ ? err.message+ : "Invalid macro syntax in custom parameter value.",+ );+ return;+ }+ }++ pendingBaselineRef.current = cloneFormBaseline({+ appIds: filteredAppIds,+ requiredParameters: normalizedRequired,+ parameters: filteredParameters,+ });++ await executeUpdate({+ workspaceId,+ appIds: filteredAppIds,+ requiredParameters: normalizedRequired,+ parameters: filteredParameters,+ });+ };++ if (!installed) {+ return null;+ }++ return (+ <form className="mt-4 space-y-4" onSubmit={onSubmit}>+ {/* App IDs */}+ <div className="rounded-lg border border-neutral-200 bg-white">+ <div className="border-b border-neutral-200 px-4 py-4">+ <p className="text-sm font-medium text-neutral-700">App IDs</p>+ <p className="mt-1 text-sm text-neutral-500">+ Add your AppsFlyer app IDs to identify your workspace when postbacks+ are received.+ </p>+ </div>++ <div className="space-y-3 p-4">+ {appIds.map((appId, index) => (+ <div key={index} className="flex items-center gap-2">+ <div className="flex-1">+ <Input+ className="max-w-none"+ placeholder="e.g., id123456789"+ type="text"+ autoComplete="off"+ aria-label={+ appIds.length > 1 ? `App ID ${index + 1}` : "App ID"+ }+ value={appId}+ onChange={(e) => {+ const updated = [...appIds];+ updated[index] = e.target.value;+ setAppIds(updated);+ }}+ />+ </div>+ <button+ type="button"+ onClick={() => setAppIds(appIds.filter((_, i) => i !== index))}+ className="text-neutral-400 transition-colors hover:text-red-500"+ aria-label={+ appIds.length > 1+ ? `Remove app ID ${index + 1}`+ : "Remove app ID"+ }+ >+ <Xmark className="size-4" aria-hidden />+ </button>+ </div>+ ))}++ <Button+ type="button"+ variant="secondary"+ onClick={() => setAppIds([...appIds, ""])}+ icon={<Plus className="size-3.5" />}+ text="Add App ID"+ className="h-7 w-fit px-2 text-xs"+ />+ </div>+ </div>++ {/* Parameters */}+ <div className="rounded-lg border border-neutral-200 bg-white">+ <div className="border-b border-neutral-200 px-4 py-4">+ <p className="text-sm font-medium text-neutral-700">+ Tracking Parameters+ </p>+ <p className="mt-1 text-sm text-neutral-500">+ Parameters injected into AppsFlyer OneLink URLs when creating+ partner links.+ </p>+ </div>++ <div className="space-y-4 p-4">+ {/* Default parameters */}+ <div>+ <p className="text-content-subtle mb-2 text-xs font-medium">+ Default Parameters+ </p>++ <div className="space-y-2">+ {APPSFLYER_HARDCODED_PARAMETERS.map((param) => (+ <div key={param.key} className="grid grid-cols-2 gap-2">+ <Input+ className="max-w-none"+ value={param.key}+ readOnly+ disabled+ aria-label={`${param.description} — parameter key (${param.key})`}+ />+ <Input+ className="max-w-none font-mono"+ value={param.value}+ readOnly+ disabled+ aria-label={`${param.description} — parameter value`}+ />+ </div>+ ))}+ </div>+ </div>++ {/* Required parameters */}+ <div className="border-t border-neutral-200 pt-4">+ <p className="text-content-subtle mb-2 text-xs font-medium">+ Required Parameters+ </p>++ <div className="space-y-2">+ {requiredParameters.map((param, index) => {+ const defaultParam = APPSFLYER_REQUIRED_PARAMETERS.find(+ (p) => p.key === param.key,+ );++ return (+ <div key={param.key} className="grid grid-cols-2 gap-2">+ <Input+ className="max-w-none"+ value={param.key}+ readOnly+ disabled+ aria-label={`${defaultParam?.description ?? param.key} — parameter key`}+ />+ <AppsFlyerRequiredMacroCombobox+ value={param.value}+ onValueChange={(next) => {+ const updated = [...requiredParameters];+ updated[index] = {+ ...updated[index],+ value: next,+ };+ setRequiredParameters(updated);+ }}+ ariaLabel={`${defaultParam?.description ?? param.key} — parameter value`}+ />+ </div>+ );+ })}+ </div>+ </div>++ {/* Custom parameters */}+ <div className="border-t border-neutral-200 pt-4">+ <p className="text-content-subtle mb-2 text-xs font-medium">+ Custom Parameters+ </p>+ <div className="space-y-2">+ {parameters.map((param, index) => (+ <div key={index} className="flex items-center gap-2">+ <div className="grid flex-1 grid-cols-2 gap-2">+ <Input+ className="max-w-none"+ placeholder="Key"+ type="text"+ autoComplete="off"+ aria-label={+ parameters.length > 1+ ? `Custom parameter key ${index + 1}`+ : "Custom parameter key"+ }+ value={param.key}+ onChange={(e) => {+ const updated = [...parameters];+ updated[index] = {+ ...updated[index],+ key: e.target.value,+ };+ setParameters(updated);+ }}+ />+ <Input+ className="max-w-none font-mono text-xs"+ placeholder="/path?code={{PARTNER_LINK_KEY}}"+ type="text"+ autoComplete="off"+ aria-label={+ parameters.length > 1+ ? `Custom parameter value ${index + 1}`+ : "Custom parameter value"+ }+ value={param.value}+ onChange={(e) => {+ const updated = [...parameters];+ updated[index] = {+ ...updated[index],+ value: e.target.value,+ };+ setParameters(updated);+ }}+ />+ </div>+ <button+ type="button"+ onClick={() =>+ setParameters(parameters.filter((_, i) => i !== index))+ }+ className="text-neutral-400 transition-colors hover:text-red-500"+ aria-label={+ parameters.length > 1+ ? `Remove custom parameter ${index + 1}`+ : "Remove custom parameter"+ }+ >+ <Xmark className="size-4" aria-hidden />+ </button>+ </div>+ ))}++ <Button+ type="button"+ variant="secondary"+ onClick={() =>+ setParameters([...parameters, { key: "", value: "" }])+ }+ icon={<Plus className="size-3.5" />}+ text="Add Parameter"+ className="h-7 w-fit px-2 text-xs"+ />+ </div>++ <p className="mt-3 text-xs text-neutral-400">+ Custom values may include text and macros. Every {"{{...}}"} must+ be a supported macro or saving will fail.+ </p>+ </div>+ </div>++ <div className="flex items-center justify-end rounded-b-lg border-t border-neutral-200 bg-neutral-50 px-4 py-3">+ <div className="shrink-0">+ <Button+ type="submit"+ variant="primary"+ text="Save changes"+ className="h-8 w-fit"+ loading={isUpdating}+ disabled={!isDirty || isUpdating}+ />+ </div>+ </div>+ </div>+ </form>+ );+};diff --git a/apps/web/lib/integrations/appsflyer/update-settings.ts b/apps/web/lib/integrations/appsflyer/update-settings.tsnew file mode 100644index 0000000000..18745ddb0d--- /dev/null+++ b/apps/web/lib/integrations/appsflyer/update-settings.ts@@ -0,0 +1,111 @@+"use server";++import { authActionClient } from "@/lib/actions/safe-action";+import { qstash } from "@/lib/cron";+import { isAppsFlyerTrackingUrl } from "@/lib/middleware/utils/is-appsflyer-tracking-url";+import { prisma } from "@dub/prisma";+import { APP_DOMAIN_WITH_NGROK, APPSFLYER_INTEGRATION_ID } from "@dub/utils";+import { revalidatePath } from "next/cache";+import * as z from "zod/v4";+import { appsFlyerSettingsSchema } from "./schema";++const schema = appsFlyerSettingsSchema.extend({+ workspaceId: z.string(),+});++export const updateAppsFlyerSettingsAction = authActionClient+ .inputSchema(schema)+ .action(async ({ parsedInput, ctx }) => {+ const { workspace } = ctx;++ // Normalize: trim whitespace and drop empty entries+ const appIds = parsedInput.appIds+ .map((id) => id.trim())+ .filter((id) => id.length > 0);++ const requiredParameters = parsedInput.requiredParameters.map((p) => ({+ key: p.key.trim(),+ value: p.value.trim(),+ }));++ const parameters = parsedInput.parameters+ .map((p) => ({+ key: p.key.trim(),+ value: p.value.trim(),+ }))+ .filter((p) => p.key.length > 0 && p.value.length > 0);++ const installedIntegration = await prisma.installedIntegration.findFirst({+ where: {+ integrationId: APPSFLYER_INTEGRATION_ID,+ projectId: workspace.id,+ },+ select: {+ id: true,+ settings: true,+ },+ });++ if (!installedIntegration) {+ throw new Error(+ "AppsFlyer integration is not installed on your workspace.",+ );+ }++ const current = appsFlyerSettingsSchema.parse(+ installedIntegration.settings ?? {},+ );++ await prisma.installedIntegration.update({+ where: {+ id: installedIntegration.id,+ },+ data: {+ settings: {+ ...current,+ appIds,+ requiredParameters,+ parameters,+ },+ },+ });++ const parametersChanged =+ JSON.stringify(current.parameters) !== JSON.stringify(parameters) ||+ JSON.stringify(current.requiredParameters) !==+ JSON.stringify(requiredParameters);++ // Re-apply updated parameters to all existing AppsFlyer default links+ if (parametersChanged) {+ const defaultLinks = await prisma.partnerGroupDefaultLink.findMany({+ where: {+ program: {+ workspaceId: workspace.id,+ },+ },+ select: {+ id: true,+ url: true,+ },+ });++ const appsFlyerDefaultLinks = defaultLinks.filter((link) =>+ isAppsFlyerTrackingUrl(link.url),+ );++ if (appsFlyerDefaultLinks.length > 0) {+ await Promise.allSettled(+ appsFlyerDefaultLinks.map((defaultLink) =>+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/update-default-links`,+ body: {+ defaultLinkId: defaultLink.id,+ },+ }),+ ),+ );+ }+ }++ revalidatePath(`/${workspace.slug}/settings/integrations/appsflyer`);+ });diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex c4c09e1c55..a4e9ecddd8 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -29,6 +29,7 @@ import { createResponseWithCookies } from "./utils/create-response-with-cookies"import { detectBot } from "./utils/detect-bot";import { getFinalUrl } from "./utils/get-final-url";import { getIdentityHash } from "./utils/get-identity-hash";+import { isAppsFlyerTrackingUrl } from "./utils/is-appsflyer-tracking-url";import { isIosAppStoreUrl } from "./utils/is-ios-app-store-url";import { isSingularTrackingUrl } from "./utils/is-singular-tracking-url";import { isSupportedCustomURIScheme } from "./utils/is-supported-custom-uri-scheme";@@ -159,9 +160,12 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {// if the following is true, we need to cache the clickId data (so it's available for subsequent /track/lead requests):// - trackConversion is enabled// - it's a partner link- // - it's a Singular tracking URL+ // - it's a Singular or AppsFlyer tracking URLconst shouldCacheClickId =- trackConversion || isPartnerLink || isSingularTrackingUrl(url);+ trackConversion ||+ isPartnerLink ||+ isSingularTrackingUrl(url) ||+ isAppsFlyerTrackingUrl(url);// by default, we only index default dub domain links (e.g. dub.sh)// everything else is not indexed by default, unless the user has explicitly set it to be indexeddiff --git a/apps/web/lib/middleware/utils/get-final-url.ts b/apps/web/lib/middleware/utils/get-final-url.tsindex e4a082a5cf..4d0e6127b0 100644--- a/apps/web/lib/middleware/utils/get-final-url.ts+++ b/apps/web/lib/middleware/utils/get-final-url.ts@@ -5,6 +5,7 @@ import {import { getUrlFromStringIfValid } from "@dub/utils/src/functions";import { ipAddress } from "@vercel/functions";import { NextRequest, userAgent } from "next/server";+import { isAppsFlyerTrackingUrl } from "./is-appsflyer-tracking-url";import { isGooglePlayStoreUrl } from "./is-google-play-store-url";import { isSingularTrackingUrl } from "./is-singular-tracking-url";import { parse } from "./parse";@@ -55,6 +56,34 @@ export const getFinalUrl = (}}+ // for AppsFlyer tracking links+ if (isAppsFlyerTrackingUrl(url)) {+ const { ua } = userAgent(req);+ const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;++ // set hardcoded query params+ urlObj.searchParams.set("pid", "dubinc_int");++ if (clickId) {+ urlObj.searchParams.set("clickid", clickId);+ }++ urlObj.searchParams.set("af_ua", ua);++ if (ip) {+ urlObj.searchParams.set("af_ip", ip);+ }++ // set dynamic params (if not exist)+ if (!urlObj.searchParams.has("c") && via) {+ urlObj.searchParams.set("c", via);+ }++ if (!urlObj.searchParams.has("af_siteid") && via) {+ urlObj.searchParams.set("af_siteid", via);+ }+ }+// for Singular tracking linksif (isSingularTrackingUrl(url)) {const ua = userAgent(req);@@ -62,18 +91,17 @@ export const getFinalUrl = (urlObj.searchParams.set("cl", clickId ?? "");urlObj.searchParams.set("ua", ua?.ua ?? "");urlObj.searchParams.set("ip", ip ?? "");- }+ // Polyfill wpcn & wpcl params for Singular integration+ const wpcn = urlObj.searchParams.get("wpcn");+ const wpcl = urlObj.searchParams.get("wpcl");- // Polyfill wpcn & wpcl params for Singular integration- const wpcn = urlObj.searchParams.get("wpcn");- const wpcl = urlObj.searchParams.get("wpcl");-- if (wpcn && wpcn === "{via}") {- urlObj.searchParams.set("wpcn", via ?? "");- }+ if (wpcn && wpcn === "{via}") {+ urlObj.searchParams.set("wpcn", via ?? "");+ }- if (wpcl && wpcl === "{dub_id}") {- urlObj.searchParams.set("wpcl", clickId ?? "");+ if (wpcl && wpcl === "{dub_id}") {+ urlObj.searchParams.set("wpcl", clickId ?? "");+ }}// for Google Play Store linksdiff --git a/apps/web/lib/middleware/utils/is-appsflyer-tracking-url.ts b/apps/web/lib/middleware/utils/is-appsflyer-tracking-url.tsnew file mode 100644index 0000000000..94277e1858--- /dev/null+++ b/apps/web/lib/middleware/utils/is-appsflyer-tracking-url.ts@@ -0,0 +1,12 @@+export const isAppsFlyerTrackingUrl = (url: string | null | undefined) => {+ if (!url) {+ return false;+ }++ try {+ const parsedUrl = new URL(url);+ return parsedUrl.hostname.endsWith(".onelink.me");+ } catch (error) {+ return false;+ }+};diff --git a/apps/web/lib/plan-capabilities.ts b/apps/web/lib/plan-capabilities.tsindex 96d6b9922f..1726080a9d 100644--- a/apps/web/lib/plan-capabilities.ts+++ b/apps/web/lib/plan-capabilities.ts@@ -21,5 +21,7 @@ export const getPlanCapabilities = (canUseGroupMoveRule: !!plan && ["enterprise", "advanced"].includes(plan),canUseBountySocialMetrics:!!plan && ["enterprise", "advanced"].includes(plan),+ canInstallAdvancedIntegrations:+ !!plan && ["enterprise", "advanced"].includes(plan),};};diff --git a/apps/web/scripts/create-integration.ts b/apps/web/scripts/create-integration.tsindex d97c226e9b..68e252749a 100644--- a/apps/web/scripts/create-integration.ts+++ b/apps/web/scripts/create-integration.ts@@ -7,15 +7,15 @@ async function main() {const integration = await prisma.integration.create({data: {id: createId({ prefix: "int_" }),- name: "Hubspot",- slug: "hubspot",- description: "Hubspot",+ name: "AppsFlyer",+ slug: "appsflyer",+ description:+ "Listen to AppsFlyer postbacks and track them as lead/sale conversion events on Dub.",developer: "Dub",website: "https://dub.co",verified: true,projectId: DUB_WORKSPACE_ID,- category: "",- guideUrl: "",+ category: "analytics",},});diff --git a/apps/web/scripts/test-appsflyer.ts b/apps/web/scripts/test-appsflyer.tsnew file mode 100644index 0000000000..691ffa3696--- /dev/null+++ b/apps/web/scripts/test-appsflyer.ts@@ -0,0 +1,28 @@+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import "dotenv-flow/config";++async function main() {+ const trackLeadSearchParams = new URLSearchParams({+ appId: "id123",+ partnerEventId: "lead",+ clickId: "OcDa0EUdcs2XcRU6",+ eventName: "Signup",+ customerExternalId: "af+customer+2",+ });++ const trackSaleSearchParams = new URLSearchParams({+ appId: "id123",+ partnerEventId: "sale",+ customerExternalId: "af+customer+2",+ amount: "2900",+ currency: "usd",+ eventName: "Purchase",+ });++ console.log({+ trackLead: `${APP_DOMAIN_WITH_NGROK}/api/appsflyer/webhook?${trackLeadSearchParams.toString()}`,+ trackSale: `${APP_DOMAIN_WITH_NGROK}/api/appsflyer/webhook?${trackSaleSearchParams.toString()}`,+ });+}++main();diff --git a/apps/web/tests/redirects/index.test.ts b/apps/web/tests/redirects/index.test.tsindex 94379fb06c..2252018719 100644--- a/apps/web/tests/redirects/index.test.ts+++ b/apps/web/tests/redirects/index.test.ts@@ -180,6 +180,18 @@ describe.runIf(env.CI)("Link Redirects", async () => {expect(response.status).toBe(302);});+ test("appsflyer tracking url", async () => {+ const response = await fetch(`${h.baseUrl}/appsflyer`, fetchOptions);++ // location to include clickid, af_siteid, af_ip, af_ua query params+ expect(response.headers.get("location")).toMatch(/pid=dubinc_int/);+ expect(response.headers.get("location")).toMatch(/clickid=[a-zA-Z0-9]+/);+ expect(response.headers.get("location")).toMatch(/af_ua=.+/);+ expect(response.headers.get("location")).toMatch(/af_ip=[a-zA-Z0-9.]+/);+ expect(response.headers.get("x-powered-by")).toBe(poweredBy);+ expect(response.status).toBe(302);+ });+test("singular tracking url", async () => {const response = await fetch(`${h.baseUrl}/singular`, fetchOptions);diff --git a/packages/utils/src/constants/integrations.ts b/packages/utils/src/constants/integrations.tsindex 2f7f793d6d..f8e0abe515 100644--- a/packages/utils/src/constants/integrations.ts+++ b/packages/utils/src/constants/integrations.ts@@ -4,3 +4,4 @@ export const SEGMENT_INTEGRATION_ID = "int_zGnSElTzimbz20OWnXerPoKv";export const ZAPIER_INTEGRATION_ID = "clzlmz336000fjeqynwhfv8vo";export const SHOPIFY_INTEGRATION_ID = "int_iWOtrZgmcyU6XDwKr4AYYqLN";export const HUBSPOT_INTEGRATION_ID = "int_ffw3qgrFAahY6qs1hXaH3wHS";+export const APPSFLYER_INTEGRATION_ID = "int_1KN8JP7ET3VQQRF7ZQEVNFPJ5";