Javascript 接受带条纹的在线支付
这是我第一次使用Stripe,我想做的就是这样。我已经为它创建了一个后端,用于测试目的。但我遇到了一个问题,当我单击“支付”按钮时,我在控制台中收到了此错误Javascript 接受带条纹的在线支付,javascript,node.js,reactjs,stripe-payments,Javascript,Node.js,Reactjs,Stripe Payments,这是我第一次使用Stripe,我想做的就是这样。我已经为它创建了一个后端,用于测试目的。但我遇到了一个问题,当我单击“支付”按钮时,我在控制台中收到了此错误Uncaught(in promise)IntegrationError:您必须提供条带元素或有效的令牌类型才能创建令牌。。是什么导致了这个错误 Server.js require("dotenv").config({ path: "./config.env" }); const express =
Uncaught(in promise)IntegrationError:您必须提供条带元素或有效的令牌类型才能创建令牌。
。是什么导致了这个错误
Server.js
require("dotenv").config({ path: "./config.env" });
const express = require("express");
const app = express();
const bodyParser = require('body-parser')
const postCharge = require('./routes/stripe')
const router = express.Router()
const cors = require("cors")
app.use(express.json());
app.use(cors());
router.post('/stripe/charge', postCharge)
router.all('*', (_, res) =>
res.json({ message: 'please make a POST request to /stripe/charge' })
)
app.use((_, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
)
next()
})
app.use(bodyParser.json())
app.use('/payment',router)
app.get('*', (_, res) => {
res.sendFile(path.resolve(__dirname, '../audible/public/index.html'))
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Sever running on port ${PORT}`)
);
Stripe.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_TEST)
async function postCharge(req, res) {
try {
const { amount, source, receipt_email } = req.body
const charge = await stripe.charges.create({
amount,
currency: 'usd',
source,
receipt_email
})
if (!charge) throw new Error('charge unsuccessful')
res.status(200).json({
message: 'charge posted successfully',
charge
})
} catch (error) {
res.status(500).json({
message: error.message
})
}
}
module.exports = postCharge
付款单
import React,{useContext, useState} from 'react'
import {CardElement, useStripe, useElements } from"@stripe/react-stripe-js"
import { CartContext } from '../../context/cart'
import axios from 'axios'
import { useHistory } from "react-router-dom";
const CARD_OPTIONS={
base: {
color: '#303238',
fontSize: '16px',
fontFamily: '"Open Sans", sans-serif',
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#CFD7DF',
},
},
invalid: {
color: '#e5424d',
':focus': {
color: '#303238',
},
},
}
const PaymentForm = () => {
const { total} = useContext(CartContext)
const stripe = useStripe();
const [receiptUrl, setReceiptUrl] = useState('')
const history = useHistory()
const {clearCart} = useContext(CartContext)
const elements = useElements()
const handleSubmit = async event => {
event.preventDefault()
const cardElement = elements.getElement(CardElement);
const { token } = await stripe.createToken()
const order = await axios.post('http://localhost:5000/api/stripe/charge', {
amount: 1000,
source: token,
card: cardElement,
receipt_email: 'customer@example.com'
})
setReceiptUrl(order.data.charge.receipt_url)
}
if (receiptUrl){
history.push('/');
clearCart();
return (
<div className="success">
<h2>Payment Successful!</h2>
</div>
)
}
return (
<>
<form onSubmit={handleSubmit}>
<fieldset className='form_group'>
<div className='formRow'>
<CardElement options={CARD_OPTIONS} />
</div>
</fieldset>
<button type='submit' className=''>Pay</button>
<h3>
order total : <span> ${total}</span>
</h3>
</form>
</>
)
}
export default PaymentForm
import React,{useContext,useState}来自“React”
从“@stripe/react stripe js”导入{CardElement,useStripe,useElements}
从“../../context/cart”导入{CartContext}
从“axios”导入axios
从“react router dom”导入{useHistory};
常量卡选项={
基数:{
颜色:'#303238',
fontSize:'16px',
fontFamily:“'开放式SAN',无衬线',
fontSmoothing:'抗锯齿',
“::占位符”:{
颜色:“#CFD7DF”,
},
},
无效:{
颜色:“#e5424d”,
“:焦点”:{
颜色:'#303238',
},
},
}
const PaymentForm=()=>{
const{total}=useContext(CartContext)
常量stripe=useStripe();
常量[receiptUrl,setReceiptUrl]=useState(“”)
const history=useHistory()
常量{clearCart}=useContext(CartContext)
常量元素=useElements()
const handleSubmit=异步事件=>{
event.preventDefault()
const cardElement=elements.getElement(cardElement);
const{token}=wait stripe.createToken()
常量顺序=等待axios.post('http://localhost:5000/api/stripe/charge', {
金额:1000,
资料来源:token,
卡片:cardElement,
收据(电邮):'customer@example.com'
})
setReceiptUrl(订单.数据.费用.收据\u url)
}
if(receiptUrl){
历史推送(“/”);
clearCart();
返回(
付款成功!
)
}
返回(
支付
订单总数:${total}
)
}
导出默认付款表单
条纹容器
import React from 'react'
import {loadStripe} from '@stripe/stripe-js'
import {Elements, } from '@stripe/react-stripe-js'
import PaymentForm from './PaymentForm'
const PUBLIC_KEY="pk_test_51IaINYEqJWuHZaMS8NbdFT8M7ssdvFXOqBO8gwn1MjQCJ9Mq5kYdraTFG4Y28i9xLtaWKJanVLLbjlrduQKHv00uJ0WbJnu"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
const StripeContainer = () => {
return (
<Elements stripe={stripeTestPromise}>
<PaymentForm />
</Elements>
)
}
export default StripeContainer
从“React”导入React
从“@stripe/stripe js”导入{loadStripe}
从'@stripe/react stripe js'导入{Elements,}
从“/PaymentForm”导入PaymentForm
const PUBLIC_KEY=“pk_test_51; iainyeqjwuzams8nbdft8m7ssdvfxoqbo8gwn1mjqcj9mq5kydratfg4y28i9xltawkjanvllbjlrduqkhv00uj0wbjnu”
const stripeTestPromise=loadStripe(公钥)
常量条带容器=()=>{
返回(
)
}
导出默认条带容器
我建议使用更新的支付意图和支付方法API,而不是使用代币和费用进行新的集成,如下所示
看起来您正在使用不推荐使用的react stripe元素
library(),该元素已被@stripe/react stripe js
库(,)替换
无论哪种情况,都需要确保使用提供程序初始化Stripe.js。使用如下()所示的较新库:
const stripePromise=loadStripe('pk_test_123');
常量应用=()=>{
返回(
);
};
如果要使用较旧的库,则提供程序的工作方式如下():
从'react stripe elements'导入{StripeProvider};
从“/MyStoreCheckout”导入MyStoreCheckout;
常量应用=()=>{
返回(
);
};
因此,我还必须更改backend/Node stripe.js以使用支付意图和支付方法是的,有一点。这不是必需的,但建议这样做。您也可以在较新的React库中使用代币和费用。
const stripePromise = loadStripe('pk_test_123');
const App = () => {
return (
<Elements stripe={stripePromise}>
<MyCheckoutForm />
</Elements>
);
};
import {StripeProvider} from 'react-stripe-elements';
import MyStoreCheckout from './MyStoreCheckout';
const App = () => {
return (
<StripeProvider apiKey="pk_test_12345">
<MyStoreCheckout />
</StripeProvider>
);
};