[英]Stripe Invalid API Key provided: undefined with express node.js
我正在为 Stripe 支付 api 苦苦挣扎。 当我在填写数据和卡号后单击按钮时,它进入支付成功页面,但控制台上有错误。 它说提供了Invalid API Key provided: undefined
Stripe 建议我使用付款方式,但在我的代码上有付款方式。 我不知道是什么问题。
这是我的代码
import React from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
//make the card elements
const stripePromise = loadStripe(`${process.env.PUBLISHABLE_KEY}`);
console.log(stripePromise);
const CheckoutFormWrap = ({ children }) => {
return (
<div>
<Elements stripe={stripePromise}>{children}</Elements>
</div>
);
};
CheckoutForm.js
import React, { useState } from 'react';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
import BillingDetailsFields from './BillingDetailForm';
import axios from 'axios';
import styled from 'styled-components';
const CheckoutForm = ({ price, onSuccessfulCheckout }) => {
const [isProcessing, setProcessingTo] = useState(false);
const [checkoutError, setCheckoutError] = useState();
const stripe = useStripe();
const elements = useElements();
const handleCardDetailsChange = ev => {
ev.error ? setCheckoutError(ev.error.message) : setCheckoutError();
};
const handleFormSubmit = async e => {
e.preventDefault();
const billingDetails = {
name: e.target.name.value,
email: e.target.email.value,
};
setProcessingTo(true);
const cardElement = elements.getElement(CardElement);
const { data: clientSecret } = await axios.post("http://localhost:5000/pay",
{amount: price}
);
console.log(clientSecret);
const paymentMethodReq = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: billingDetails,
});
const confirmCardPayment = await stripe.confirmCardPayment(clientSecret,{
payment_method: paymentMethodReq.paymentMethod,
})
onSuccessfulCheckout();
console.log(confirmCardPayment);
if (paymentMethodReq.error) {
setCheckoutError(paymentMethodReq.error.message);
setProcessingTo(false);
return;
}
};
return (
<form onSubmit={handleFormSubmit}>
<div>
<CheckoutTitle>Pay with</CheckoutTitle>
<BillingDetailsFields />
</div>
<div>
<CardElementContainer>
<CardElement
onChange={handleCardDetailsChange}
/>
</CardElementContainer>
</div>
<div>
<PayBtn disabled={isProcessing || !stripe}>
{isProcessing ? 'Processing...' : `Confirm and Pay`}
</PayBtn>
</div>
</form>
);
};
export default CheckoutForm;
server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, error => {
if (error) throw error;
console.log('server running on port' + port);
});
app.post('/pay', async (req, res) => {
if (req.method === 'POST') {
try {
const { amount } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
payment_method_types: ['card_present'],
});
res.status(200).send(paymentIntent.client_secret);
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message });
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
});
有任何想法吗?
我看到两个问题:
loadStripe
和您的可发布密钥初始化 Stripe.js ,并像文档所说的那样设置Elements
提供程序?confirmCardPayment
您可能需要使用paymentMethodReq.paymentMethod.id
因为createPaymentMethod
返回一个对象。请注意,您不需要进行两次调用。 您可以将付款方式创建和付款意向确认合并为一个步骤, 如下所示:
const result = await stripe.confirmCardPayment('{CLIENT_SECRET}', {
payment_method: {
card: cardElement,
billing_details: billingDetails,
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.