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.

manage payment methods

Kiran K31bbb0067cb7
diff --git a/apps/web/app/api/stripe/connect/webhook/route.ts b/apps/web/app/api/stripe/connect/webhook/route.ts
index 16131eacbf..849f4be695 100644
--- a/apps/web/app/api/stripe/connect/webhook/route.ts
+++ b/apps/web/app/api/stripe/connect/webhook/route.ts
@@ -4,17 +4,9 @@ import { NextResponse } from "next/server";
import Stripe from "stripe";
import { accountUpdated } from "./account-updated";
-const relevantEvents = new Set([
- "account.updated",
- "charge.succeeded",
- "payment_method.attached",
- "checkout.session.completed",
- "customer.subscription.updated",
- "customer.subscription.deleted",
- "invoice.payment_failed",
-]);
+const relevantEvents = new Set(["account.updated"]);
-// POST /api/stripe/webhook – listen to Stripe webhooks
+// POST /api/stripe/connect/webhook – listen to Stripe webhooks
export const POST = async (req: Request) => {
const buf = await req.text();
const sig = req.headers.get("Stripe-Signature") as string;
diff --git a/apps/web/app/api/stripe/integration/webhook/route.ts b/apps/web/app/api/stripe/integration/webhook/route.ts
index e3a92b11c2..3b64ab2a74 100644
--- a/apps/web/app/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/api/stripe/integration/webhook/route.ts
@@ -13,6 +13,7 @@ const relevantEvents = new Set([
"account.application.deauthorized",
]);
+// POST /api/stripe/integration/webhook – listen to Stripe webhooks
export const POST = withAxiom(
async (req: Request) => {
const buf = await req.text();
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
index f3e7d1e836..3b86bd1cbf 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
@@ -1,7 +1,13 @@
+import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { stripe } from "@/lib/stripe";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
+import { z } from "zod";
+
+const addPaymentMethodSchema = z.object({
+ method: z.enum(["card", "us_bank_account"]),
+});
export const GET = withWorkspace(async ({ workspace }) => {
if (!workspace.stripeId) {
@@ -20,17 +26,19 @@ export const GET = withWorkspace(async ({ workspace }) => {
}
});
-export const POST = withWorkspace(async ({ workspace }) => {
+export const POST = withWorkspace(async ({ workspace, req }) => {
if (!workspace.stripeId) {
return NextResponse.json({ error: "Workspace does not have a Stripe ID" });
}
- const { url } = await stripe.billingPortal.sessions.create({
+ const { method } = addPaymentMethodSchema.parse(await parseRequestBody(req));
+
+ const { url } = await stripe.checkout.sessions.create({
+ mode: "setup",
customer: workspace.stripeId,
- return_url: `${APP_DOMAIN}/${workspace.slug}/settings/billing`,
- flow_data: {
- type: "payment_method_update",
- },
+ payment_method_types: [method],
+ success_url: `${APP_DOMAIN}/${workspace.slug}/settings/billing`,
+ cancel_url: `${APP_DOMAIN}/${workspace.slug}/settings/billing`,
});
return NextResponse.json({ url });
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-method-types.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-method-types.ts
index 29d0b64ae4..c1572e5b19 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-method-types.ts
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-method-types.ts
@@ -3,13 +3,13 @@
import { CreditCard, GreekTemple, StripeLink } from "@dub/ui/icons";
import { Stripe } from "stripe";
-export const PaymentMethodTypesList = (paymentMethod: Stripe.PaymentMethod) =>
+export const PaymentMethodTypesList = (paymentMethod?: Stripe.PaymentMethod) =>
[
{
type: "card",
title: "Card",
icon: CreditCard,
- description: paymentMethod.card
+ description: paymentMethod?.card
? `Connected ${paymentMethod.card.brand} ***${paymentMethod.card.last4}`
: "No card connected",
},
@@ -17,7 +17,7 @@ export const PaymentMethodTypesList = (paymentMethod: Stripe.PaymentMethod) =>
type: "us_bank_account",
title: "ACH",
icon: GreekTemple,
- description: paymentMethod.us_bank_account
+ description: paymentMethod?.us_bank_account
? `Connected ${paymentMethod.us_bank_account.account_holder_type} account ending in ${paymentMethod.us_bank_account.last4}`
: "No ACH Debit connected",
},
@@ -26,7 +26,9 @@ export const PaymentMethodTypesList = (paymentMethod: Stripe.PaymentMethod) =>
title: "Link",
icon: StripeLink,
iconBgColor: "bg-green-100",
- description: `Connected Link account ${paymentMethod.link?.email}`,
+ description: paymentMethod?.link
+ ? `Connected Link account ${paymentMethod.link?.email}`
+ : "No Link account connected",
},
] satisfies {
type: Stripe.PaymentMethod.Type;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-methods.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-methods.tsx
index 8d4fb317ef..e35a46ce10 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-methods.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/payment-methods.tsx
@@ -2,9 +2,7 @@
import usePaymentMethods from "@/lib/swr/use-payment-methods";
import useWorkspace from "@/lib/swr/use-workspace";
-import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
-import { Button, TooltipContent } from "@dub/ui";
-import { CreditCard } from "@dub/ui/icons";
+import { Button } from "@dub/ui";
import { cn } from "@dub/utils";
import { useRouter } from "next/navigation";
import { useState } from "react";
@@ -12,23 +10,7 @@ import { Stripe } from "stripe";
import { PaymentMethodTypesList } from "./payment-method-types";
export default function PaymentMethods() {
- const router = useRouter();
- const [isLoading, setIsLoading] = useState(false);
- const { slug, stripeId } = useWorkspace();
- const { paymentMethods } = usePaymentMethods();
-
- const managePaymentMethods = async () => {
- setIsLoading(true);
- const { url } = await fetch(
- `/api/workspaces/${slug}/billing/payment-methods`,
- {
- method: "POST",
- },
- ).then((res) => res.json());
-
- router.push(url);
- setIsLoading(false);
- };
+ const { paymentMethods, loading } = usePaymentMethods();
return (
<div className="rounded-lg border border-neutral-200 bg-white">
@@ -39,50 +21,26 @@ export default function PaymentMethods() {
Manage your payment methods on Dub
</p>
</div>
- <Button
- variant="secondary"
- text="Manage"
- className="h-8 w-fit"
- disabledTooltip={
- !stripeId && (
- <TooltipContent
- title="You must upgrade to a paid plan to manage your payment methods."
- cta="Upgrade"
- href={`/${slug}/upgrade`}
- />
- )
- }
- onClick={managePaymentMethods}
- loading={isLoading}
- />
</div>
<div className="grid gap-4 border-t border-neutral-200 p-6">
- {paymentMethods ? (
- paymentMethods.length > 0 ? (
- paymentMethods.map((paymentMethod) => (
+ {!loading ? (
+ ["card", "us_bank_account"].map((methodType) => {
+ const paymentMethod = paymentMethods?.find(
+ (pm) => pm.type === methodType,
+ );
+
+ return (
<PaymentMethodCard
- key={paymentMethod.id}
+ key={methodType}
+ type={methodType as Stripe.PaymentMethod.Type}
paymentMethod={paymentMethod}
/>
- ))
- ) : (
- <AnimatedEmptyState
- title="No payment methods found"
- description="You haven't added any payment methods yet"
- cardContent={() => (
- <>
- <CreditCard className="size-4 text-neutral-700" />
- <div className="h-2.5 w-24 min-w-0 rounded-sm bg-neutral-200" />
- </>
- )}
- className="border-none md:min-h-[250px]"
- />
- )
+ );
+ })
) : (
<>
<PaymentMethodCardSkeleton />
<PaymentMethodCardSkeleton />
- <PaymentMethodCardSkeleton />
</>
)}
</div>
@@ -91,18 +49,38 @@ export default function PaymentMethods() {
}
const PaymentMethodCard = ({
+ type,
paymentMethod,
}: {
- paymentMethod: Stripe.PaymentMethod;
+ type: Stripe.PaymentMethod.Type;
+ paymentMethod?: Stripe.PaymentMethod;
}) => {
+ const router = useRouter();
+ const { slug } = useWorkspace();
+ const [isLoading, setIsLoading] = useState(false);
+
+ const result = PaymentMethodTypesList(paymentMethod);
+
const {
title,
icon: Icon,
iconBgColor,
description,
- } = PaymentMethodTypesList(paymentMethod).find(
- (method) => method.type === paymentMethod.type,
- ) || PaymentMethodTypesList(paymentMethod)[0];
+ } = result.find((method) => method.type === type) || result[0];
+
+ const managePaymentMethods = async (method: string) => {
+ setIsLoading(true);
+ const { url } = await fetch(
+ `/api/workspaces/${slug}/billing/payment-methods`,
+ {
+ method: "POST",
+ body: JSON.stringify({ method }),
+ },
+ ).then((res) => res.json());
+
+ window.open(url, "_blank");
+ setIsLoading(false);
+ };
return (
<div className="flex items-center justify-between rounded-lg border border-neutral-200 p-4">
@@ -120,6 +98,13 @@ const PaymentMethodCard = ({
<p className="text-sm text-neutral-500">{description}</p>
</div>
</div>
+ <Button
+ variant={paymentMethod ? "secondary" : "primary"}
+ className="h-8 w-fit"
+ text={paymentMethod ? "Manage" : "Connect"}
+ onClick={() => managePaymentMethods(type)}
+ loading={isLoading}
+ />
</div>
);
};
diff --git a/apps/web/scripts/stripe-testing.ts b/apps/web/scripts/stripe-testing.ts
index d82463aa56..12526935fc 100644
--- a/apps/web/scripts/stripe-testing.ts
+++ b/apps/web/scripts/stripe-testing.ts
@@ -4,44 +4,15 @@ import "dotenv-flow/config";
import { stripe } from "./stripe-init";
async function main() {
- // const customer = await stripe.customers.create({
- // email: "[email protected]",
- // metadata: {
- // dubCustomerId: "[email protected]",
- // },
- // });
-
- // console.log(customer);
-
- // Create checkout session for this customer
- const { url } = await stripe.checkout.sessions.create({
- customer_email: "[email protected]",
- success_url: "https://dub.co?session_id={CHECKOUT_SESSION_ID}",
- cancel_url: "https://dub.co",
- line_items: [
- // Recurring
- {
- price: "price_1PE8VYSIvbPMbbGzw4JsqFye",
- quantity: 2,
- },
-
- // One-time
- // {
- // price: "price_1PGxy6SIvbPMbbGz8xFJOPkD",
- // quantity: 2,
- // },
- ],
- // invoice_creation: {
- // enabled: true,
- // },
- mode: "subscription",
- metadata: {
- dubCustomerId: "kiran",
- },
- // customer_creation: "always",
+ const session = await stripe.checkout.sessions.create({
+ mode: "setup",
+ customer: "cus_RPOmxGDnMiVIa3",
+ payment_method_types: ["us_bank_account"],
+ success_url: "https://example.com/success",
+ cancel_url: "https://example.com/cancel",
});
- console.log(url);
+ console.log("Checkout session created:", session);
}
main();