#lua_code

1 messages ¡ Page 1 of 1 (latest)

plush treeBOT
#

👋 Welcome to your new thread!

⏲️ We'll be here soon! Typically we respond in a few minutes, but sometimes we might take a bit longer if the server is busy or if you have a particularly tricky question.

⏱️ We close idle threads, which makes them read-only. Once a thread is closed it won't be reopened, but you can always start a new thread if you have another question.

🔗 This thread will always be available, even after it's closed. You can find it again using Discord's search, or you can save this link: https://discord.com/channels/841573134531821608/1311617840914235466

📝 Have more to share? Add more details, code, screenshots, videos, etc. below.

Below are links to other discussions we've had with you in the past week in case you want to review that information. If your question is related to one of these previous discussions, please provide a comprehensive summary of the current state and what you need help with now. We help many users simultaneously, so a summary allows us to resolve your issue as soon as possible.

wary token
#
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
const admin = require("firebase-admin");

const app = express();


const serviceAccount = require("./firebase-credentials.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});
const db = admin.firestore();


app.use(
  cors({
    origin: process.env.CLIENT_URL || "http://localhost:5501",
    methods: ["GET", "POST", "OPTIONS"],
    allowedHeaders: ["Content-Type", "Authorization"],
  })
);
app.use(express.json()); 
app.use(
  "/webhook",
  express.raw({ type: "application/json" }) 
);


const storePlans = new Map([
  [1, { name: "Basic Plan", priceId: "price_1QPZz0Rrl7l1Yvwh2rb193bl", maxBots: 5 }],
  [2, { name: "Standard Plan", priceId: "price_1QPZyURrl7l1YvwhsQKG7G7w", maxBots: 10 }],
  [3, { name: "Premium Plan", priceId: "price_1QPZxoRrl7l1YvwhMPXHHRmQ", maxBots: 20 }],
]);


app.post("/create-subscription-session", async (req, res) => {
  try {
    const { planId, userId } = req.body;

    
    if (!userId || typeof userId !== "string") {
      return res.status(400).json({ error: "Invalid or missing userId." });
    }

    const plan = storePlans.get(planId);
    if (!plan) {
      return res.status(400).json({ error: `Plan with ID ${planId} not found.` });
    }

    
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      mode: "subscription",
      line_items: [{ price: plan.priceId, quantity: 1 }],
      success_url: `${process.env.CLIENT_URL}/success.html`,
      cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
      metadata: {
        userId: userId,
        planName: plan.name,
        maxBots: plan.maxBots,
      },
    });

    console.log("Created Stripe Session:", session);
    res.json({ url: session.url });
  } catch (error) {
    console.error("Error creating subscription session:", error.message);
    res.status(500).json({ error: "Failed to create subscription session." });
  }
});


app.post("/webhook", async (req, res) => {
  const sig = req.headers["stripe-signature"];
  const endpointSecret = process.env.STRIPE_ENDPOINT_SECRET;

  let event;
  try {
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
  } catch (err) {
    console.error(`Error verifying webhook: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  
  if (event.type === "checkout.session.completed") {
    const session = event.data.object;

    console.log("Webhook Event Received:", event.type);
    console.log("Session Metadata:", session.metadata);

    const { userId, planName, maxBots } = session.metadata;

    if (!userId || !planName || !maxBots) {
      console.error("Missing metadata in session!");
      return res.status(400).send("Missing metadata.");
    }

    try {
      
      const userRef = db.collection("users").doc(userId);
      await userRef.set(
        {
          plan: planName,
          payment_status: "paid",
          max_bots: parseInt(maxBots, 10),
        },
        { merge: true } 
      );
      console.log(`Successfully updated user ${userId} to plan ${planName}.`);
    } catch (error) {
      console.error(`Error updating Firestore: ${error.message}`);
      return res.status(500).send("Internal Server Error.");
    }
  }

  res.status(200).json({ received: true });
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
silver moth
#

Hi, let me help you with this.