【问题标题】:You did not provide an API key. You need to provide your API key in the Authorization header您没有提供 API 密钥。您需要在授权标头中提供您的 API 密钥
【发布时间】:2023-02-22 06:40:56
【问题描述】:

当我尝试使用 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/.

我还尝试使用 if 检查来检查条带键,但我收到一条错误消息,指出该键不存在。

结帐功能:

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 });
  };

即使我将 Stripe api 密钥作为授权标头传递,它仍然无法正常工作

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");
  }
}

【问题讨论】:

  • 您是否向自己证明了 process.env.STRIPE_SECRET_KEY 存在
  • fetch 调用之前添加:if (!process.env.STRIPE_SECRET_KEY) throw new Error('process.env.STRIPE_SECRET_KEY not found');
  • 你能分享写在getStripeapi/stripe中的代码吗
  • if 检查抛出了错误。我不知道为什么。

标签: reactjs next.js stripe-payments


【解决方案1】:

我不认为你需要发送这个:Authorization: Bearer ${process.env.STRIPE_SECRET_KEY},。我认为问题出在这里

const getStripe = () => {
  if (!stripePromise) {
    stripePromise = loadStripe(`${process.env.STRIPE_PUBLIC_KEY}`);
  }

  return stripePromise;
};

由于您在客户端,process.env.STRIPE_PUBLIC_KEY 将是未定义的。因为默认情况下 .env 文件中的环境变量会加载到服务器。看看这个:whats-the-difference-between-exposing-environment-variables-in-nextjs-through

你必须定义你的环境变量

  NEXT_PUBLIC_STRIPE_API_KEY=xxxxxxxxxxxxxxx

然后在getStripe中使用它:

stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_API_KEY);

【讨论】:

  • 我有同样的问题并且 coe stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_API_KEY) 仍然没有在生产中初始化条带。在本地开发环境中运行良好。是的,我已经仔细检查了我的主机提供商中的环境变量是否设置正确
【解决方案2】:

首先,您必须将 NEXT.js 后缀添加到 getStripe.ts 文件中的公钥,如下所示:

stripePromise = loadStripe(`${process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}`);

然后推送您的更改(不要合并它们)。

在 vercel 中,在“项目设置”选项卡下添加您的环境变量,并选择您要公开它们的环境(预览/开发/生产)。

最后,重新部署你的分支。这将创建一个新的部署,但使用项目设置中的最新配置,这意味着您的新环境变量。

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 2019-06-29
    • 2020-10-22
    • 2015-12-09
    • 2017-05-31
    • 2020-12-10
    • 2021-04-17
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多