Stripe Payment Integration
Accept payments and manage subscriptions with Stripe.
Setup
npm install stripe @stripe/stripe-js
Server-Side: Create Payment Intent
// api/create-payment-intent.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
app.post('/create-payment-intent', async (req, res) => {
const { amount, currency = 'usd' } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount * 100, // cents
currency,
automatic_payment_methods: { enabled: true },
});
res.json({ clientSecret: paymentIntent.client_secret });
});
Client-Side: Payment Form
import { loadStripe } from '@stripe/stripe-js';
import { Elements, PaymentElement, useStripe } from '@stripe/react-stripe-js';
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_KEY);
function CheckoutForm() {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: `${window.location.origin}/success`,
},
});
if (error) setMessage(error.message);
};
return (
<form onSubmit={handleSubmit}>
<PaymentElement />
<button>Pay Now</button>
</form>
);
}
Webhook Handling
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
const event = stripe.webhooks.constructEvent(
req.body, sig, process.env.STRIPE_WEBHOOK_SECRET
);
switch (event.type) {
case 'payment_intent.succeeded':
const payment = event.data.object;
// Fulfill order
break;
case 'customer.subscription.updated':
// Handle subscription change
break;
}
res.json({ received: true });
});
Always test with Stripe's test mode before going live.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!