Reputation: 883
im getting this error when i try to use the my checkout function using Stripe:
You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
I also tried to use a if check to check for the stripe key, but i got an error that said the key did not exist .
checkout function:
const handleCheckOut = async () => {
const stripe = await getStripe();
const response = await fetch("/api/stripe", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(cartItems),
});
if (response.statusCode === 500) return;
const data = await response.json();
toast.loading("Redirecting...");
stripe.redirectToCheckout({ sessionId: data.id });
};
Even though im passing the Stripe api secret key as Authorization header it is still not woking
getStripe.js
import { loadStripe } from "@stripe/stripe-js";
let stripePromise;
const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(`${process.env.STRIPE_PUBLIC_KEY}`);
}
return stripePromise;
};
export default getStripe;
api/stripe.js
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default async function handler(req, res) {
console.log(req.body.cartItems);
if (req.method === "POST") {
try {
const params = {
submit_type: "pay",
mode: "payment",
payment_method_type: ["card"],
billing_address_collection: "auto",
// formas de envio
shipping_options: [
{ shipping_rate: "shr_1LJo2EHt0s8JSRoPQEDeHfo5" },
{ shipping_rate: "shr_1LJo3ZHt0s8JSRoP8uVNJhwS" },
],
line_items: req.body.map((item) => {
const img = item.image[0].asset._ref;
const newImage = img
.replace(
"image-",
"https://cdn.sanity.io/images/psdgq2wv/production/"
)
.replace("-webp", ".webp");
return {
price_data: {
currency: "usd",
product_data: {
name: item.name,
images: [newImage],
},
unit_amount: item.price * 100,
adjustable_quantity: {
enabled: true,
minimum: 1,
},
quantity: item.quantity,
},
};
}),
// success_url: `${req.headers.origin}/?success=true`,
// cancel_url: `${req.headers.origin}/?canceled=true`,
};
// Create Checkout Sessions from body params.
const session = await stripe.checkout.sessions.create(params);
res.status(200).json(session);
} catch (err) {
res.status(err.statusCode || 500).json(err.message);
}
} else {
res.setHeader("Allow", "POST");
res.status(405).end("Method Not Allowed");
}
}
Upvotes: 2
Views: 24056
Reputation: 1
If you're facing issues with your Stripe connected account not recognizing process.env.STRIPE_API_KEY
, you can directly paste the API key into your code for testing purposes. Here's how you might do it:
import Stripe from "stripe";
**const stripe = new Stripe('your_actual_stripe_api_key_here');**
Upvotes: 0
Reputation: 1
it works in my case: just add this in head of server file
const env = require("dotenv").config({ path: "./.env" });
or with import ES:
import dotenv from "dotenv";
const env = dotenv.config({ path: "./.env" });```
in any case, file names in .env must begin with REACT_APP_... for react + vite
Upvotes: 0
Reputation: 71
It's not mandatory to send API key by header, I think you are having problem with const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
and process.env is not loading .env
variables you need to check if it's working and if not have to configure dotenv
FOR NestJs API
you can see This Answer
Upvotes: 0
Reputation: 109
First, you have to add the NEXT.js suffix to the public key in your getStripe.ts file, like this:
stripePromise = loadStripe(`${process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}`);
Then push your changes (don't merge them yet).
In vercel, add your environment variables under the "Project Settings" tab, and select the environment where you want to expose them (Preview/Development/Production).
Finally, redeploy your branch. This will create a new deployment, but with the newest configuration from your Project Settings, meaning your new environment variables.
Upvotes: 0
Reputation: 49341
I do not think that you need to send this: Authorization:
Bearer ${process.env.STRIPE_SECRET_KEY},
. I think the issue is here
const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(`${process.env.STRIPE_PUBLIC_KEY}`);
}
return stripePromise;
};
since you are on client side, process.env.STRIPE_PUBLIC_KEY
will be undefined. because by default environment variables from .env files load to server. check this out: whats-the-difference-between-exposing-environment-variables-in-nextjs-through
You have to define your env variable
NEXT_PUBLIC_STRIPE_API_KEY=xxxxxxxxxxxxxxx
then use it in getStripe
:
stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_API_KEY);
Upvotes: 2