我正在将前端应用程序与 Stripe 集成以进行支付处理。
我正在遵循快速入门文档,并且几乎一切正常,但是我没有被自动重定向。我确实得到了一个包含链接的成功响应,因此从响应中提取该链接不会太困难。但是,如果这不是预期的实现,我不想这样做。
我的后端:
@app.post('/create-checkout-session')
async def create_checkout_session(request: Request):
data = await request.json()
price_id = data['price_id']
try:
checkout_session = stripe.checkout.Session.create(
line_items=[
{
# Provide the exact Price ID (for example, pr_1234) of the product you want to sell
'price': price_id,
'quantity': 1,
},
],
mode='subscription',
success_url='http://localhost:3000' + '?success=true',
cancel_url='http://localhost:3000' + '?canceled=true',
)
except Exception as e:
print(e)
return str(e)
return redirect(checkout_session.url, code=303)
我的前端api调用:
fetch("{backend}/create-checkout-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify({ price_id: "price_1P3O6zRsJS40xuhRCkN4vrML" }),
});
以及对 api 调用的响应
{
"headers": {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": "905",
"Location": "https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl"
},
"_status": "303 SEE OTHER",
"_status_code": 303,
"direct_passthrough": false,
"_on_close": [],
"response": [
"<!doctype html>\n<html lang=en>\n<title>Redirecting...</title>\n<h1>Redirecting...</h1>\n<p>You should be redirected automatically to the target URL: <a href=\"https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl\">https://checkout.stripe.com/c/pay/cs_test_a1ODicN9C2lxgpSowo6RVXl8G1FaBFwaJrkgKwtuPKE6LBSIV5izrxyT67#fidkdWxOYHwnPyd1blpxYHZxWjA0Sn9cR1ZXdk9WMTV9cG1Xcnd0N38wN2prTnBHbUcxTDNUd3V0fW9uSFRWUEdhS29WdF1cXH1jbmRSXX1Tdnd2Yn1MazVwaTNkMHU3cXdKY2tIM2J9VTdrNTU8R092cjZudCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYHgl</a>. If not, click the link.\n"
]
}
如果很重要,我的 python 端点中的
redirect
调用来自 flask
我提供了我的示例代码。我使用 Node.js/Express 后端和 React/Redux 前端。
后端代码:
const createCheckoutSession = async (req, res) => {
try {
const { priceId, type } = req.body;
const email = req?.decoded?.email;
// Check if user exists
const user = await User.findOne({ email });
if (!user) {
return res.status(404).json({ error: MESSAGE.USER_NOT_FOUND });
}
// Create a new checkout session
const session = await stripe.checkout.sessions.create({
customer_email: email, // Associate session with existing customer
mode: type, // subscription
payment_method_types: ['card'],
line_items: [{ price: priceId, quantity: 1 }],
allow_promotion_codes: true,
automatic_tax: { enabled: true },
success_url: config.STRIPE_SUCCESS_URL,
cancel_url: config.STRIPE_CANCELED_URL,
});
// Return the session ID
return res.status(200).json({ id: session.id });
} catch (error) {
// Handle errors
console.log(error)
return res.status(500).json({ message: error.message });
}
};
前端代码:
import { loadStripe } from '@stripe/stripe-js';
const handlePayment = async () => {
setLoading(true);
try {
const stripe = await loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
const response = await api.post('/api/create-checkout-session', JSON.stringify(item));
const { id: sessionId } = response.data;
const result = await stripe.redirectToCheckout({ sessionId });
if (result.error) {
console.error(result.error);
}
} catch (error) {
console.error('Error processing payment:', error);
} finally {
setLoading(false);
}
};
您可以在您的 React 应用程序中使用 stripe-js。