The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add PayPal OAuth integration and update dependencies
Kiran K394885994f10
diff --git a/apps/web/app/api/paypal/callback/route.ts b/apps/web/app/api/paypal/callback/route.tsnew file mode 100644index 0000000000..27c813988f--- /dev/null+++ b/apps/web/app/api/paypal/callback/route.ts@@ -0,0 +1,81 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getSession } from "@/lib/auth";+import {+ exchangeCodeForToken,+ getUserInfo,+ verifyState,+} from "@/lib/paypal/oauth";+import { prisma } from "@dub/prisma";+import { getSearchParams } 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 PayPal+export const GET = async (req: Request) => {+ const session = await getSession();++ try {+ if (!session?.user.id) {+ throw new DubApiError({+ code: "unauthorized",+ message:+ "Unauthorized. You must be logged in https://partners.dub.co/ to continue.",+ });+ }++ const { defaultPartnerId } = session.user;++ if (!defaultPartnerId) {+ throw new DubApiError({+ code: "not_found",+ message: "Partner profile not found.",+ });+ }++ const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));++ const isStateValid = await verifyState({+ state,+ dubUserId: session.user.id,+ });++ if (!isStateValid) {+ throw new DubApiError({+ code: "bad_request",+ message: "Invalid state",+ });+ }++ const accessToken = await exchangeCodeForToken({+ code,+ });++ const paypalUser = await getUserInfo({+ token: accessToken,+ });++ // TODO:+ // Should we check if the paypal email is verified?++ await prisma.partner.update({+ where: {+ id: defaultPartnerId,+ },+ data: {+ paypalEmail: paypalUser.email,+ },+ });+ } catch (e: any) {+ return handleAndReturnErrorResponse(e);+ }++ // TODO:+ // Maybe redirect to /success?method=paypal++ redirect("/programs");+};diff --git a/apps/web/app/partners.dub.co/(onboarding)/onboarding/verify/page.tsx b/apps/web/app/partners.dub.co/(onboarding)/onboarding/verify/page.tsxindex 995fef35d6..82127bb09a 100644--- a/apps/web/app/partners.dub.co/(onboarding)/onboarding/verify/page.tsx+++ b/apps/web/app/partners.dub.co/(onboarding)/onboarding/verify/page.tsx@@ -1,5 +1,7 @@+import PaypalConnectButton from "@/ui/partners/paypal-connect-button";import StripeConnectButton from "@/ui/partners/stripe-connect-button";import Link from "next/link";+export default function OnboardingVerification() {return (<div className="relative mx-auto my-10 flex w-full max-w-[416px] flex-col items-center md:mt-14">@@ -28,6 +30,7 @@ export default function OnboardingVerification() {</div><div className="mt-10 grid gap-4"><StripeConnectButton text="Save and continue" />+ <PaypalConnectButton text="Connect your PayPal account" /><Linkhref="/programs"className="text-sm text-neutral-500 transition-colors hover:text-neutral-800"diff --git a/apps/web/lib/actions/partners/start-paypal-oauth-flow.ts b/apps/web/lib/actions/partners/start-paypal-oauth-flow.tsnew file mode 100644index 0000000000..a16843348e--- /dev/null+++ b/apps/web/lib/actions/partners/start-paypal-oauth-flow.ts@@ -0,0 +1,22 @@+"use server";++import { getAuthorizationUrl } from "@/lib/paypal/oauth";+import { authPartnerActionClient } from "../safe-action";++export const startPaypalOauthFlowAction = authPartnerActionClient.action(+ async ({ ctx }) => {+ let { partner, user } = ctx;++ if (partner.paypalEmail) {+ throw new Error("You have already connected your PayPal account.");+ }++ const url = await getAuthorizationUrl({+ dubUserId: user.id,+ });++ return {+ url,+ };+ },+);diff --git a/apps/web/lib/paypal/env.ts b/apps/web/lib/paypal/env.tsnew file mode 100644index 0000000000..b558525660--- /dev/null+++ b/apps/web/lib/paypal/env.ts@@ -0,0 +1,15 @@+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_TOKEN_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.tsnew file mode 100644index 0000000000..3652bdc313--- /dev/null+++ b/apps/web/lib/paypal/oauth.ts@@ -0,0 +1,98 @@+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { AuthorizationCode } from "simple-oauth2";+import { v4 as uuidv4 } from "uuid";+import { redis } from "../upstash/redis";+import { paypalEnv } from "./env";++interface AccessToken {+ token: {+ access_token: string;+ };+}++interface UserInfo {+ email: string;+ verified: boolean;+ email_verified: boolean;+}++const oauth2 = new AuthorizationCode({+ client: {+ id: paypalEnv.PAYPAL_CLIENT_ID,+ secret: paypalEnv.PAYPAL_CLIENT_SECRET,+ },+ auth: {+ tokenHost: paypalEnv.PAYPAL_TOKEN_HOST,+ tokenPath: "/v1/oauth2/token",+ authorizeHost: paypalEnv.PAYPAL_AUTHORIZE_HOST,+ authorizePath: "/signin/authorize",+ },+ options: {+ authorizationMethod: "header",+ bodyFormat: "form",+ },+});++const REDIRECT_URI = `${APP_DOMAIN_WITH_NGROK}/api/paypal/callback`;+const STATE_CACHE_PREFIX = "paypal:oauth:state:";++export async function getAuthorizationUrl({+ dubUserId,+}: {+ dubUserId: string;+}): Promise<string> {+ const state = uuidv4();++ await redis.set(`${STATE_CACHE_PREFIX}${state}`, dubUserId, {+ ex: 60 * 2, // 2 minutes+ });++ return oauth2.authorizeURL({+ state,+ scope: ["email"],+ redirect_uri: REDIRECT_URI,+ });+}++export async function verifyState({+ state,+ dubUserId,+}: {+ state: string;+ dubUserId: string;+}) {+ return (await redis.get(`${STATE_CACHE_PREFIX}${state}`)) === dubUserId;+}++// Exchanges the authorization code for an access token+export async function exchangeCodeForToken({ code }: { code: string }) {+ const accessToken: AccessToken = await oauth2.getToken({+ code,+ redirect_uri: REDIRECT_URI,+ });++ return accessToken.token.access_token;+}++// Fetch the user info+export async function getUserInfo({ token }: { token: string }) {+ const response = await fetch(+ `${paypalEnv.PAYPAL_TOKEN_HOST}/v1/identity/openidconnect/userinfo?schema=openid`,+ {+ headers: {+ Authorization: `Bearer ${token}`,+ "Content-Type": "application/x-www-form-urlencoded",+ },+ },+ );++ const data = (await response.json()) as UserInfo;++ if (!response.ok) {+ throw new Error("Failed to fetch user info from PayPal.", {+ cause: data,+ });+ }++ return data;+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 1c770df0a6..0fee146f97 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -113,6 +113,7 @@"rehype-slug": "^5.1.0","remark-gfm": "^4.0.0","shiki": "^1.14.1",+ "simple-oauth2": "^5.1.0","sonner": "^1.4.41","stripe": "^12.12.0","swr": "^2.1.5",diff --git a/apps/web/ui/partners/paypal-connect-button.tsx b/apps/web/ui/partners/paypal-connect-button.tsxnew file mode 100644index 0000000000..0ebfb4325a--- /dev/null+++ b/apps/web/ui/partners/paypal-connect-button.tsx@@ -0,0 +1,29 @@+"use client";++import { startPaypalOauthFlowAction } from "@/lib/actions/partners/start-paypal-oauth-flow";+import { Button, ButtonProps } from "@dub/ui";+import { useAction } from "next-safe-action/hooks";+import { useRouter } from "next/navigation";+import { toast } from "sonner";++export default function PaypalConnectButton(props: ButtonProps) {+ const router = useRouter();++ const { executeAsync, isPending } = useAction(startPaypalOauthFlowAction, {+ onSuccess: ({ data }) => {+ if (!data?.url) {+ toast.error("Something went wrong. Please try again.");+ return;+ }++ router.push(data.url);+ },+ onError: ({ error }) => {+ toast.error(error.serverError);+ },+ });++ return (+ <Button onClick={() => executeAsync()} loading={isPending} {...props} />+ );+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 68b070b6e3..1841e17e4d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -327,6 +327,9 @@ importers:shiki:specifier: ^1.14.1version: 1.14.1+ simple-oauth2:+ specifier: ^5.1.0+ version: 5.1.0sonner:specifier: ^1.4.41@@ -2562,12 +2565,24 @@ packages:engines: {node: '>=6'}hasBin: true+ '@hapi/[email protected]':+ resolution: {integrity: sha512-ERcCZaEjdH3OgSJlyjVk8pHIFeus91CjKP3v+MpgBNp5IvGzP2l/bRiD78nqYcKPaZdbKkK5vDBVPd2ohHBlsA==}++ '@hapi/[email protected]':+ resolution: {integrity: sha512-Waj1cwPXJDucOib4a3bAISsKJVb15MKi9IvmTI/7ssVEm6sywXGjVJDhl6/umt1pK1ZS7PacXU3A1PmFKHEZ2w==}++ '@hapi/[email protected]':+ resolution: {integrity: sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ==}+'@hapi/[email protected]':resolution: {integrity: sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==}'@hapi/[email protected]':resolution: {integrity: sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==}+ '@hapi/[email protected]':+ resolution: {integrity: sha512-0z6ZRCmFEfV/MQqkQomJ7sl/hyxvcZM7LtuVqN3vdAO4vM9eBbowl0kaqQj9EJJQab+3Uuh1GxbGIBFy4NfJ4w==}+'@hookform/[email protected]':resolution: {integrity: sha512-bU0Gr4EepJ/EQsH/IwEzYLsT/PEj5C0ynLQ4m+GSHS+xKH4TfSelhluTgOaoc4kA5s7eCsQbM4wvZLzELmWzUg==}peerDependencies:@@ -10465,6 +10480,9 @@ packages:resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}+ resolution: {integrity: sha512-gWDa38Ccm4MwlG5U7AlcJxPv3lvr80dU7ARJWrGdgvOKyzSj1gr3GBPN1rABTedAYvC/LsGYoFuFxwDBPtGEbw==}+resolution: {integrity: sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==}@@ -13881,12 +13899,26 @@ snapshots:protobufjs: 7.4.0yargs: 17.7.2+ '@hapi/[email protected]':+ dependencies:+ '@hapi/hoek': 11.0.7++ '@hapi/[email protected]': {}++ '@hapi/[email protected]': {}+'@hapi/[email protected]': {}'@hapi/[email protected]':dependencies:'@hapi/hoek': 9.3.0+ '@hapi/[email protected]':+ dependencies:+ '@hapi/boom': 10.0.1+ '@hapi/bourne': 3.0.0+ '@hapi/hoek': 11.0.7+dependencies:react-hook-form: 7.52.1([email protected])@@ -24007,6 +24039,15 @@ snapshots:once: 1.4.0simple-concat: 1.0.1+ dependencies:+ '@hapi/hoek': 11.0.7+ '@hapi/wreck': 18.1.0+ debug: 4.4.0+ joi: 17.11.0+ transitivePeerDependencies:+ - supports-color+dependencies:is-arrayish: 0.3.2