【问题标题】:why I am getting 404 error when creating a stripe checkout payment?为什么我在创建条带结帐付款时收到 404 错误?
【发布时间】:2022-07-19 06:31:05
【问题描述】:

我正在使用 firebase 创建一个 react-app,我想在我的项目中使用条带支付网关,但我无法使用它,因为它给了我一个错误。每当我通过 axios 调用发布请求时,我都会收到此错误 POST: http://localhost:4242/payments 404 not found 。 这是我的条纹结帐, <StripeCheckout stripeKey="PUBLIC_KE" token={handleToken} billingAddress shippingAddress amount={getBasketTotal(basket)} ></StripeCheckout>

    async function handleToken(token) {
    console.log(token);
    const totalAmount = getBasketTotal(basket);
    const cart = { name: "All products", totalAmount };
    const response = await axios.post("http://localhost:4242/payments", {
    token,
    cart,
    });
    let { status } = response.data;
    console.log(response);
    if (status === "success") {
    navigate("/");
    toast.success("Your Order has been Placed Successfully!", {});
    } else {
    alert("Something went wrong!");
   navigate("/");
  //   toast.error("Something went wrong!", {});
    }
  }   

   app.post("/payments", (req, res) => {
   let error;
   let status;
   try {
   const { cart, token } = req.body;
  const customer = await stripe.customers.create({
  email: token.email,
   source: token.id,
    });
   const key = uuidv4();

  const charge = await stripe.charges.create(
   {
     amount: cart.totalAmount * 100,
     currency: "usd",
    customer: customer.id,
    receipt_email: token.email,
    description: "Product request Successfully recieved",
    shipping: {
      name: token.card.name,
      address: {
        line1: token.card.address_line1,
        line2: token.card.address_line2,
        city: token.card.address_city,
        country: token.card.address_country,
        postal: token.card.address_zip,
      },
    },
  },
  {
    idempotencyKey: key,
  }
);

 status = "success";
 } catch (error) {
  console.log(error);
  status = "error";
  }
   res.json({ status });
   });

 app.listen(4242, () => console.log("Running on 4242"));

任何支持都会有所帮助。

【问题讨论】:

  • 你是怎么运行这个的?您确定您的服务器实际上正在侦听端口 4242 并响应 /payments 路由吗?你可以用 curl/postman 手动点击它吗?

标签: reactjs firebase axios stripe-payments http-status-code-404


【解决方案1】:

希望对你有帮助

我的例子:

const STRIPE_PUBLIC_KEY = process.env.REACT_APP_STRIPE_PUBLIC_KEY

在 React .env 中应该带有 REACT_APP 前缀

用户请求:

const BASE_URL = "http://localhost:5000/api/";  // my api is on 5000 
     const TOKEN = // yourToken - this one goes to header for auth 
    export const publicRequest = axios.create({
    baseURL: BASE_URL,
   });

export const userRequest = axios.create({
    baseURL: BASE_URL,
    header: { token: `Bearer ${TOKEN}` },
});

购物车页面:

const Cart = () => {
   const cart = useSelector((state) => state.cart);
   let navigate = useNavigate();
// STRIPE Payment
   let [stripeToken, setStripeToken] = useState("");
  let onToken = (token) => {
setStripeToken(token);
};

useEffect(() => {
const makeRequest = async () => {

  try {
    let res = await userRequest.post("/checkout/payment", {
      tokenId: stripeToken.id,
      amount: cart.total * 100,
    });
    navigate("/success", {
      replace: true,
      stripeData: res.data,
      products: cart,
    });
  } catch { }
};
stripeToken && makeRequest();
}, [stripeToken, cart.total, cart, navigate]);

 return (
<div> 
<some elements />
<some elements />
<some elements />

//BUTTON 
<StripeCheckout
          name="SHOP NAME"
          image="https://icons.iconarchive.com/icons/icons8/windows- 
8/512/Logos-Google-Code-icon.png"
          billingAddress
          shippingAddress
          currency="EUR" // usd is default , you can ignore this for usd 
          description={`total: ${cart.total}`}
          amount={cart.total * 100} // 100 = 1.00usd 
          token={onToken}
          stripeKey={STRIPE_PUBLIC_KEY}
        >
          <Button>PAY?</Button>
        </StripeCheckout>
 <div>
 )

成功页面:

const Success = () => {
const location = useLocation();
const data = location.stripeData; // **location.state.stripeData FAILS!**
const cart = location.cart;
const currentUser = useSelector((state) => state.user.currentUser);
const [orderId, setOrderId] = useState(null);

useEffect(() => {
    const createOrder = async () => {
        try {
            const res = await userRequest.post("/orders", {
                userId: currentUser._id,
                products: cart.products.map((item) => ({
                    productId: item._id,
                    quantity: item._quantity,
                })),
                amount: cart.total,
                address: data.billing_details.address,
            });
            setOrderId(res.data._id);
        } catch { }
    };
    data && createOrder();
}, [cart, data, currentUser]);

return (
    <div
        style={{
            height: "100vh",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
        }}
    >
        {orderId
            ? `Order has been created successfully. Your order number is 
 ${orderId}`
            : `Successfull. Your order is being prepared...`}
        <button style={{ padding: 10, marginTop: 20 }}>Go to 
  Homepage</button>
    </div>
);
};

export default Success

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 1970-01-01
    • 2015-05-28
    • 2017-10-12
    • 2015-04-12
    • 2012-06-16
    • 2022-01-08
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多