我已经创建了一个应用程序和一个后端,但是在确认成功交易的最后一步中遇到了麻烦。具体来说,付款的价格属性没有通过。看起来product.price可以在前端代码中识别出来,不确定为什么它不能正确传递到后端。
谢谢您的帮助!
错误消息:TypeError:无法读取未定义的属性'price'
我的带有付款代码的应用程序:
import React, { useState } from 'react';
import './styles.scss';
import StripeCheckout from "react-stripe-checkout"
function Subscribe() {
const[product, setProduct] = useState({
name: "Ezcema Guru Services",
price: 30,
productBy: "EzcemaGuru"
});
const makePayment = token => {
const middle = {
token,
product
};
const top = {
"Content-Type": "application/json"
};
return fetch(`http://localhost:8282/payment`, {
method: "POST",
top,
middle: JSON.stringify(middle)
})
.then(response => {
console.log("RESPONSE ", response)
const { status } = response;
console.log("STATUS ", status)
})
.catch(error => console.log(error));
};
return(
<div>
<h1>
Subscription Page
</h1>
<StripeCheckout
stripeKey="pk_test_51HdglCIiJoZbD0sLYY2Yw8uryaImmNp8RURTyWZUXtv2D3ONtkIrVxtF6E5wnbtEeEJFoZm411ZglYSQRA25RDvU00Sbs3f1Ug"
token={makePayment}
name="Ezcema Insider"
amount={product.price * 100}>
</StripeCheckout>
</div>
)
}
export default Subscribe;
我的后端代码:
const cors = require("cors");
const express = require("express");
const stripe = require("stripe")("sk_test_51HdglCIiJoZbD0sLTvXHKuQ8ovCcxM1cXxS2NTmEajZWa1F6p7XkEDbht82uaMWbIXh4tPMB5RbMLD7EpHprdty300nwUOAD2t")
const { v4: uuidv4 } = require('uuid');
const { resolve } = require("path");
const app = express();
//middleware
app.use(express.json())
app.use(cors());
//routes
app.get("/", (req, res) => {
res.send("IT WORKS")
});
app.post("/payment", (req, res) => {
const {product, token} = req.body;
console.log("PRODUCT ", product);
console.log("PRICE ", product.price);
const idempontencyKey = uuid()
return stripe.customers.create({
email: token.email,
source: token.id
}).then(customer=> {
stripe.charges.create({
amount: product.price * 100,
currency: 'usd',
customer: customer.id,
receipt_email: token.email,
description: `purchase of ${product.name}`,
}, {idempontencyKey})
})
.then(result => res. status(200).json(result))
.catch(err => console.log(err) )
})
//listen
app.listen(8282, () => console.log("LISTENING AT PORT 8282"));
答案 0 :(得分:0)
您正在将未知参数传递给fetch
API,没有top
或middle
参数:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
我认为您可能打算改用headers
和body
:
return fetch(`http://localhost:8282/payment`, {
method: "POST",
headers: top,
body: JSON.stringify(middle)
})