Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Payment Support #2

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions app/api/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Hono } from "hono";
import { clerkMiddleware, getAuth } from "@hono/clerk-auth";
import Stripe from "stripe";

const app = new Hono();

Expand All @@ -22,4 +23,26 @@ api.get("/hello", (c) => {
});
});

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string);

api.post("/create-payment-intent", async (c) => {
// const { items } = c.body;
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount: 100,
currency: "usd",
// In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
automatic_payment_methods: {
enabled: true,
},
});

return c.json(
{
clientSecret: paymentIntent.client_secret,
},
201
);
});

export default app;
23 changes: 13 additions & 10 deletions app/components/ui/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ const Header = ({ logo }: HeaderProps) => {
<div className="flex items-center justify-between h-16">
{/* Logo */}
<div className="flex items-center">
<Link to="/">
<span className="font-bold text-xl">{logo}</span>
<Link to="/" className="font-bold text-xl">
{logo}
</Link>
</div>

Expand All @@ -36,20 +36,23 @@ const Header = ({ logo }: HeaderProps) => {
<NavigationMenu>
<NavigationMenuList className="flex space-x-4">
<NavigationMenuItem>
<NavigationMenuLink className="text-sm">
<Link to="/editor">Editor</Link>
<NavigationMenuLink className="text-sm" asChild>
<Link to="/payment">Payment</Link>
</NavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem>
<NavigationMenuLink className="text-sm">
<Link to="/about">About</Link>
<NavigationMenuLink className="text-sm" asChild>
<Link to="/editor">Editor</Link>
</NavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem>
<NavigationMenuLink className="text-sm text-gray-400">
Help
<NavigationMenuLink className="text-sm" asChild>
<Link to="/about">About</Link>
</NavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem>
<NavigationMenuLink active={false}>Help</NavigationMenuLink>
</NavigationMenuItem>
</NavigationMenuList>
</NavigationMenu>
</div>
Expand All @@ -67,12 +70,12 @@ const Header = ({ logo }: HeaderProps) => {
size={16}
/>
</div>
<a href="https://github.com/laiso/hono-spa-react/issues">
<Link to="https://github.com/laiso/hono-spa-react/issues">
<Button variant="ghost" size="sm" className="ml-2">
Feedback
<ExternalLink className="pl-1 text-gray-400" size={16} />
</Button>
</a>
</Link>
<SignedOut>
<SignInButton>
<Button variant="outline" size="sm" className="ml-2">
Expand Down
2 changes: 1 addition & 1 deletion app/routes/__root.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createRootRoute, Link, Outlet } from "@tanstack/react-router";
import { createRootRoute, Outlet } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/router-devtools";

import Header from "@/components/ui/header";
Expand Down
139 changes: 139 additions & 0 deletions app/routes/payment.lazy.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { Button } from "@/components/ui/button";
import {
Elements,
PaymentElement,
useElements,
useStripe,
} from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";

import { createLazyFileRoute } from "@tanstack/react-router";
import React from "react";
import { useEffect, useState } from "react";

const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLIC_KEY);

function CheckoutForm() {
const stripe = useStripe();
const elements = useElements();

const [message, setMessage] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
if (!stripe) {
return;
}

const clientSecret = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);

if (!clientSecret) {
return;
}

stripe.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => {
if (!paymentIntent) {
return;
}

switch (paymentIntent.status) {
case "succeeded":
setMessage("Payment succeeded!");
break;
case "processing":
setMessage("Your payment is processing.");
break;
case "requires_payment_method":
setMessage("Your payment was not successful, please try again.");
break;
default:
setMessage("Something went wrong.");
break;
}
});
}, [stripe]);

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();

setIsLoading(true);

if (!stripe || !elements) {
return;
}

const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: "http://localhost:5173/payment",
},
});

if (error.type === "card_error" || error.type === "validation_error") {
setMessage(error.message || null);
} else {
setMessage("An unexpected error occurred.");
}

setIsLoading(false);
};

const paymentElementOptions = {
layout: "tabs" as const,
};

return (
<form id="payment-form" onSubmit={handleSubmit}>
<PaymentElement id="payment-element" options={paymentElementOptions} />
<div className="py-2">
<Button disabled={isLoading || !stripe || !elements} id="submit">
<span id="button-text">
{isLoading ? (
<div className="spinner" id="spinner"></div>
) : (
"Pay now"
)}
</span>
</Button>
</div>
{message && <div id="payment-message">{message}</div>}
</form>
);
}

const Page = () => {
const [clientSecret, setClientSecret] = useState("");

useEffect(() => {
fetch("/api/create-payment-intent", {
method: "POST",
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then((data) => setClientSecret(data.clientSecret));
}, []);

const appearance = {
theme: "stripe" as const,
};
const options = {
clientSecret,
appearance,
};

return (
<div className="App">
{clientSecret && (
<Elements options={options} stripe={stripePromise}>
<CheckoutForm />
</Elements>
)}
</div>
);
};

export const Route = createLazyFileRoute("/payment")({
component: () => <Page />,
});
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@
"@hono/clerk-auth": "^2.0.0",
"@radix-ui/react-navigation-menu": "^1.2.0",
"@radix-ui/react-slot": "^1.1.0",
"@stripe/react-stripe-js": "^2.7.3",
"@stripe/stripe-js": "^4.1.0",
"@tanstack/react-router": "^1.40.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"hono": "^4.4.12",
"lucide-react": "^0.400.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"stripe": "^16.2.0",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7"
},
Expand Down