Skip to content

Instantly share code, notes, and snippets.

@memdufaizan
Forked from ShariqAnsari88/order.js
Created March 10, 2023 19:04
Show Gist options
  • Select an option

  • Save memdufaizan/627b18e8b1cf7e846bbd9f13ab8a233c to your computer and use it in GitHub Desktop.

Select an option

Save memdufaizan/627b18e8b1cf7e846bbd9f13ab8a233c to your computer and use it in GitHub Desktop.

Revisions

  1. @ShariqAnsari88 ShariqAnsari88 renamed this gist Dec 18, 2022. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @ShariqAnsari88 ShariqAnsari88 created this gist Dec 18, 2022.
    51 changes: 51 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    ("use strict");
    const stripe = require("stripe")(process.env.STRIPE_KEY);
    /**
    * order controller
    */

    const { createCoreController } = require("@strapi/strapi").factories;

    module.exports = createCoreController("api::order.order", ({ strapi }) => ({
    async create(ctx) {
    const { products } = ctx.request.body;
    try {
    const lineItems = await Promise.all(
    products.map(async (product) => {
    const item = await strapi
    .service("api::product.product")
    .findOne(product.id);

    return {
    price_data: {
    currency: "inr",
    product_data: {
    name: item.title,
    },
    unit_amount: Math.round(item.price * 100),
    },
    quantity: product.attributes.quantity,
    };
    })
    );

    const session = await stripe.checkout.sessions.create({
    shipping_address_collection: { allowed_countries: ["IN"] },
    payment_method_types: ["card"],
    mode: "payment",
    success_url: process.env.CLIENT_URL + "/success",
    cancel_url: process.env.CLIENT_URL + "?success=false",
    line_items: lineItems,
    });

    await strapi
    .service("api::order.order")
    .create({ data: { products, stripeId: session.id } });

    return { stripeSession: session };
    } catch (error) {
    ctx.response.status = 500;
    return { error };
    }
    },
    }));