【发布时间】:2021-11-02 11:36:16
【问题描述】:
https://github.com/WebDevSimplified/stripe-checkout-simple/commit/b1bac8e70cf783c983f2d41b7f1e17b0617c324d
以上是 github 的链接,您可以在其中查看整个代码。 下面我将粘贴我的代码,以防你不想去 github: /服务器启动/
require("dotenv").config()
const express = require("express")
const app = express()
const cors = require("cors")
app.use(express.json())
app.use(
cors({
origin: "http://localhost:5500",
})
)
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY)
const storeItems = new Map([
[1, { priceInCents: 10000, name: "Learn React Today" }],
[2, { priceInCents: 20000, name: "Learn CSS Today" }],
])
app.post("/create-checkout-session", async (req, res) => {
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ["card"],
mode: "payment",
line_items: req.body.items.map(item => {
const storeItem = storeItems.get(item.id)
return {
price_data: {
currency: "usd",
product_data: {
name: storeItem.name,
},
unit_amount: storeItem.priceInCents,
},
quantity: item.quantity,
}
}),
success_url: `${process.env.CLIENT_URL}/success.html`,
cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
})
res.json({ url: session.url })
} catch (e) {
res.status(500).json({ error: e.message })
}
})
app.listen(3000)
/** script.js start **/
const button = document.querySelector("button")
button.addEventListener("click", () => {
fetch("http://localhost:3000/create-checkout-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
items: [
{ id: 1, quantity: 3 },
{ id: 2, quantity: 1 },
],
}),
})
.then(res => {
if (res.ok) return res.json()
return res.json().then(json => Promise.reject(json))
})
.then(({ url }) => {
window.location = url
})
.catch(e => {
console.error(e.error)
})
})
/*** start of .env **/
CLIENT_URL=http://localhost:5500
STRIPE_PRIVATE_KEY: I have it in my code but wont post it here.
/*** index.html**/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<button>Checkout</button>
</body>
</html>
我得到的错误是: 1- script.js:3 POST http://localhost:3000/create-checkout-session 500(内部服务器错误) 2-即使我提供了我的钥匙,甚至仔细检查了它: 您没有提供 API 密钥。您需要使用 Bearer auth 在 Authorization 标头中提供您的 API 密钥(例如“授权:Bearer YOUR_SECRET_KEY”)。详情请参阅https://stripe.com/docs/api#authentication,或者我们可以通过https://support.stripe.com/ 提供帮助。
【问题讨论】:
-
您至少可以将错误添加为代码 sn-p 吗?在问题中点被合并
-
它说我需要提供一个KEY,但我已经在文件夹中有我的密钥
-
你能告诉我你在 fetch 里面写了什么吗?您是否将
YOUR_SECRET_KEY更改为您的条带私钥? -
它对我有用,我在本地测试过,效果很好
-
您可以在 .env 和 fetch 中添加 STRIPE_PRIVATE_KEY 而不是 API_KEY 只需放入您的条带私钥(例如 Bearer KJhsj.builbrsvbuibuw)
标签: javascript node.js shopping-cart web-development-server