utkarsh-1602 / ecommerce-admin

This repository provides a comprehensive solution for managing billboards, categories, and products, allowing you to create a customized online shopping experience similar to Shopify. With intuitive features, you can effortlessly design and organize your store as well.
https://ecommerce-admin-mauve-psi.vercel.app
MIT License
2 stars 0 forks source link

Make a documentation on Stripe webhook #57

Closed utkarsh-1602 closed 10 months ago

utkarsh-1602 commented 10 months ago

in my api/webhook/route.ts file, I've used Stripe webhook, I need a proper documentation which explain the stripe webhook working in the code.

Feel Free to work on this Issue. Comment below to assign you the Task.

import Stripe from "stripe"; import { headers } from "next/headers" import { stripe } from "@/lib/stripe"; import { NextResponse } from "next/server"; import prismadb from "@/lib/prismadb";

export async function POST(req: Request) { const body = await req.text(); const signature = headers().get("Stripe-Signature") as string;

let event: Stripe.Event;
// TODO: provide Overview and flow for Stripe.Event

try {
    event = stripe.webhooks.constructEvent(
        body,
        signature,
        process.env.STRIPE_WEBOOK_SECRET!

    )
}
catch (error: any) {
    return new NextResponse(`Webhook Error: ${error.message}`, { status: 400 })
}

const session = event.data.object as Stripe.Checkout.Session;
const address = session?.customer_details?.address;

const addressComponents = [
    address?.line1,
    address?.line2,
    address?.city,
    address?.postal_code,
    address?.state,
    address?.country,
]

const addressString = addressComponents.filter((c) => c !== null).join(", ");

if (event.type === "checkout.session.completed") {
    const order = await prismadb.order.update({
        where: {
            id: session?.metadata?.orderId,
        },
        data: {
            isPaid: true,
            address: addressString,
            phone: session?.customer_details?.phone || "",
        },
        include: {
            orderItems: true,
        }
    });

    const productIds = order.orderItems.map((orderItem) => orderItem.productId)

    await prismadb.product.updateMany({
        where: {
            id: {
                in: [...productIds]
            }
        },
        data: {
            isArchived: true
        }
    });
}

return new NextResponse(null, { status: 200 });

}

utkarsh-1602 commented 10 months ago

Stripe.Event : Events are our way of letting you know when something interesting happens in your account. When an interesting event occurs, we create a new Event object. For example, when a charge succeeds, we create a charge.succeeded event, and when an invoice payment attempt fails, we create an invoice.payment_failed event. Certain API requests might create multiple events. For example, if you create a new subscription for a customer, you receive both a customer.subscription.created event and a charge.succeeded event

utkarsh-1602 commented 10 months ago

Use Stripe(publishableKey, options?) to create an instance of the Stripe object. The Stripe object is your entrypoint to the rest of the Stripe.js SDK.


import Stripe from "stripe"

export const stripe = new Stripe(process.env.STRIPE_API_SECRET_KEY!, {
    apiVersion: "2023-10-16",
    typescript: true,
})
utkarsh-1602 commented 10 months ago

A Very Helpful Documentation for Setting Up and Deploying a webhook to listen events from stripe : https://stripe.com/docs/webhooks/quickstart Use webhooks for post-payment commerce events such as sending custom email receipts, fulfilling orders, or updating your database

utkarsh-1602 commented 10 months ago

This code defines a Next.js API route that handles incoming POST requests from Stripe webhooks. It validates the webhook signature, extracts relevant information from the Stripe event (specifically from the Checkout Session), and processes the event when a checkout session is completed. The order status and associated products are updated in the database accordingly. The route returns a 200 response to indicate successful processing of the webhook.