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.

support creating link

Kiran Kf4089d64c76c
diff --git a/packages/stripe-app/README.md b/packages/stripe-app/README.md
index 2d8481557e..174b2715db 100644
--- a/packages/stripe-app/README.md
+++ b/packages/stripe-app/README.md
@@ -8,3 +8,9 @@ This is the [Stripe app](https://marketplace.stripe.com/apps/dub-conversions) fo
2. Update the `version` in `stripe-app.json`
3. Run `stripe apps upload`
4. Make a release via the [Stripe dashboard](https://dashboard.stripe.com/apps/dub.co)
+
+## Run locally
+
+```
+stripe apps dev
+```
\ No newline at end of file
diff --git a/packages/stripe-app/src/utils/constants.ts b/packages/stripe-app/src/utils/constants.ts
index 45540a3303..993be69abe 100644
--- a/packages/stripe-app/src/utils/constants.ts
+++ b/packages/stripe-app/src/utils/constants.ts
@@ -4,6 +4,7 @@ import { StripeMode } from "./types";
export const DUB_CLIENT_ID =
"dub_app_517290377fe6b4dfcc8726a7061ba9b6da1c4d7d7d75f77a";
export const DUB_HOST = "https://app.dub.co";
+export const DUB_API_HOST = "https://api.dub.co";
// Stripe
export const STRIPE_MODE: StripeMode = "live";
diff --git a/packages/stripe-app/src/utils/create-link.ts b/packages/stripe-app/src/utils/create-link.ts
new file mode 100644
index 0000000000..c057eb479d
--- /dev/null
+++ b/packages/stripe-app/src/utils/create-link.ts
@@ -0,0 +1,36 @@
+import { DUB_API_HOST } from "./constants";
+import { getValidToken } from "./oauth";
+import { stripe } from "./stripe";
+
+export async function createLink({
+ url,
+ isPublic,
+}: {
+ url: string;
+ isPublic: boolean;
+}) {
+ const token = isPublic ? null : await getValidToken({ stripe });
+
+ const response = await fetch(`${DUB_API_HOST}/links`, {
+ method: "POST",
+ body: JSON.stringify({
+ url,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ ...(!token
+ ? { "dub-anonymous-link-creation": "1" }
+ : { Authorization: `Bearer ${token.access_token}` }),
+ },
+ });
+
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error("Failed to create link.", {
+ cause: data.error,
+ });
+ }
+
+ return data;
+}
diff --git a/packages/stripe-app/src/utils/dub.ts b/packages/stripe-app/src/utils/dub.ts
index 12938357e9..a91b95c4b6 100644
--- a/packages/stripe-app/src/utils/dub.ts
+++ b/packages/stripe-app/src/utils/dub.ts
@@ -31,4 +31,4 @@ export async function updateWorkspace({
cause: data.error,
});
}
-}
+}
\ No newline at end of file
diff --git a/packages/stripe-app/src/utils/oauth.ts b/packages/stripe-app/src/utils/oauth.ts
index 891df156aa..4c18ef9c4e 100644
--- a/packages/stripe-app/src/utils/oauth.ts
+++ b/packages/stripe-app/src/utils/oauth.ts
@@ -1,5 +1,10 @@
import Stripe from "stripe";
-import { DUB_CLIENT_ID, DUB_HOST, STRIPE_MODE } from "./constants";
+import {
+ DUB_API_HOST,
+ DUB_CLIENT_ID,
+ DUB_HOST,
+ STRIPE_MODE,
+} from "./constants";
import { getSecret } from "./secrets";
import { Token, Workspace } from "./types";
@@ -18,7 +23,7 @@ export function getOAuthUrl({
state: string;
challenge: string;
}) {
- return `${DUB_HOST}/oauth/authorize?client_id=${DUB_CLIENT_ID}&redirect_uri=${getRedirectURL()}&response_type=code&scope=workspaces.write&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`;
+ return `${DUB_HOST}/oauth/authorize?client_id=${DUB_CLIENT_ID}&redirect_uri=${getRedirectURL()}&response_type=code&scope=workspaces.write,links.write&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`;
}
// Exchanges the authorization code for an access token
@@ -29,7 +34,7 @@ export async function getToken({
code: string;
verifier: string;
}) {
- const url = `${DUB_HOST}/api/oauth/token`;
+ const url = `${DUB_API_HOST}/oauth/token`;
try {
const response = await fetch(url, {
@@ -60,7 +65,7 @@ export async function getToken({
// 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`, {
+ const response = await fetch(`${DUB_API_HOST}/oauth/userinfo`, {
headers: {
Authorization: `Bearer ${token.access_token}`,
},
@@ -92,8 +97,40 @@ export async function getValidToken({ stripe }: { stripe: Stripe }) {
const tokenData = JSON.parse(token) as Token;
+ try {
+ await getUserInfo({ token: tokenData });
+ } catch (e) {
+ const refreshedToken = await refreshToken({ token: tokenData });
+ return refreshedToken!;
+ }
+
return tokenData as Token;
+}
+
+export async function refreshToken({ token }: { token: Token }) {
+ const url = `${DUB_API_HOST}/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,
+ grant_type: "refresh_token",
+ refresh_token: token.refresh_token,
+ }),
+ });
- // TODO:
- // Refresh the token
+ const data = await response.json();
+
+ if (!response.ok) {
+ throw new Error(data.error.message);
+ }
+
+ return data as Token;
+ } catch (e) {
+ console.error("Unable to refresh Dub access token:", (e as Error).message);
+ }
}
diff --git a/packages/stripe-app/src/utils/stripe.ts b/packages/stripe-app/src/utils/stripe.ts
new file mode 100644
index 0000000000..fdec2fe15d
--- /dev/null
+++ b/packages/stripe-app/src/utils/stripe.ts
@@ -0,0 +1,12 @@
+import {
+ createHttpClient,
+ STRIPE_API_KEY,
+} from "@stripe/ui-extension-sdk/http_client";
+import Stripe from "stripe";
+
+// You don't need an API Key here, because the app uses the
+// dashboard credentials to make requests.
+export const stripe: Stripe = new Stripe(STRIPE_API_KEY, {
+ httpClient: createHttpClient() as Stripe.HttpClient,
+ apiVersion: "2023-08-16",
+});
diff --git a/packages/stripe-app/src/views/AppSettings.tsx b/packages/stripe-app/src/views/AppSettings.tsx
index d2d85937f5..4f7c7ca5b7 100644
--- a/packages/stripe-app/src/views/AppSettings.tsx
+++ b/packages/stripe-app/src/views/AppSettings.tsx
@@ -1,18 +1,14 @@
import type { ExtensionContextValue } from "@stripe/ui-extension-sdk/context";
-import {
- createHttpClient,
- STRIPE_API_KEY,
-} from "@stripe/ui-extension-sdk/http_client";
import { createOAuthState } from "@stripe/ui-extension-sdk/oauth";
import {
Banner,
+ Box,
Button,
Link,
SignInView,
Spinner,
} from "@stripe/ui-extension-sdk/ui";
import { useEffect, useRef, useState } from "react";
-import Stripe from "stripe";
import { useWorkspace } from "../hooks/use-workspace";
import appIcon from "../icon.svg";
import { updateWorkspace } from "../utils/dub";
@@ -23,18 +19,13 @@ import {
getValidToken,
} from "../utils/oauth";
import { deleteSecret, setSecret } from "../utils/secrets";
+import { stripe } from "../utils/stripe";
import { Workspace } from "../utils/types";
+import { CreateLink } from "./create-link";
// TODO:
// Handle errors and display them to the user
-// You don't need an API Key here, because the app uses the
-// dashboard credentials to make requests.
-const stripe: Stripe = new Stripe(STRIPE_API_KEY, {
- httpClient: createHttpClient() as Stripe.HttpClient,
- apiVersion: "2023-08-16",
-});
-
const AppSettings = ({ userContext, oauthContext }: ExtensionContextValue) => {
const credentialsUsed = useRef(false);
const [oauthState, setOAuthState] = useState("");
@@ -151,52 +142,58 @@ const AppSettings = ({ userContext, oauthContext }: ExtensionContextValue) => {
return <Spinner size="large" />;
}
- if (workspace) {
- return (
- <Banner
- title="Dub workspace"
- description={`Connected to ${workspace.name}`}
- actions={
- <Button
- type="destructive"
- size="small"
- disabled={disconnecting}
- onPress={async () => {
- setDisconnecting(true);
-
- await disconnectWorkspace({
- workspace,
- });
-
- mutate();
- setDisconnecting(false);
- }}
- >
- {disconnecting ? "Disconnecting..." : "Disconnect"}
- </Button>
- }
- />
- );
- }
-
return (
- <SignInView
- description="Connect your Dub workspace with Stripe to start tracking the conversions."
- primaryAction={{
- label: connecting ? "Connecting please wait..." : "Connect workspace",
- href: connecting ? "#" : getOAuthUrl({ state: oauthState, challenge }),
- }}
- footerContent={
- <>
- Don&apos;t have an Dub account?{" "}
- <Link href="https://app.dub.co/register" target="_blank" external>
- Sign up
- </Link>
- </>
- }
- brandColor="#000000"
- brandIcon={appIcon}
- />
+ <Box css={{ width: "6/12", stack: "y", gap: "large" }}>
+ {workspace ? (
+ <Banner
+ title="Dub workspace"
+ description={`Connected to ${workspace.name}`}
+ actions={
+ <Button
+ type="destructive"
+ size="small"
+ disabled={disconnecting}
+ onPress={async () => {
+ setDisconnecting(true);
+
+ await disconnectWorkspace({
+ workspace,
+ });
+
+ mutate();
+ setDisconnecting(false);
+ }}
+ >
+ {disconnecting ? "Disconnecting..." : "Disconnect"}
+ </Button>
+ }
+ />
+ ) : (
+ <SignInView
+ description="Connect your Dub workspace with Stripe to start tracking the conversions."
+ primaryAction={{
+ label: connecting
+ ? "Connecting please wait..."
+ : "Connect workspace",
+ href: connecting
+ ? "#"
+ : getOAuthUrl({ state: oauthState, challenge }),
+ }}
+ footerContent={
+ <>
+ Don&apos;t have an Dub account?{" "}
+ <Link href="https://app.dub.co/register" target="_blank" external>
+ Sign up
+ </Link>
+ </>
+ }
+ brandColor="#000000"
+ brandIcon={appIcon}
+ />
+ )}
+
+ <CreateLink workspace={workspace} />
+ </Box>
);
};
diff --git a/packages/stripe-app/src/views/create-link.tsx b/packages/stripe-app/src/views/create-link.tsx
new file mode 100644
index 0000000000..0c8c8e49b9
--- /dev/null
+++ b/packages/stripe-app/src/views/create-link.tsx
@@ -0,0 +1,88 @@
+import {
+ Box,
+ Button,
+ FormFieldGroup,
+ Link,
+ TextField,
+} from "@stripe/ui-extension-sdk/ui";
+import { showToast } from "@stripe/ui-extension-sdk/utils";
+import { useState } from "react";
+import { createLink } from "../utils/create-link";
+import { Workspace } from "../utils/types";
+
+export const CreateLink = ({ workspace }: { workspace: Workspace | null }) => {
+ const [url, setUrl] = useState("");
+ const [shortLink, setShortLink] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleCreateLink = async () => {
+ setIsSubmitting(true);
+
+ try {
+ const link = await createLink({
+ url,
+ isPublic: !workspace,
+ });
+
+ showToast("Link created", { type: "success" }); // TODO: This is not working
+ setShortLink(link.shortLink);
+ setUrl("");
+ } catch (error: any) {
+ console.error(error);
+ showToast(error.message, { type: "caution" });
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Box
+ css={{
+ padding: "large",
+ keyline: "neutral",
+ borderRadius: "small",
+ stack: "y",
+ gap: "large",
+ }}
+ >
+ <FormFieldGroup
+ legend="Destination URL"
+ description="Enter a long URL to shorten"
+ >
+ <TextField
+ label="Destination URL"
+ placeholder="https://dub.co/help/article/what-is-dub"
+ hiddenElements={["label"]}
+ size="large"
+ onChange={(e) => setUrl(e.target.value)}
+ value={url}
+ />
+ <Button
+ type="primary"
+ size="large"
+ onPress={handleCreateLink}
+ disabled={isSubmitting || !url}
+ >
+ {isSubmitting ? "Creating..." : "Create link"}
+ </Button>
+ </FormFieldGroup>
+
+ {shortLink && (
+ <Link href={shortLink} target="_blank">
+ {shortLink}
+ </Link>
+ )}
+
+ {!workspace && (
+ <Button
+ type="secondary"
+ size="small"
+ target="_blank"
+ href="https://d.to/register"
+ >
+ Connect to Dub to shorten more links
+ </Button>
+ )}
+ </Box>
+ );
+};
diff --git a/packages/stripe-app/stripe-app.json b/packages/stripe-app/stripe-app.json
index e1408fb803..453b4f912f 100644
--- a/packages/stripe-app/stripe-app.json
+++ b/packages/stripe-app/stripe-app.json
@@ -49,7 +49,11 @@
}
],
"content_security_policy": {
- "connect-src": null,
+ "connect-src": [
+ "http://localhost:8888/api/",
+ "https://api.dub.co/",
+ "https://api-staging.dub.co/"
+ ],
"image-src": null,
"purpose": ""
}