E-commerce 2 min read 1,627 views

Building E-commerce with Stripe: Payments, Subscriptions, and Webhooks

Integrate Stripe payments into your application. Learn about checkout, subscriptions, webhooks, and PCI compliance.

Stripe payments

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.

Share this article:
ES
Written by

Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!

Related Articles

Related Articles

Need Help With Your Project?

Book a free 30-minute consultation to discuss your technical challenges and explore solutions together.