The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor PayPal OAuth to use generic provider
Kiran K023224bd727b
diff --git a/apps/web/app/(ee)/api/paypal/callback/route.ts b/apps/web/app/(ee)/api/paypal/callback/route.tsindex dd95248543..c5fea39b17 100644--- a/apps/web/app/(ee)/api/paypal/callback/route.ts+++ b/apps/web/app/(ee)/api/paypal/callback/route.ts@@ -1,14 +1,8 @@import { getSession } from "@/lib/auth";-import { paypalOAuth } from "@/lib/paypal/oauth";+import { paypalOAuthProvider } from "@/lib/paypal/oauth";import { prisma } from "@dub/prisma";-import { getSearchParams, PARTNERS_DOMAIN } from "@dub/utils";+import { PARTNERS_DOMAIN } from "@dub/utils";import { redirect } from "next/navigation";-import { z } from "zod";--const oAuthCallbackSchema = z.object({- code: z.string(),- state: z.string(),-});// GET /api/paypal/callback - callback from PayPalexport const GET = async (req: Request) => {@@ -38,24 +32,13 @@ export const GET = async (req: Request) => {throw new Error("partner_not_found");}- const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));-- const isStateValid = await paypalOAuth.verifyState({- state,- dubUserId: session.user.id,- });-- if (!isStateValid) {- throw new Error("invalid_state");- }+ const {+ token: { token },+ } = await paypalOAuthProvider.exchangeCodeForToken(req);- const accessToken = await paypalOAuth.exchangeCodeForToken({- code,- });-- const paypalUser = await paypalOAuth.getUserInfo({- token: accessToken,- });+ const paypalUser = await paypalOAuthProvider.getUserInfo(+ token.access_token,+ );if (!paypalUser.email_verified) {throw new Error("paypal_email_not_verified");diff --git a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts b/apps/web/lib/actions/partners/generate-paypal-oauth-url.tsindex 83446f43e1..311285e41e 100644--- a/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts+++ b/apps/web/lib/actions/partners/generate-paypal-oauth-url.ts@@ -1,6 +1,6 @@"use server";-import { paypalOAuth } from "@/lib/paypal/oauth";+import { paypalOAuthProvider } from "@/lib/paypal/oauth";import { COUNTRIES, PAYPAL_SUPPORTED_COUNTRIES } from "@dub/utils";import { authPartnerActionClient } from "../safe-action";@@ -20,12 +20,8 @@ export const generatePaypalOAuthUrl = authPartnerActionClient.action();}- const url = await paypalOAuth.getAuthorizationUrl({- dubUserId: user.id,- });-return {- url,+ url: await paypalOAuthProvider.generateAuthUrl(user.id),};},);diff --git a/apps/web/lib/integrations/hubspot/oauth.ts b/apps/web/lib/integrations/hubspot/oauth.tsindex 2346d7cd4c..46ff0390df 100644--- a/apps/web/lib/integrations/hubspot/oauth.ts+++ b/apps/web/lib/integrations/hubspot/oauth.ts@@ -68,5 +68,5 @@ export const hubSpotOAuthProvider = new HubSpotOAuthProvider({"crm.schemas.contacts.write",].join(" "),tokenSchema: hubSpotAuthTokenSchema,- tokenRequestStyle: "form",+ bodyFormat: "form",});diff --git a/apps/web/lib/integrations/oauth-provider.ts b/apps/web/lib/integrations/oauth-provider.tsindex 260e653bd9..998c3a4230 100644--- a/apps/web/lib/integrations/oauth-provider.ts+++ b/apps/web/lib/integrations/oauth-provider.ts@@ -13,7 +13,7 @@ export interface OAuthProviderConfig {scopes: string;redisStatePrefix: string;tokenSchema: z.ZodSchema;- tokenRequestStyle: "form" | "formdata" | "json";+ bodyFormat: "form" | "formdata" | "json";}const codeExchangeSchema = z.object({@@ -61,7 +61,7 @@ export class OAuthProvider<T extends z.ZodSchema> {let body: BodyInit;let headers: Record<string, string> = {};- switch (this.provider.tokenRequestStyle) {+ switch (this.provider.bodyFormat) {case "form":headers["Content-Type"] = "application/x-www-form-urlencoded";body = new URLSearchParams({diff --git a/apps/web/lib/integrations/slack/oauth.ts b/apps/web/lib/integrations/slack/oauth.tsindex 97a9250a6a..0c23c81b8d 100644--- a/apps/web/lib/integrations/slack/oauth.ts+++ b/apps/web/lib/integrations/slack/oauth.ts@@ -59,5 +59,5 @@ export const slackOAuthProvider = new SlackOAuthProvider({"incoming-webhook",].join(","),tokenSchema: slackAuthTokenSchema,- tokenRequestStyle: "formdata",+ bodyFormat: "formdata",});diff --git a/apps/web/lib/paypal/env.ts b/apps/web/lib/paypal/env.tsindex 7486d28714..62f57f84d8 100644--- a/apps/web/lib/paypal/env.ts+++ b/apps/web/lib/paypal/env.ts@@ -3,9 +3,9 @@ const isLive = process.env.NODE_ENV === "production";export const paypalEnv = {PAYPAL_CLIENT_ID: process.env.PAYPAL_CLIENT_ID || "",PAYPAL_CLIENT_SECRET: process.env.PAYPAL_CLIENT_SECRET || "",- PAYPAL_AUTHORIZE_HOST: isLive- ? "https://www.paypal.com"- : "https://www.sandbox.paypal.com",+ PAYPAL_AUTHORIZE_URL: isLive+ ? "https://www.paypal.com/signin/authorize"+ : "https://www.sandbox.paypal.com/signin/authorize",PAYPAL_API_HOST: isLive? "https://api.paypal.com": "https://api-m.sandbox.paypal.com",diff --git a/apps/web/lib/paypal/oauth.ts b/apps/web/lib/paypal/oauth.tsindex 30f33c60d7..3a12006504 100644--- a/apps/web/lib/paypal/oauth.ts+++ b/apps/web/lib/paypal/oauth.ts@@ -1,83 +1,17 @@-import { PARTNERS_DOMAIN_WITH_NGROK } from "@dub/utils";-import { AuthorizationCode } from "simple-oauth2";-import { v4 as uuidv4 } from "uuid";-import { redis } from "../upstash/redis";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import {+ OAuthProvider,+ OAuthProviderConfig,+} from "../integrations/oauth-provider";import { paypalEnv } from "./env";+import { paypalAuthTokenSchema, paypalUserInfoSchema } from "./schema";-interface AccessToken {- token: {- access_token: string;- };-}--interface PayPalUserInfo {- email: string;- email_verified: boolean; // Indicates whether the user's paypal email address is verified.-}--const REDIRECT_URI = `${PARTNERS_DOMAIN_WITH_NGROK}/api/paypal/callback`;-const STATE_CACHE_PREFIX = "paypal:oauth:state:";--export class PayPalOAuth {- private oauth2: AuthorizationCode;-- constructor() {- this.oauth2 = new AuthorizationCode({- client: {- id: paypalEnv.PAYPAL_CLIENT_ID,- secret: paypalEnv.PAYPAL_CLIENT_SECRET,- },- auth: {- tokenHost: paypalEnv.PAYPAL_API_HOST,- tokenPath: "/v1/oauth2/token",- authorizeHost: paypalEnv.PAYPAL_AUTHORIZE_HOST,- authorizePath: "/signin/authorize",- },- options: {- authorizationMethod: "header",- bodyFormat: "form",- },- });- }-- async getAuthorizationUrl({- dubUserId,- }: {- dubUserId: string;- }): Promise<string> {- const state = uuidv4();-- await redis.set(`${STATE_CACHE_PREFIX}${state}`, dubUserId, {- ex: 60 * 5, // 5 minutes- });-- return this.oauth2.authorizeURL({- state,- scope: ["email"],- redirect_uri: REDIRECT_URI,- });- }-- async verifyState({- state,- dubUserId,- }: {- state: string;- dubUserId: string;- }) {- return (await redis.get(`${STATE_CACHE_PREFIX}${state}`)) === dubUserId;- }-- async exchangeCodeForToken({ code }: { code: string }) {- const accessToken: AccessToken = await this.oauth2.getToken({- code,- redirect_uri: REDIRECT_URI,- });-- return accessToken.token.access_token;+class PayPalOAuthProvider extends OAuthProvider<typeof paypalAuthTokenSchema> {+ constructor(provider: OAuthProviderConfig) {+ super(provider);}- async getUserInfo({ token }: { token: string }) {+ async getUserInfo(token: string) {const response = await fetch(`${paypalEnv.PAYPAL_API_HOST}/v1/identity/openidconnect/userinfo?schema=openid`,{@@ -88,7 +22,7 @@ export class PayPalOAuth {},);- const data = (await response.json()) as PayPalUserInfo;+ const data = await response.json();if (!response.ok) {throw new Error("Failed to fetch user info from PayPal.", {@@ -96,8 +30,19 @@ export class PayPalOAuth {});}- return data;+ return paypalUserInfoSchema.parse(data);}}-export const paypalOAuth = new PayPalOAuth();+export const paypalOAuthProvider = new PayPalOAuthProvider({+ name: "PayPal",+ clientId: paypalEnv.PAYPAL_CLIENT_ID!,+ clientSecret: paypalEnv.PAYPAL_CLIENT_SECRET!,+ authUrl: paypalEnv.PAYPAL_AUTHORIZE_URL,+ tokenUrl: `${paypalEnv.PAYPAL_API_HOST}/v1/oauth2/token`,+ redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`,+ redisStatePrefix: "paypal:oauth:state",+ scopes: ["email"].join(" "),+ tokenSchema: paypalAuthTokenSchema,+ bodyFormat: "form",+});diff --git a/apps/web/lib/paypal/schema.ts b/apps/web/lib/paypal/schema.tsnew file mode 100644index 0000000000..cb64e0df7a--- /dev/null+++ b/apps/web/lib/paypal/schema.ts@@ -0,0 +1,12 @@+import { z } from "zod";++export const paypalAuthTokenSchema = z.object({+ token: z.object({+ access_token: z.string(),+ }),+});++export const paypalUserInfoSchema = z.object({+ email: z.string(),+ email_verified: z.boolean(), // Indicates whether the user's paypal email address is verified.+});