Accepting Payments with Stripe
A comprehensive guide to integrating Stripe payments into your Next.js application.
Accepting Payments with Stripe
Stripe makes it easy to accept payments online. Here is how to get started.
Setup
- Create a Stripe account at stripe.com
- Get your API keys from the dashboard
- Install the SDK:
``bash
npm install stripe @stripe/stripe-js
`
Environment Variables
Add these to your .env.local:
`
STRIPE_SECRET_KEY=sk_test_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
`
Creating a Checkout Session
`typescript
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [
{
price: "price_xxx",
quantity: 1,
},
],
success_url: "https://example.com/success",
cancel_url: "https://example.com/cancel",
});
`
Handling Webhooks
Webhooks let you know when payments are completed:
`typescript
export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get("stripe-signature")!;
const event = stripe.webhooks.constructEvent( body, signature, process.env.STRIPE_WEBHOOK_SECRET! );
switch (event.type) { case "checkout.session.completed": // Handle successful payment break; } } ``
Start accepting payments today!
Related Posts
Enjoyed this article?
Check out more posts or subscribe to our newsletter.