#derin_api

1 messages ¡ Page 1 of 1 (latest)

near basaltBOT
#

👋 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/1219884426830282804

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

midnight owl
#

hello! I'm not familiar with vite-express, but how are you initializing Stripe, can you share that line of code?

#

When sharing code please be sure to remove/redact any API Keys or other sensitive information.

thick gull
#

Hi Alex. I have my code as below.

#

import Stripe from "stripe";
import Book from "./../models/bookModel.mjs";
import Purchase from "./../models/purchaseModel.mjs";
import catchAsync from "../utils/catchAsync.mjs";
import factory from "./handlerFactory.mjs";

const stripe = new Stripe(process.env.STRIPE_TEST_SECRET_KEY, {
apiVersion: "2023-10-16",
});

const getCheckoutSession = catchAsync(async (req, res, next) => {
try {
const book = await Book.findById(req.params.bookId);

const product = await stripe.products.create({
  name: `${book.title}`,
  description: book.summary,
});

const price = await stripe.prices.create({
  product: product.id,
  unit_amount: book.price * 100,
  currency: "usd",
});

const session = await stripe.checkout.sessions.create(
  {
    mode: "payment",
    success_url: `${req.protocol}://${req.get("host")}/?book=${
      req.params.bookId
    }&&user=${req.user.id}&&price=${book.price}`,
    cancel_url: `${req.protocol}://${req.get("host")}/book/${book.slug}`,
    customer_email: req.user.email,
    client_reference_id: req.params.bookId,
    line_items: [
      {
        price: price.id,
        quantity: 1,
      },
    ],
  },

  {
    headers: {
      Authorization: `Bearer ${process.env.STRIPE_TEST_SECRET_KE}Y`,
    },
  }
);
console.log(session);

res.status(200).json({
  status: "success",
  session,
});

} catch (error) {
console.error("Stripe API error", error);

res.status(500).json({
  status: "error",
  message: "An error occurred while creating the checkout session",
});

}
});

midnight owl
#

if you add a line here to log, is the secret key logged?

console.log(process.env.STRIPE_TEST_SECRET_KEY);
const stripe = new Stripe(process.env.STRIPE_TEST_SECRET_KEY, {
  apiVersion: "2023-10-16",
});
thick gull
#

The console.log(process.env.STRIPE_TEST_SECRET_KEY) is undefined

#

It appears my API is not getting delivered into the code.

midnight owl
#

you're probably going to need to import a package that does that and make the necessary configurations

thick gull
#

I already have dotenv installed and I have used it for nodemailer and it worked. I have used .env for jsonwedtoken, nodemailer, mongoDB databse and I have not encountered an issue. I really need help with this.

midnight owl
#

you mentioned you have dotenv installed but I don't see it imported in the code you shared. Just as an example, this works as expected for me, with my secret key being loaded from the .env file.

import dotenv from 'dotenv'
dotenv.config({ path: "../.env" })

import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2023-10-16',
});
thick gull
#

I will try this out now. Thank you so much

#

Thank you alex, now it sees the API keys

#

But it has lead to another error while testing the same route. Can I go ahead and ask the question?

midnight owl
#

sure!

thick gull
#

I have created this middleware to aunthenticate a user before creating a session which is now giving me an issue. import jwt from "jsonwebtoken";
import crypto from "crypto";
import User from "../models/userModel.mjs";

import catchAsync from "../utils/catchAsync.mjs";
import { promisify } from "util";
import Email from "../utils/email.mjs";
import dotenv from "dotenv";
dotenv.config({ path: "./config.env" });

const signToken = (id) => {
return jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
};

const createSendToken = (user, statusCode, res) => {
const token = signToken(user._id);

const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000
),
// secure: true,
httpOnly: true,
};
if (process.env.NODE_ENV === "production") cookieOptions.secure = true;
res.cookie("jwt", token, cookieOptions);

user.password = undefined;

res.status(statusCode).json({
status: "success",
token,
data: {
user,
},
});
};

const protect = catchAsync(async (req, res, next) => {
// 1. Get and Check if Token exist
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}

if (!token) {
return next(
new AppError("You are not logged in! Please log in to have access", 401)
);
}

const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);

console.log(decoded);

const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next(new AppError("User no longer exist.", 401));
}

if (currentUser.changedPasswordAfter(decoded.iat)) {
return next(new AppError("Password Changed, please login again", 401));
}

req.user = currentUser;
res.locals.user = currentUser;
next();
});

#

When I try to do my testing, I get this message. {
"status": "error",
"error": {
"name": "JsonWebTokenError",
"message": "jwt malformed",
"statusCode": 500,
"status": "error"
},
"message": "jwt malformed",
"stack": "JsonWebTokenError: jwt malformed\n at module.exports (C:\Users\derin\Downloads\thewordthatsuits-frontend-server\node_modules\jsonwebtoken\verify.js:70:17)\n at node:internal/util:375:7\n at new Promise (<anonymous>)\n at node:internal/util:361:12\n at file:///C:/Users/derin/Downloads/thewordthatsuits-frontend-server/controllers/authController.mjs:108:46\n at file:///C:/Users/derin/Downloads/thewordthatsuits-frontend-server/utils/catchAsync.mjs:3:5\n at Layer.handle [as handle_request] (C:\Users\derin\Downloads\thewordthatsuits-frontend-server\node_modules\express\lib\router\layer.js:95:5)\n at trim_prefix (C:\Users\derin\Downloads\thewordthatsuits-frontend-server\node_modules\express\lib\router\index.js:328:13)\n at C:\Users\derin\Downloads\thewordthatsuits-frontend-server\node_modules\express\lib\router\index.js:286:9\n at Function.process_params (C:\Users\derin\Downloads\thewordthatsuits-frontend-server\node_modules\express\lib\router\index.js:346:12)"
}

#

Here is my route. import express from "express";
import purchaseController from "../controllers/purchaseController.mjs";
import authController from "../controllers/authController.mjs";

const router = express.Router();

router.use(authController.protect);

router.get("/checkout-session/:bookId", purchaseController.getCheckoutSession);

midnight owl
#

This isn't something that I can help with unfortunately. It's not a Stripe specific issue