简体   繁体   English

带 node.js 部署的 Stripe webhook 主机

[英]Stripe webhook host with node.js deployment

Is it possible to host stripe webhook with node.js deploy.是否可以使用 node.js deploy 来托管 stripe webhook。

I've setup my stripe webhook with stripe checkout and It's ran successfully in localhost using stripe cli.我已经使用 stripe checkout 设置了我的 stripe webhook,并且它使用 stripe cli 在 localhost 中成功运行。

But I'm tried to take webhooks live.但我试图让 webhooks 生效。

const express = require("express");
const Stripe = require("stripe");
const { Order } = require("../models/Order");

require("dotenv").config();

const stripe = Stripe(`${process.env.STRIPE_SECRET}`);

const router = express.Router();

router.post("/create-checkout-session", async (req, res) => {

  const customer = await stripe.customers.create({
    metadata: {
      userId: req.body.userId,
      cart: JSON.stringify(req.body.products),
    },
  });

  const line_items = req.body.products.map((item) => {
    return {
      price_data: {
        currency: "usd",
        product_data: {
          name: item.title,
          description: item.description,
          metadata: {
            id: item.id,
          },
        },
        unit_amount: item.price * 100,
      },
      quantity: item.quantity,
    };
  });

  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    shipping_address_collection: {
      allowed_countries: ["BD", "US", "CA"],
    },
    shipping_options: [
      {
        shipping_rate_data: {
          type: "fixed_amount",
          fixed_amount: {
            amount: 0,
            currency: "usd",
          },
          display_name: "Free shipping",
          // Delivers between 5-7 business days
          delivery_estimate: {
            minimum: {
              unit: "business_day",
              value: 5,
            },
            maximum: {
              unit: "business_day",
              value: 7,
            },
          },
        },
      },
      {
        shipping_rate_data: {
          type: "fixed_amount",
          fixed_amount: {
            amount: 1500,
            currency: "usd",
          },
          display_name: "Next day air",
          // Delivers in exactly 1 business day
          delivery_estimate: {
            minimum: {
              unit: "business_day",
              value: 1,
            },
            maximum: {
              unit: "business_day",
              value: 1,
            },
          },
        },
      },
    ],
    line_items,
    mode: "payment",
    customer: customer.id,
    success_url: `https://nobab-3b3c4.web.app/checkout-success`,
    cancel_url: `https://nobab-3b3c4.web.app/`,
  });

  // res.redirect(303, session.url);
  res.send({ url: session.url });
});

// Create order function

const createOrder = async (customer, data) => {
  const Items = JSON.parse(customer.metadata.cart);

  const products = Items.map((item) => {
    return {
      productId: item.id,
      quantity: item.quantity,
    };
  });

  const newOrder = new Order({
    userId: customer.metadata.userId,
    customerId: data.customer,
    paymentIntentId: data.payment_intent,
    products,
    subtotal: data.amount_subtotal,
    total: data.amount_total,
    shipping: data.customer_details,
    payment_status: data.payment_status,
  });

  try {
    const savedOrder = await newOrder.save();
    console.log("Processed Order:", savedOrder);
  } catch (err) {
    console.log(err);
  }
};

// Stripe webhoook

router.post(
  "/webhook",
  express.json({ type: "application/json" }),
  async (req, res) => {
    let data;
    let eventType;
    // Check if webhook signing is configured.
    // let webhookSecret = `${process.env.STRIPE_WEB_HOOK}`;
    let webhookSecret;

    if (webhookSecret) {
      // Retrieve the event by verifying the signature using the raw body and secret.
      let event;
      let signature = req.headers["stripe-signature"];
      try {
        event = stripe.webhooks.constructEvent(
          req.body,
          signature,
          webhookSecret
        );

      } catch (err) {
        console.log(`⚠️  Webhook signature verification failed:  ${err}`);
        return res.sendStatus(400);
      }
      // Extract the object from the event.
      data = event.data.object;
      eventType = event.type;
    } else {
      // Webhook signing is recommended, but if the secret is not configured in `config.js`,
      // retrieve the event data directly from the request body.
      data = req.body.data.object;
      eventType = req.body.type;
    }

    // Handle the checkout.session.completed event
    if (eventType === "checkout.session.completed") {
      stripe.customers
        .retrieve(data.customer)
        .then(async (customer) => {
          try {
            // CREATE ORDER
            createOrder(customer, data);
            console.log("Ordered");
            res.status(200).json({ message: 'Order created', data: data })
            res.status(200).send("Order created")
          } catch (err) {
            console.log(typeof createOrder);
            console.log(err);
          }
        })
        .catch((err) => console.log(err.message));
    }

    res.status(200).end();
  }
);

module.exports = router;

This code working fine and store user order in mongodb database, but i need to run this after my server deployment.此代码工作正常并将用户订单存储在 mongodb 数据库中,但我需要在服务器部署后运行它。

Thanks everyone谢谢大家

for help me帮帮我

Yes it should be possible to host webhook with Node: Stripe Doc .是的,应该可以使用 Node: Stripe Doc托管 webhook。 It's a separated logic with your Checkout Creation endpoint, and you will need to test the webhook endpoint properly.它与您的 Checkout Creation 端点是一个独立的逻辑,您需要正确测试 webhook 端点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM