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.

Retrieve connected customer for attribution

Steven Teyca931d289309
diff --git a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
index ab782af3bf..5bcd05a4e0 100644
--- a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -23,11 +23,12 @@ import { Customer } from "@dub/prisma/client";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { getConnectedCustomer } from "./utils";
// Handle event "checkout.session.completed"
export async function checkoutSessionCompleted(event: Stripe.Event) {
let charge = event.data.object as Stripe.Checkout.Session;
- const dubCustomerId = charge.metadata?.dubCustomerId;
+ let dubCustomerId = charge.metadata?.dubCustomerId;
const clientReferenceId = charge.client_reference_id;
const stripeAccountId = event.account as string;
const stripeCustomerId = charge.customer as string;
@@ -42,45 +43,12 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
let linkId: string;
/*
- for regular stripe checkout setup:
- - if dubCustomerId is found, we update the customer with the stripe customerId
- - we then find the lead event using the customer's unique ID on Dub
- - the lead event will then be passed to the remaining logic to record a sale
- */
- if (dubCustomerId) {
- try {
- // Update customer with stripe customerId if exists
- customer = await prisma.customer.update({
- where: {
- projectConnectId_externalId: {
- projectConnectId: stripeAccountId,
- externalId: dubCustomerId,
- },
- },
- data: {
- stripeCustomerId,
- },
- });
- } catch (error) {
- // Skip if customer not found
- console.log(error);
- return `Customer with dubCustomerId ${dubCustomerId} not found, skipping...`;
- }
-
- // Find lead
- leadEvent = await getLeadEvent({ customerId: customer.id }).then(
- (res) => res.data[0],
- );
-
- linkId = leadEvent.link_id;
-
- /*
for stripe checkout links:
- if client_reference_id is a dub_id, we find the click event
- the click event will be used to create a lead event + customer
- the lead event will then be passed to the remaining logic to record a sale
*/
- } else if (clientReferenceId?.startsWith("dub_id_")) {
+ if (clientReferenceId?.startsWith("dub_id_")) {
const dubClickId = clientReferenceId.split("dub_id_")[1];
clickEvent = await getClickEvent({ clickId: dubClickId }).then(
@@ -169,7 +137,54 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
// if it's not either a regular stripe checkout setup or a stripe checkout link,
// we skip the event
} else {
- return `Customer ID not found in Stripe checkout session metadata and client_reference_id is not a dub_id, skipping...`;
+ /*
+ for regular stripe checkout setup:
+ - if dubCustomerId not provided, we try to find the customer on the connected account
+ - if present:
+ - we update the customer with the stripe customerId
+ - we then find the lead event using the customer's unique ID on Dub
+ - the lead event will then be passed to the remaining logic to record a sale
+ - if not present, we skip the event
+ */
+
+ if (!dubCustomerId) {
+ const connectedCustomer = await getConnectedCustomer({
+ stripeCustomerId,
+ stripeAccountId,
+ });
+
+ if (!connectedCustomer || !connectedCustomer.metadata.dubCustomerId) {
+ return `Customer ID not found in Stripe checkout session metadata (nor is it available on the connected customer ${stripeCustomerId}) and client_reference_id is not a dub_id, skipping...`;
+ }
+
+ dubCustomerId = connectedCustomer.metadata.dubCustomerId;
+ }
+
+ try {
+ // Update customer with stripe customerId if exists
+ customer = await prisma.customer.update({
+ where: {
+ projectConnectId_externalId: {
+ projectConnectId: stripeAccountId,
+ externalId: dubCustomerId,
+ },
+ },
+ data: {
+ stripeCustomerId,
+ },
+ });
+ } catch (error) {
+ // Skip if customer not found
+ console.log(error);
+ return `Customer with dubCustomerId ${dubCustomerId} not found, skipping...`;
+ }
+
+ // Find lead
+ leadEvent = await getLeadEvent({ customerId: customer.id }).then(
+ (res) => res.data[0],
+ );
+
+ linkId = leadEvent.link_id;
}
if (charge.amount_total === 0) {
diff --git a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
index a179441e4c..a8fec6b53d 100644
--- a/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/api/stripe/integration/webhook/invoice-paid.ts
@@ -10,22 +10,44 @@ import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { getConnectedCustomer } from "./utils";
// Handle event "invoice.paid"
export async function invoicePaid(event: Stripe.Event) {
const invoice = event.data.object as Stripe.Invoice;
+ const stripeAccountId = event.account as string;
const stripeCustomerId = invoice.customer as string;
const invoiceId = invoice.id;
// Find customer using projectConnectId and stripeCustomerId
- const customer = await prisma.customer.findUnique({
+ let customer = await prisma.customer.findUnique({
where: {
stripeCustomerId,
},
});
+ // if customer is not found, we try to find it on the connected customer
if (!customer) {
- return `Customer with stripeCustomerId ${stripeCustomerId} not found, skipping...`;
+ const connectedCustomer = await getConnectedCustomer({
+ stripeCustomerId,
+ stripeAccountId,
+ });
+
+ if (connectedCustomer?.metadata.dubCustomerId) {
+ customer = await prisma.customer.findUnique({
+ where: {
+ projectConnectId_externalId: {
+ projectConnectId: stripeAccountId,
+ externalId: connectedCustomer.metadata.dubCustomerId,
+ },
+ },
+ });
+ }
+ }
+
+ // if customer is still not found, we skip the event
+ if (!customer) {
+ return `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor is it available on the connected customer ${stripeCustomerId}), skipping...`;
}
// Skip if invoice id is already processed
diff --git a/apps/web/app/api/stripe/integration/webhook/utils.ts b/apps/web/app/api/stripe/integration/webhook/utils.ts
index 4746f0aa25..4bd89690e0 100644
--- a/apps/web/app/api/stripe/integration/webhook/utils.ts
+++ b/apps/web/app/api/stripe/integration/webhook/utils.ts
@@ -2,6 +2,7 @@ import { createId } from "@/lib/api/create-id";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { stripeAppClient } from "@/lib/stripe";
import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
@@ -124,3 +125,29 @@ export async function createNewCustomer(event: Stripe.Event) {
return `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`;
}
+
+export async function getConnectedCustomer({
+ stripeCustomerId,
+ stripeAccountId,
+}: {
+ stripeCustomerId: string;
+ stripeAccountId: string;
+}) {
+ try {
+ const connectedCustomer = await stripeAppClient.customers.retrieve(
+ stripeCustomerId,
+ {
+ stripeAccount: stripeAccountId,
+ },
+ );
+
+ if (connectedCustomer.deleted) {
+ return null;
+ }
+
+ return connectedCustomer;
+ } catch (error) {
+ console.error(error);
+ return null;
+ }
+}
diff --git a/apps/web/lib/stripe/index.ts b/apps/web/lib/stripe/index.ts
index 2e6d37c89f..bee86ca27d 100644
--- a/apps/web/lib/stripe/index.ts
+++ b/apps/web/lib/stripe/index.ts
@@ -7,3 +7,15 @@ export const stripe = new Stripe(`${process.env.STRIPE_SECRET_KEY}`, {
version: "0.1.0",
},
});
+
+// Stripe Integration App client
+export const stripeAppClient = new Stripe(
+ `${process.env.STRIPE_APP_SECRET_KEY}`,
+ {
+ apiVersion: "2022-11-15",
+ appInfo: {
+ name: "Dub.co",
+ version: "0.1.0",
+ },
+ },
+);
diff --git a/apps/web/scripts/backfill-stripe-connect.ts b/apps/web/scripts/partners/backfill-stripe-connect.ts
similarity index 92%
rename from apps/web/scripts/backfill-stripe-connect.ts
rename to apps/web/scripts/partners/backfill-stripe-connect.ts
index 3cab44343b..1ef698342b 100644
--- a/apps/web/scripts/backfill-stripe-connect.ts
+++ b/apps/web/scripts/partners/backfill-stripe-connect.ts
@@ -1,6 +1,6 @@
import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
-import { stripe } from "../lib/stripe";
+import { stripeConnectClient } from "./stripe";
async function main() {
const partners = await prisma.partner.findMany({
@@ -19,7 +19,7 @@ async function main() {
await Promise.allSettled(
partners.map(async (partner) => {
const [firstName, lastName] = partner.name.split(" ");
- const res = await stripe.accounts.create({
+ const res = await stripeConnectClient.accounts.create({
type: "express",
business_type: "individual",
email: partner.email!,
diff --git a/apps/web/scripts/backfill-webhook-events.ts b/apps/web/scripts/stripe/backfill-stripe-webhook-events.ts
similarity index 76%
rename from apps/web/scripts/backfill-webhook-events.ts
rename to apps/web/scripts/stripe/backfill-stripe-webhook-events.ts
index cf439ae927..b8390383f9 100644
--- a/apps/web/scripts/backfill-webhook-events.ts
+++ b/apps/web/scripts/stripe/backfill-stripe-webhook-events.ts
@@ -1,19 +1,6 @@
import { prisma } from "@dub/prisma";
import "dotenv-flow/config";
-import Stripe from "stripe";
-
-/*
- One time script to backfill webhook events for connected customers
- that don't have a stripe customer id
-*/
-
-export const stripe = new Stripe(`${process.env.STRIPE_APP_SECRET_KEY}`, {
- apiVersion: "2022-11-15",
- appInfo: {
- name: "Dub.co",
- version: "0.1.0",
- },
-});
+import { stripeAppClient } from "../../lib/stripe";
const stripeAccountId = "xxx";
@@ -39,7 +26,7 @@ async function main() {
if (!customer.email) return;
if (customer.stripeCustomerId) return;
- const stripeCustomer = await stripe.customers.list(
+ const stripeCustomer = await stripeAppClient.customers.list(
{
email: customer.email,
},
diff --git a/apps/web/scripts/stripe/get-connected-customer.ts b/apps/web/scripts/stripe/get-connected-customer.ts
new file mode 100644
index 0000000000..0850a6257c
--- /dev/null
+++ b/apps/web/scripts/stripe/get-connected-customer.ts
@@ -0,0 +1,15 @@
+import "dotenv-flow/config";
+import { stripeAppClient } from "../../lib/stripe";
+
+async function main() {
+ const connectedCustomer = await stripeAppClient.customers.retrieve(
+ "cus_SCCWOFWpb9aU5v",
+ {
+ stripeAccount: "acct_1QmcXXKojVEYZPlX",
+ },
+ );
+
+ console.log(connectedCustomer);
+}
+
+main();