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.

revert the Stripe install

Kiran K380e63ffecbe
diff --git a/apps/web/.env.example b/apps/web/.env.example
index d68aa44328..c5f532c823 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -60,6 +60,7 @@ STRIPE_SECRET_KEY=
STRIPE_WEBHOOK_SECRET=
# Stripe App
+STRIPE_APP_INSTALL_URL=
STRIPE_APP_WEBHOOK_SECRET=
# Shopify App webhook events
diff --git a/apps/web/app/api/stripe/integration/callback/route.ts b/apps/web/app/api/stripe/integration/callback/route.ts
index 1d1ce83ba3..8c6ef04c02 100644
--- a/apps/web/app/api/stripe/integration/callback/route.ts
+++ b/apps/web/app/api/stripe/integration/callback/route.ts
@@ -1,106 +1,81 @@
-import { DubApiError } from "@/lib/api/errors";
-import { parseRequestBody } from "@/lib/api/utils";
-import { withWorkspace } from "@/lib/auth";
+import { getSession } from "@/lib/auth";
import { installIntegration } from "@/lib/integrations/install";
+import { redis } from "@/lib/upstash";
import z from "@/lib/zod";
import { prisma } from "@dub/prisma";
-import { STRIPE_INTEGRATION_ID } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { NextResponse } from "next/server";
+import { APP_DOMAIN, getSearchParams, STRIPE_INTEGRATION_ID } from "@dub/utils";
+import { redirect } from "next/navigation";
+import { NextRequest } from "next/server";
-const CORS_HEADERS = {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "PATCH, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
-};
-
-const updateWorkspaceSchema = z.object({
- stripeAccountId: z.string().nullable(),
+const schema = z.object({
+ state: z.string(),
+ stripe_user_id: z.string().optional(),
+ error: z.string().optional(),
+ error_description: z.string().optional(),
});
-// PATCH /api/stripe/integration/callback - update a workspace with a stripe connect account id
-export const PATCH = withWorkspace(
- async ({ req, workspace, session }) => {
- const body = await parseRequestBody(req);
- const { stripeAccountId } = updateWorkspaceSchema.parse(body);
+export const GET = async (req: NextRequest) => {
+ const session = await getSession();
+
+ if (!session?.user.id) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ const parsed = schema.safeParse(getSearchParams(req.url));
- try {
- const response = await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- stripeConnectId: true,
- },
- });
+ if (!parsed.success) {
+ console.error("[Stripe OAuth callback] Error", parsed.error);
+ return new Response("Invalid request", { status: 400 });
+ }
- waitUntil(
- (async () => {
- const installation = await prisma.installedIntegration.findUnique({
- where: {
- userId_integrationId_projectId: {
- userId: session.user.id,
- projectId: workspace.id,
- integrationId: STRIPE_INTEGRATION_ID,
- },
- },
- select: {
- id: true,
- },
- });
+ const {
+ state,
+ stripe_user_id: stripeAccountId,
+ error,
+ error_description,
+ } = parsed.data;
- // Install the integration if it doesn't exist
- if (!installation) {
- await installIntegration({
- userId: session.user.id,
- workspaceId: workspace.id,
- integrationId: STRIPE_INTEGRATION_ID,
- credentials: {
- stripeConnectId: stripeAccountId,
- },
- });
- }
+ // Find workspace that initiated the Stripe app install
+ const workspaceId = await redis.get<string>(`stripe:install:state:${state}`);
- // Uninstall the integration if the stripe account id is null
- if (installation && stripeAccountId === null) {
- await prisma.installedIntegration.delete({
- where: {
- id: installation.id,
- },
- });
- }
- })(),
- );
+ if (!workspaceId) {
+ redirect(APP_DOMAIN);
+ }
- return NextResponse.json(response, {
- headers: CORS_HEADERS,
- });
- } catch (error) {
- if (error.code === "P2002") {
- throw new DubApiError({
- code: "conflict",
- message: `The stripe connect account "${stripeAccountId}" is already in use.`,
- });
- }
+ // Delete the state key from Redis
+ await redis.del(`stripe:install:state:${state}`);
- throw new DubApiError({
- code: "internal_server_error",
- message: error.message,
- });
+ if (error) {
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ });
+ if (!workspace) {
+ redirect(APP_DOMAIN);
}
- },
- {
- requiredPermissions: ["workspaces.write"],
- requiredAddOn: "conversion",
- },
-);
+ redirect(
+ `${APP_DOMAIN}/${workspace.slug}/settings/integrations/stripe?stripeConnectError=${error_description}`,
+ );
+ } else if (stripeAccountId) {
+ // Update the workspace with the Stripe Connect ID
+ const workspace = await prisma.project.update({
+ where: {
+ id: workspaceId,
+ },
+ data: {
+ stripeConnectId: stripeAccountId,
+ },
+ });
+
+ await installIntegration({
+ integrationId: STRIPE_INTEGRATION_ID,
+ userId: session.user.id,
+ workspaceId: workspace.id,
+ });
+
+ redirect(`${APP_DOMAIN}/${workspace.slug}/settings/integrations/stripe`);
+ }
-export const OPTIONS = () => {
- return new Response(null, {
- status: 204,
- headers: CORS_HEADERS,
- });
-};
+ return new Response("Invalid request", { status: 400 });
+};
\ No newline at end of file
diff --git a/apps/web/lib/actions/get-integration-install-url.ts b/apps/web/lib/actions/get-integration-install-url.ts
index 199ef634ca..a70a8254c6 100644
--- a/apps/web/lib/actions/get-integration-install-url.ts
+++ b/apps/web/lib/actions/get-integration-install-url.ts
@@ -1,6 +1,7 @@
"use server";
import { getSlackInstallationUrl } from "../integrations/slack/install";
+import { getStripeInstallationUrl } from "../integrations/stripe/install";
import z from "../zod";
import { authActionClient } from "./safe-action";
@@ -18,7 +19,12 @@ export const getIntegrationInstallUrl = authActionClient
let url: string | null = null;
- if (integrationSlug === "slack") {
+ if (integrationSlug === "stripe") {
+ if (!workspace.conversionEnabled) {
+ throw new Error("Conversions feature is not enabled.");
+ }
+ url = await getStripeInstallationUrl(workspace.id);
+ } else if (integrationSlug === "slack") {
url = await getSlackInstallationUrl(workspace.id);
} else {
throw new Error("Invalid integration slug");
diff --git a/apps/web/lib/integrations/stripe/install.ts b/apps/web/lib/integrations/stripe/install.ts
new file mode 100644
index 0000000000..d475be4fc2
--- /dev/null
+++ b/apps/web/lib/integrations/stripe/install.ts
@@ -0,0 +1,33 @@
+import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";
+import { redis } from "../../upstash";
+import z from "../../zod";
+
+const envSchema = z.object({
+ STRIPE_APP_INSTALL_URL: z.string(),
+});
+
+export const getStripeInstallationUrl = async (workspaceId: string) => {
+ const state = nanoid(16);
+ await redis.set(`stripe:install:state:${state}`, workspaceId, {
+ ex: 30 * 60,
+ });
+
+ const env = envSchema.safeParse(process.env);
+
+ if (!env.success) {
+ throw new Error(
+ "Stripe App environment variables are not configured properly.",
+ );
+ }
+
+ const { STRIPE_APP_INSTALL_URL } = env.data;
+
+ const url = new URL(STRIPE_APP_INSTALL_URL);
+ url.searchParams.set(
+ "redirect_uri",
+ `${APP_DOMAIN_WITH_NGROK}/api/stripe/integration/callback`,
+ );
+ url.searchParams.set("state", state);
+
+ return url.toString();
+};