我正在制作一个通过Stripe管理支付的React应用程序。Stripe有"产品"。你可以将产品和价格id复制到你的代码中,然后Stripe将注册你的付款并将其链接到所选产品。我是Stripe的新手,不太清楚该怎么做。目前,我在"描述"中传递产品名称。字段和价格作为整数。
这是我的条纹元素代码:<Elements stripe={stripePromise}>
<CheckoutForm price='1000' name='orientacion'/>
</Elements>
价格和名称道具传递给CheckoutFrom组件:
import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import { Elements, CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import {Button, Form} from 'react-bootstrap';
import axios from 'axios';
const stripePromise = loadStripe('pk_test_MYPUBLICKEY');
const CheckoutForm = (props) => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement)
});
if (!error) {
console.log(paymentMethod);
const { id } = paymentMethod;
console.log('id');
console.log(id)
const data = await axios.post('http://localhost:3001/api/checkout',
{
id,
amount: props.price,
description: props.name
}
);
console.log(data);
} else {
console.log(error);
}
}
return (
<Form onSubmit ={handleSubmit}>
<CardElement />
<p>Price: {props.price/100} eur</p>
<Button type='submit'>
Comprar
</Button>
</Form>
)
}
export default CheckoutForm;
从那里它们被发送到我的本地服务器:
const express = require('express');
const Stripe = require('stripe');
const cors = require('cors');
const app = express();
const stripe = new Stripe('sk_test_51IRxezLeEfBz7v63tNaTPPWBdlMaVCVHxVDsqQ5Z4BzVxIf5fgxI4fTkznzt1S8ZRNnyc146VPqA29I4lmsNl1C600nnih2m6x');
app.use(cors({origin: 'http://localhost:3000'}));
app.use(express.json());
app.post('/api/checkout', async (req, res) => {
const {id, amount, description} = req.body;
const payment = await stripe.paymentIntents.create({
amount,
currency: "EUR",
description,
payment_method: id,
confirm: true
});
console.log(payment);
res.send({message: 'Sucess payment'});
});
app.listen(3001, () => {
console.log('server listened', 3001)
})
将其发送到Stripe。那么我如何告诉stripe使用价格和产品id呢?
产品和价格与订阅和结帐相关联,而不是与付款意图相关联。所以,你不能将现有的Product和Price附加到PaymentIntent。
例如,您可以将产品和价格附加到结帐:https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-line_items或订阅:https://stripe.com/docs/api/subscriptions/create
如果你想实现PaymentIntent,我的建议是在你的网站上列出你的产品供用户选择,然后从价格中提取amount
并传递到PaymentIntent的amount
。