The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Stripe app improvements
Kiran Kf039016d22f2
diff --git a/apps/web/app/api/oauth/token/route.ts b/apps/web/app/api/oauth/token/route.tsindex 1c07715886..bf87df38f0 100644--- a/apps/web/app/api/oauth/token/route.ts+++ b/apps/web/app/api/oauth/token/route.ts@@ -4,6 +4,12 @@ import { NextRequest, NextResponse } from "next/server";import { exchangeAuthCodeForToken } from "./exchange-code-for-token";import { refreshAccessToken } from "./refresh-access-token";+const CORS_HEADERS = {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "POST, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type, Authorization",+};+// POST /api/oauth/token - Exchange authorization code for access token and refresh access tokenexport async function POST(req: NextRequest) {try {@@ -13,11 +19,23 @@ export async function POST(req: NextRequest) {if (validatedData.grant_type === "authorization_code") {return NextResponse.json(await exchangeAuthCodeForToken(req, validatedData),+ {+ headers: CORS_HEADERS,+ },);} else if (validatedData.grant_type === "refresh_token") {- return NextResponse.json(await refreshAccessToken(req, validatedData));+ return NextResponse.json(await refreshAccessToken(req, validatedData), {+ headers: CORS_HEADERS,+ });}} catch (error) {return handleAndReturnErrorResponse(error);}}++export const OPTIONS = () => {+ return new Response(null, {+ status: 204,+ headers: CORS_HEADERS,+ });+};diff --git a/apps/web/app/api/oauth/userinfo/route.ts b/apps/web/app/api/oauth/userinfo/route.tsindex 7fd3bccab8..23dad82ef0 100644--- a/apps/web/app/api/oauth/userinfo/route.ts+++ b/apps/web/app/api/oauth/userinfo/route.ts@@ -5,6 +5,12 @@ import { NextRequest, NextResponse } from "next/server";export const dynamic = "force-dynamic";+const CORS_HEADERS = {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "GET, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type, Authorization",+};+// GET /api/oauth/userinfo - get user info by access tokenexport async function GET(req: NextRequest) {try {@@ -60,8 +66,17 @@ export async function GET(req: NextRequest) {},};- return NextResponse.json(userInfo);+ return NextResponse.json(userInfo, {+ headers: CORS_HEADERS,+ });} catch (e) {return handleAndReturnErrorResponse(e);}}++export const OPTIONS = () => {+ return new Response(null, {+ status: 204,+ headers: CORS_HEADERS,+ });+};diff --git a/apps/web/app/api/stripe/integration/callback/route.ts b/apps/web/app/api/stripe/integration/callback/route.tsindex 4ca9489d4f..3d46a1fb35 100644--- a/apps/web/app/api/stripe/integration/callback/route.ts+++ b/apps/web/app/api/stripe/integration/callback/route.ts@@ -1,81 +1,108 @@-import { getSession } from "@/lib/auth";+import { DubApiError } from "@/lib/api/errors";+import { parseRequestBody } from "@/lib/api/utils";+import { withWorkspace } 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 { APP_DOMAIN, getSearchParams, STRIPE_INTEGRATION_ID } from "@dub/utils";-import { redirect } from "next/navigation";-import { NextRequest } from "next/server";+// import { STRIPE_INTEGRATION_ID } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";-const schema = z.object({- state: z.string(),- stripe_user_id: z.string().optional(),- error: z.string().optional(),- error_description: z.string().optional(),-});+const STRIPE_INTEGRATION_ID = "int_JpQs8mHb8Umci4waZeRSAkYE";-export const GET = async (req: NextRequest) => {- const session = await getSession();+const CORS_HEADERS = {+ "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Methods": "PATCH, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type, Authorization",+};- if (!session?.user.id) {- return new Response("Unauthorized", { status: 401 });- }+const updateWorkspaceSchema = z.object({+ stripeAccountId: z.string().nullable(),+});- const parsed = schema.safeParse(getSearchParams(req.url));+// 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);- if (!parsed.success) {- console.error("[Stripe OAuth callback] Error", parsed.error);- return new Response("Invalid request", { status: 400 });- }+ try {+ const response = await prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ stripeConnectId: true,+ },+ });- const {- state,- stripe_user_id: stripeAccountId,- error,- error_description,- } = parsed.data;+ 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,+ },+ });- // Find workspace that initiated the Stripe app install- const workspaceId = await redis.get<string>(`stripe:install:state:${state}`);+ // 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,+ },+ });+ }- if (!workspaceId) {- redirect(APP_DOMAIN);- }+ // Uninstall the integration if the shopify store id is null+ if (installation && stripeAccountId === null) {+ await prisma.installedIntegration.delete({+ where: {+ id: installation.id,+ },+ });+ }+ })(),+ );- // Delete the state key from Redis- await redis.del(`stripe:install:state:${state}`);+ 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.`,+ });+ }- if (error) {- const workspace = await prisma.project.findUnique({- where: {- id: workspaceId,- },- });- if (!workspace) {- redirect(APP_DOMAIN);+ throw new DubApiError({+ code: "internal_server_error",+ message: error.message,+ });}- 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`);- }+ },+ {+ requiredPermissions: ["workspaces.write"],+ requiredAddOn: "conversion",+ },+);- return new Response("Invalid request", { status: 400 });+export const OPTIONS = () => {+ return new Response(null, {+ status: 204,+ headers: CORS_HEADERS,+ });};diff --git a/packages/stripe-app/src/utils/constants.ts b/packages/stripe-app/src/utils/constants.tsnew file mode 100644index 0000000000..97fbdef050--- /dev/null+++ b/packages/stripe-app/src/utils/constants.ts@@ -0,0 +1,3 @@+export const DUB_CLIENT_ID =+ "dub_app_c572e2fef56dc49d827dd77e58322536fc52e9e5b1f2c498";+export const DUB_HOST = "http://localhost:8888";diff --git a/packages/stripe-app/src/utils/dub.ts b/packages/stripe-app/src/utils/dub.tsnew file mode 100644index 0000000000..28802483d8--- /dev/null+++ b/packages/stripe-app/src/utils/dub.ts@@ -0,0 +1,93 @@+import Stripe from "stripe";+import { DUB_HOST } from "./constants";+import { getValidToken } from "./oauth";+import { deleteSecret, getSecret } from "./secrets";+import { Workspace } from "./types";++export async function updateWorkspace({+ stripe,+ workspaceId,+ accountId,+}: {+ stripe: Stripe;+ workspaceId: string;+ accountId: string | null;+}) {+ const token = await getValidToken({ stripe });++ const response = await fetch(+ `${DUB_HOST}/api/stripe/integration/callback?workspaceId=${workspaceId}`,+ {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${token.access_token}`,+ },+ body: JSON.stringify({+ stripeAccountId: accountId,+ }),+ },+ );++ if (!response.ok) {+ const data = await response.json();++ throw new Error("Failed to update workspace.", {+ cause: data.error,+ });+ }+}++export async function fetchWorkspace({ stripe }: { stripe: Stripe }) {+ const workspace = await getSecret({+ stripe,+ name: "dub_workspace",+ });++ if (!workspace) {+ return null;+ }++ return JSON.parse(workspace) as Workspace;+}++export async function connectWorkspace({+ stripe,+ workspaceId,+ accountId,+}: {+ stripe: Stripe;+ workspaceId: string;+ accountId: string;+}) {+ await updateWorkspace({+ stripe,+ workspaceId,+ accountId,+ });+}++export async function disconnectWorkspace({+ stripe,+ workspaceId,+}: {+ stripe: Stripe;+ workspaceId: string;+}) {+ await updateWorkspace({+ stripe,+ workspaceId,+ accountId: null,+ });++ await Promise.all([+ deleteSecret({+ stripe,+ name: "dub_token",+ }),++ deleteSecret({+ stripe,+ name: "dub_workspace",+ }),+ ]);+}diff --git a/packages/stripe-app/src/utils/oauth.ts b/packages/stripe-app/src/utils/oauth.tsnew file mode 100644index 0000000000..e69b3a7e1d--- /dev/null+++ b/packages/stripe-app/src/utils/oauth.ts@@ -0,0 +1,100 @@+// Handle the Dub OAuth flow++import Stripe from "stripe";+import { DUB_CLIENT_ID, DUB_HOST } from "./constants";+import { getSecret } from "./secrets";+import { Token, Workspace } from "./types";++const getRedirectURL = (mode: "live" | "test") => {+ return `https://dashboard.stripe.com/${+ mode === "test" ? "test/" : ""+ }apps-oauth/dub.co`;+};++// Returns the authorization URL+export function getOAuthUrl({+ state,+ challenge,+}: {+ state: string;+ challenge: string;+}) {+ return `${DUB_HOST}/oauth/authorize?client_id=${DUB_CLIENT_ID}&redirect_uri=${getRedirectURL("test")}&response_type=code&scope=workspaces.write&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`;+}++// Exchanges the authorization code for an access token+export async function getToken({+ code,+ verifier,+}: {+ code: string;+ verifier: string;+}) {+ const url = `${DUB_HOST}/api/oauth/token`;++ try {+ const response = await fetch(url, {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ client_id: DUB_CLIENT_ID,+ redirect_uri: getRedirectURL("test"),+ grant_type: "authorization_code",+ code_verifier: verifier,+ code,+ }),+ });++ const data = await response.json();++ if (!response.ok) {+ throw new Error(data.error.message);+ }++ return data as Token;+ } catch (e) {+ console.error("Unable to retrieve Dub access token:", (e as Error).message);+ }+}++// Returns the user info from Dub using the access token+export async function getUserInfo({ token }: { token: Token }) {+ const response = await fetch(`${DUB_HOST}/api/oauth/userinfo`, {+ headers: {+ Authorization: `Bearer ${token.access_token}`,+ },+ });++ const data = await response.json();++ if (!response.ok) {+ throw new Error("Failed to fetch user info from Dub.", {+ cause: data.error,+ });+ }++ const { workspace } = data as { workspace: Workspace };++ return workspace;+}++// If the token is expired, it will refresh it+export async function getValidToken({ stripe }: { stripe: Stripe }) {+ const token = await getSecret({+ stripe,+ name: "dub_token",+ });++ if (!token) {+ throw new Error("Access token not found for the account.");+ }++ const tokenData = JSON.parse(token) as Token;++ return tokenData as Token;++ // TODO:+ // Refresh the token+}diff --git a/packages/stripe-app/src/utils/secrets.ts b/packages/stripe-app/src/utils/secrets.tsindex 614bfa095a..3724b1eaaa 100644--- a/packages/stripe-app/src/utils/secrets.ts+++ b/packages/stripe-app/src/utils/secrets.ts@@ -1,6 +1,6 @@import Stripe from "stripe";-type SecretName = "token" | "workspace";+type SecretName = "dub_token" | "dub_workspace";// Secrets are stored on account levelconst scope: Stripe.Apps.SecretCreateParams.Scope = {@@ -32,11 +32,29 @@ export async function getSecret<T>({stripe: Stripe;name: SecretName;}) {- const secret = await stripe.apps.secrets.find({+ try {+ const secret = await stripe.apps.secrets.find({+ name,+ scope,+ expand: ["payload"],+ });++ return secret.payload;+ } catch (e) {+ return null;+ }+}++// Delete a secret for the account+export async function deleteSecret({+ stripe,+ name,+}: {+ stripe: Stripe;+ name: SecretName;+}) {+ return await stripe.apps.secrets.deleteWhere({name,scope,- expand: ["payload"],});-- return secret as T;}diff --git a/packages/stripe-app/src/utils/types.ts b/packages/stripe-app/src/utils/types.tsindex 46d289fabe..f1b5eebb7e 100644--- a/packages/stripe-app/src/utils/types.ts+++ b/packages/stripe-app/src/utils/types.ts@@ -10,4 +10,4 @@ export interface Workspace {id: string;name: string;logo: string;-}+}\ No newline at end of filediff --git a/packages/stripe-app/src/views/AppSettings.tsx b/packages/stripe-app/src/views/AppSettings.tsxindex ae4f4e9048..ef933f6457 100644--- a/packages/stripe-app/src/views/AppSettings.tsx+++ b/packages/stripe-app/src/views/AppSettings.tsx@@ -3,12 +3,19 @@ import {createHttpClient,STRIPE_API_KEY,} from "@stripe/ui-extension-sdk/http_client";-import { Link, SignInView } from "@stripe/ui-extension-sdk/ui";-import { useEffect } from "react";+import { createOAuthState } from "@stripe/ui-extension-sdk/oauth";+import { Banner, Button, Link, SignInView } from "@stripe/ui-extension-sdk/ui";+import { useEffect, useRef, useState } from "react";import Stripe from "stripe";import appIcon from "../icon.svg";-import { getSecret } from "../utils/secrets";-import { Token } from "../utils/types";+import {+ connectWorkspace,+ disconnectWorkspace,+ fetchWorkspace,+} from "../utils/dub";+import { getOAuthUrl, getToken, getUserInfo } from "../utils/oauth";+import { setSecret } from "../utils/secrets";+import { Workspace } from "../utils/types";// You don't need an API Key here, because the app uses the// dashboard credentials to make requests.@@ -23,38 +30,119 @@ const AppSettings = ({appContext,oauthContext,}: ExtensionContextValue) => {- console.log({- userContext,- environment,- appContext,- oauthContext,- });+ const credentialsUsed = useRef(false);+ const [oauthState, setOAuthState] = useState("");+ const [challenge, setChallenge] = useState("");+ const [workspace, setWorkspace] = useState<Workspace | null>(null);- useEffect(() => {- // setSecret({- // stripe,- // name: "token",- // payload: JSON.stringify({- // access_token: "123",- // refresh_token: "456",- // token_type: "Bearer",- // expires_in: 3600,- // scope: "read_write",- // }),- // });-- getSecret<Token>({+ const code = oauthContext?.code;+ const verifier = oauthContext?.verifier;+ const error = oauthContext?.error;++ // Verify token and connect workspace+ const verifyTokenAndConnectWorkspace = async () => {+ if (!code || !verifier) {+ return;+ }++ const token = await getToken({ code, verifier });++ if (!token) {+ return;+ }++ await setSecret({+ stripe,+ name: "dub_token",+ payload: JSON.stringify(token),+ });++ const workspace = await getUserInfo({ token });++ if (!workspace) {+ return;+ }++ await connectWorkspace({+ stripe,+ workspaceId: workspace.id,+ accountId: userContext.account.id,+ });++ await setSecret({stripe,- name: "token",+ name: "dub_workspace",+ payload: JSON.stringify(workspace),+ });++ credentialsUsed.current = true;+ setWorkspace(workspace);+ };++ // Fetch the workspace for the current account+ useEffect(() => {+ fetchWorkspace({ stripe }).then((workspace) => {+ if (workspace) {+ setWorkspace(workspace);+ }});}, []);+ useEffect(() => {+ // if there is a workspace, we're done here+ if (workspace) {+ return;+ }++ // there is an ongoing oauth flow+ if (code && verifier && !workspace && !credentialsUsed.current) {+ verifyTokenAndConnectWorkspace();+ return;+ }++ // no oauth flow, no token, we need to start one+ if (!oauthState && !workspace) {+ createOAuthState().then(({ state, challenge }) => {+ setOAuthState(state);+ setChallenge(challenge);+ });+ }+ }, [workspace, oauthState, code, verifier]);++ if (workspace) {+ return (+ <Banner+ type="default"+ title="Dub account"+ description={`Connected to Acme Inc.`}+ actions={+ <Button+ onPress={() => {+ if (!workspace) {+ return;+ }++ disconnectWorkspace({+ stripe,+ workspaceId: workspace.id,+ });++ setWorkspace(null);+ }}+ >+ Disconnect+ </Button>+ }+ />+ );+ }+return (<SignInViewdescription="Connect your Dub workspace with Stripe to start tracking the conversions."primaryAction={{label: "Connect workspace",- href: "https://example.com",+ href: getOAuthUrl({ state: oauthState, challenge }),}}footerContent={<>@@ -66,37 +154,6 @@ const AppSettings = ({brandIcon={appIcon}/>);-- // return (- // <SettingsView onSave={() => {}}>- // <Box- // css={{- // background: "container",- // borderRadius: "medium",- // padding: "large",- // }}- // >- // <Box css={{ marginBottom: "small" }}>- // <Icon name="settings" size="medium" />- // </Box>- // Hello there- // <Inline css={{ fontFamily: "monospace" }}>- // src/views/AppSettings.tsx- // </Inline>{" "}- // and save to reload this view.- // <Link- // target="_blank"- // href={- // "https://stripe.com/docs/stripe-apps/build-test-views#add-application-settings"- // }- // >- // <Box css={{ marginTop: "medium" }}>- // Adding application settings <Icon name="arrowRight" size="xsmall" />- // </Box>- // </Link>- // </Box>- // </SettingsView>- // );};export default AppSettings;