Last active
June 29, 2024 15:26
-
-
Save dev-xo/3f782eb4bf99fdc94e7b98a7337cccfa to your computer and use it in GitHub Desktop.
Stripe Checkout - One time payments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { DataFunctionArgs } from '@remix-run/node' | |
import { json, redirect } from '@remix-run/node' | |
import { Form } from '@remix-run/react' | |
import Stripe from 'stripe' | |
export async function loader({ request }: DataFunctionArgs) { | |
// Gets params from URL. | |
const url = new URL(request.url) | |
const userId = url.searchParams.get('userId') | |
const successPayment = url.searchParams.get('success') | |
const cancelPayment = url.searchParams.get('cancel') | |
if (userId && successPayment) { | |
// On success payment, we could update user subscription status in database. | |
// Call stripe api e.g: getStripeCustomer, or getStripePayment etc.. | |
// Return data back to the client. | |
return json({ success: true }) | |
} | |
return json({}) | |
} | |
export async function action({ request }: DataFunctionArgs) { | |
// Inits Stripe. | |
const stripe = new Stripe(process.env.STRIPE_SECRET_API_KEY!, { | |
apiVersion: '2022-11-15', | |
typescript: true, | |
}) | |
// Creates a Checkout Sessions. | |
const session = await stripe.checkout.sessions.create({ | |
// Provide the Price ID from Products Dashboard. | |
line_items: [ | |
{ | |
price: 'price_1MKbCCFaUfwAZVY7Cc2D0sce', | |
quantity: 1, | |
}, | |
], | |
mode: 'payment', | |
success_url: `${getDomainUr(request)}?userId=1&success=true`, | |
cancel_url: `${getDomainUr(request)}?userId=1&canceled=true`, | |
}) | |
if (!session.url) throw new Error('Could not create a checkout session.') | |
return redirect(session.url) | |
} | |
export default function CheckoutSessionRoute() { | |
return ( | |
<div | |
style={{ | |
height: '100%', | |
width: '100%', | |
display: 'flex', | |
flexDirection: 'row', | |
alignItems: 'center', | |
justifyContent: 'center', | |
}}> | |
<Form method="post"> | |
<button>Submit</button> | |
</Form> | |
</div> | |
) | |
} | |
// Helper function that gets domain URL. | |
function getDomainUr(request: Request) { | |
const host = request.headers.get('X-Forwarded-Host') ?? request.headers.get('host') | |
if (!host) throw new Error('Could not determine domain URL.') | |
const protocol = host.includes('localhost') ? 'http' : 'https' | |
return `${protocol}://${host}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment