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.

Add foreign exchange quote functionality for payout conversions

Kiran K35ac9b9edbc4
diff --git a/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts b/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
index 3c5cb1fdda..3b0174a7e5 100644
--- a/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/confirm/confirm-payouts.ts
@@ -6,6 +6,7 @@ import {
} from "@/lib/partners/cutoff-period";
import { calculatePayoutFeeForMethod } from "@/lib/payment-methods";
import { stripe } from "@/lib/stripe";
+import { createFxQuote } from "@/lib/stripe/create-fx-quote";
import { resend } from "@dub/email/resend";
import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";
import PartnerPayoutConfirmed from "@dub/email/templates/partner-payout-confirmed";
@@ -13,6 +14,11 @@ import { prisma } from "@dub/prisma";
import { chunk, log } from "@dub/utils";
import { Program, Project } from "@prisma/client";
+const paymentMethodToCurrency = {
+ sepa_debit: "eur",
+ acss_debit: "cad",
+} as const;
+
export async function confirmPayouts({
workspace,
program,
@@ -96,8 +102,29 @@ export async function confirmPayouts({
`Using payout fee of ${payoutFee} for payment method ${paymentMethod.type}`,
);
+ const currency = paymentMethodToCurrency[paymentMethod.type] || "usd";
const totalFee = amount * payoutFee;
const total = amount + totalFee;
+ let convertedTotal = total;
+
+ // convert the amount to EUR/CAD if the payment method is sepa_debit or acss_debit
+ if (["sepa_debit", "acss_debit"].includes(paymentMethod.type)) {
+ const fxQuote = await createFxQuote({
+ fromCurrency: "usd",
+ toCurrency: currency,
+ });
+
+ const exchangeRate = fxQuote.rates[currency].exchange_rate;
+
+ if (exchangeRate === null) {
+ throw new Error(
+ `Failed to get exchange rate from Stripe for ${currency}.`,
+ );
+ }
+
+ // Add a 0.5% markup to the exchange rate to cover forex conversion spread
+ convertedTotal = total * exchangeRate * 1.005;
+ }
// Generate the next invoice number
const totalInvoices = await tx.invoice.count({
@@ -125,14 +152,14 @@ export async function confirmPayouts({
}
await stripe.paymentIntents.create({
- amount: invoice.total,
+ amount: convertedTotal,
customer: workspace.stripeId!,
payment_method: paymentMethod.id,
automatic_payment_methods: {
enabled: true,
allow_redirects: "never",
},
- currency: "usd",
+ currency,
confirm: true,
transfer_group: invoice.id,
statement_descriptor: "Dub Partners",
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
index e8cd3089f4..82c89c8e4b 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
@@ -6,7 +6,7 @@ import Stripe from "stripe";
export async function chargeSucceeded(event: Stripe.Event) {
const charge = event.data.object as Stripe.Charge;
- const { id: chargeId, receipt_url, transfer_group } = charge;
+ const { id: chargeId, receipt_url, transfer_group, payment_intent } = charge;
if (!transfer_group) {
console.log("No transfer group found, skipping...");
@@ -57,6 +57,7 @@ export async function chargeSucceeded(event: Stripe.Event) {
receiptUrl: receipt_url,
status: "completed",
paidAt: new Date(),
+ stripePaymentIntentId: payment_intent as string,
},
});
diff --git a/apps/web/lib/stripe/create-fx-quote.ts b/apps/web/lib/stripe/create-fx-quote.ts
new file mode 100644
index 0000000000..83e41ef0c9
--- /dev/null
+++ b/apps/web/lib/stripe/create-fx-quote.ts
@@ -0,0 +1,39 @@
+import { z } from "zod";
+
+const fxQuoteSchema = z.object({
+ rates: z.record(
+ z.string(),
+ z.object({
+ exchange_rate: z.number(),
+ }),
+ ),
+ to_currency: z.string(),
+});
+
+export async function createFxQuote({
+ fromCurrency,
+ toCurrency,
+}: {
+ fromCurrency: string;
+ toCurrency: string;
+}) {
+ const fxQuoteResponse = await fetch("https://api.stripe.com/v1/fx_quotes", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
+ "Stripe-Version": "2025-05-28.basil;fx_quote_preview=v1",
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ from_currencies: fromCurrency,
+ to_currency: toCurrency,
+ lock_duration: "none",
+ }),
+ });
+
+ const fxQuote = await fxQuoteResponse.json();
+
+ console.log(["/v1/fx_quotes"], fxQuote);
+
+ return fxQuoteSchema.parse(fxQuote);
+}
diff --git a/packages/prisma/schema/invoice.prisma b/packages/prisma/schema/invoice.prisma
index 9f49641141..a557f61256 100644
--- a/packages/prisma/schema/invoice.prisma
+++ b/packages/prisma/schema/invoice.prisma
@@ -5,18 +5,19 @@ enum InvoiceStatus {
}
model Invoice {
- id String @id @default(cuid())
- programId String
- workspaceId String
- number String? @unique // This starts with the customer’s unique invoicePrefix
- status InvoiceStatus @default(processing)
- amount Int @default(0)
- fee Int @default(0)
- total Int @default(0)
- receiptUrl String? @db.Text
- failedReason String? @db.Text
- createdAt DateTime @default(now())
- paidAt DateTime?
+ id String @id @default(cuid())
+ programId String
+ workspaceId String
+ number String? @unique // This starts with the customer’s unique invoicePrefix
+ status InvoiceStatus @default(processing)
+ amount Int @default(0)
+ fee Int @default(0)
+ total Int @default(0)
+ receiptUrl String? @db.Text
+ failedReason String? @db.Text
+ stripePaymentIntentId String?
+ createdAt DateTime @default(now())
+ paidAt DateTime?
payouts Payout[]
program Program @relation(fields: [programId], references: [id])