【问题标题】:Stripe testing works only on localhost条带测试仅适用于本地主机
【发布时间】:2021-07-01 17:58:40
【问题描述】:

条带测试付款在 localhost 上运行良好,但是当应用程序部署到数字海洋测试时不起作用,我没有得到 clientSecret(下面的代码)。

我也遇到了这个错误: 从源“http://www.e-keyboards.com”访问“http://e-keyboards.com/api/create-payment-intent”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“访问控制” -Allow-Origin' 标头出现在请求的资源上

来自后端的代码:

const stripe = require('stripe')(process.env.STRIPE_SECRET)

exports.createPaymentIntent = async (req, res) => {

    const user = await User.findOne({email: req.user.email}).exec()

    const cart = await Cart.findOne({orderedBy: user._id}).exec()

    const {cartTotal} = cart

    console.log('CART TOTAL CHARGED', cart.cartTotal)
    const paymentIntent = await stripe.paymentIntents.create({
        amount: cartTotal * 100,
        currency: 'eur'
    })

    res.send({
        clientSecret: paymentIntent.client_secret,
        cartTotal,
    })
}

条带路线:

const express = require('express')
const router = express.Router()

const {
    createPaymentIntent
} = require('../controllers/stripe')

const {
    authCheck
} = require('../middlewares/auth')
const { checkout } = require('./auth')

router.post('/create-payment-intent', authCheck, createPaymentIntent)

module.exports = router

前端代码:

 let {cart, user, checkout} = useSelector(state => ({...state})) 

    const [error, setError] = useState(null)
    const [processing, setProcessing] = useState('')
    const [disabled, setDisabled] = useState(true)
    const [clientSecret, setClientSecret] = useState('')
    const [cartTotal, setCartTotal] = useState(0)


    const stripe = useStripe()
    const elements = useElements()
    const options = useOptions();

    useEffect(() => {
        createPaymentIntent(user.token)
        .then(res => {
            setClientSecret(res.data.clientSecret)
            setCartTotal(res.data.cartTotal)
        })
    }, [user.token])

    const handleSubmit = async e => {
        e.preventDefault()
        setProcessing(true)

        const payload = await stripe.confirmCardPayment(clientSecret, {
          payment_method:{
            card: elements.getElement(CardNumberElement),
            billing_details: {
              name: e.target.name.value
            }
          }
        })

        if(payload.error){
          setError(`Payment failed ${payload.error.message}`)
        }else{
          console.log(JSON.stringify(payload, null, 4))
          createOrder(payload, user.token)
          .then(res => {
            if(res.data.ok){
              if(typeof window !== "undefined") localStorage.removeItem('cart')
              dispatch(emptyCart())
              dispatch(checkoutChange(false))
              localStorage.removeItem('checkout')
              empytUserCart(user.token)
              toast.success('Payment successfull!!')
            }
          })
          setError(null)
          setProcessing(false)
        }
    }

createPaymentIntent 函数:

export const createPaymentIntent = (authtoken) => axios.post(`${process.env.REACT_APP_API}/create-payment-intent`, 
    {},
    {
        headers: {
            authtoken
        }
    })

我添加了 “内容类型”:“文本/纯文本”, “访问控制允许来源”:“*” 到 createPaymentIntent 函数中的 headers 对象,但仍然出现错误并且仍然没有得到 res.data.clientSecret 和 res.data.cartTotal 的反应。 再次 - 在 localhost 上一切正常。问题出现在已部署的应用程序中。

【问题讨论】:

    标签: node.js reactjs frontend stripe-payments backend


    【解决方案1】:

    您使用的来源(特别是域名)不匹配,并且您没有配置 CORS 以允许来源不匹配。

    具体来说,您的页面似乎是从http://www.e-keyboards.com 的来源加载的,并且正在尝试向具有不同来源的http://e-keyboards.com/api/create-payment-intent 发出请求 (http://e-keyboards.com)。检查您的 process.env.REACT_APP_API 值以及您用于加载页面的 URL。

    如果您将所有内容切换为 http://e-keyboards.com http://www.e-keyboards.com,则应该可以正常工作。您还可以配置 CORS 以允许跨域请求,但使源匹配可能更容易。

    【讨论】:

    • 我没有收到以前的错误,但仍然无法正常工作。现在我得到:“POST e-keyboards.com/api/create-payment-intent 504 (Gateway Time-out)”和“Uncaught (in promise) Error: Request failed with status code 504 at createError (createError.js:16) at resolve (settle.js: 17) 在 XMLHttpRequest.handleLoad (xhr.js:62)"
    • @Justin 你能看看这个问题吗:stackoverflow.com/q/66983230/9409877
    • 我看了看,但问题似乎在 cmets 中得到了解决。很高兴听到您成功了!
    猜你喜欢
    • 2018-11-16
    • 2017-02-25
    • 2023-04-05
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2012-10-08
    相关资源
    最近更新 更多