Skip to content

Commit

Permalink
added logs
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinreber committed Nov 24, 2024
1 parent 3c54c4d commit 71bdfcd
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 70 deletions.
10 changes: 6 additions & 4 deletions app/routes/checkout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
redirect,
type LoaderFunctionArgs,
MetaFunction,
type MetaFunction,
} from "@remix-run/node";
import { requireUserLogin } from "~/services/auth.server";
import { stripeCheckout } from "~/services/stripe.server";
Expand All @@ -11,10 +11,12 @@ import { Logger } from "~/utils/logger.server";
export const meta: MetaFunction<
typeof loader,
{ root: typeof UserLoaderData }
> = ({ data, params, matches }) => {
// Incase our Profile loader ever fails, we can get logged in user data from root
> = ({ matches }) => {
const userMatch = matches.find((match) => match.id === "root");
const username = userMatch?.data.data?.username || userMatch?.data.data?.name;
const username =
userMatch?.data?.userData?.username ||
userMatch?.data?.userData?.name ||
"Checkout";

return [{ title: `Checkout | ${username}` }];
};
Expand Down
20 changes: 4 additions & 16 deletions app/routes/webhook.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import type {
ActionFunction,
LoaderFunctionArgs,
MetaFunction,
} from "@remix-run/node";
import type { ActionFunction, MetaFunction } from "@remix-run/node";
import { json } from "@remix-run/node";
import { requireUserLogin } from "~/services";
import { stripe } from "~/services/stripe.server";
import { handleStripeEvent } from "~/services/webhook.server";
import { Logger } from "~/utils/logger.server";
Expand All @@ -13,25 +8,18 @@ export const meta: MetaFunction = () => {
return [{ title: "Stripe Webhook" }];
};

// Add this temporary debug route to verify your environment variables
export const loader = async ({ request }: LoaderFunctionArgs) => {
await requireUserLogin(request);
return json({
webhookSecretSet: !!process.env.STRIPE_WEB_HOOK_SECRET,
stripeKeySet: !!process.env.STRIPE_SECRET_KEY,
origin: process.env.ORIGIN,
});
};

// [credit @kiliman to get this webhook working](https://github.com/remix-run/remix/discussions/1978)
// To have this webhook working locally, in another server we must run `stripe listen --forward-to localhost:3000/webhook` (yarn run stripe:listen)
export const action: ActionFunction = async ({ request }) => {
console.log("Webhook endpoint hit!", new Date().toISOString());

Logger.info({
message: "[webhook.ts]: Received webhook request",
metadata: {
method: request.method,
url: request.url,
headers: Object.fromEntries(request.headers.entries()),
timestamp: new Date().toISOString(),
},
});

Expand Down
102 changes: 52 additions & 50 deletions app/services/webhook.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,59 +15,10 @@ export const handleStripeEvent = async (
metadata: { type, id, data: JSON.stringify(data) },
});

const isTestEvent = id === "evt_00000000000000";
if (isTestEvent) {
Logger.info({ message: "[webhook.server]: Skipping test event" });
return;
}

switch (type) {
case CHECKOUT_SESSION_COMPLETED: {
const session = data.object as Stripe.Checkout.Session;

Logger.info({
message: "[webhook.server]: Checkout Session Data",
metadata: {
sessionId: session.id,
metadata: session.metadata,
customerId: session.customer,
paymentStatus: session.payment_status,
},
});

if (!session.metadata?.userId) {
throw new Error("No userId found in session metadata");
}

const creditsToAdd = 100;
Logger.info({
message: "[webhook.server]: Updating user credits",
metadata: {
userId: session.metadata.userId,
creditsToAdd,
},
});

const userData = await prisma.user.update({
where: {
id: session.metadata.userId,
},
data: {
credits: {
increment: creditsToAdd,
},
},
});

Logger.info({
message: "[webhook.server]: Successfully updated user credits",
metadata: {
userId: userData.id,
newCreditBalance: userData.credits,
},
});

return userData;
return handleCheckoutSession(session);
}

default:
Expand All @@ -86,3 +37,54 @@ export const handleStripeEvent = async (
throw error;
}
};

const handleCheckoutSession = async (session: Stripe.Checkout.Session) => {
Logger.info({
message: "[webhook.server]: Processing checkout session",
metadata: {
sessionId: session.id,
metadata: session.metadata,
customerId: session.customer,
paymentStatus: session.payment_status,
},
});

if (!session.metadata?.userId) {
throw new Error("No userId found in session metadata");
}

return await updateUserCredits(session.metadata.userId);
};

const updateUserCredits = async (userId: string) => {
const creditsToAdd = 100;

Logger.info({
message: "[webhook.server]: Updating user credits",
metadata: {
userId,
creditsToAdd,
},
});

const userData = await prisma.user.update({
where: {
id: userId,
},
data: {
credits: {
increment: creditsToAdd,
},
},
});

Logger.info({
message: "[webhook.server]: Successfully updated user credits",
metadata: {
userId: userData.id,
newCreditBalance: userData.credits,
},
});

return userData;
};

0 comments on commit 71bdfcd

Please sign in to comment.