无需Express在SvelteKit中自定义Stripe成功页面并获取客户名
问题描述
我希望在SvelteKit应用的Stripe支付成功页面显示客户名称。
Stripe官方提供了自定义成功页面的教程,但示例使用Express框架搭建Node端点,我希望避免使用该框架。官方示例代码如下:
const express = require('express'); const app = express(); // Set your secret key. Remember to switch to your live secret key in production. // See your keys here: https://dashboard.stripe.com/apikeys const stripe = require('stripe')('sk_test_26PHem9AhJZvU623DfE1x4sd'); app.get('/order/success', async (req, res) => { const session = await stripe.checkout.sessions.retrieve(req.query.session_id); const customer = await stripe.customers.retrieve(session.customer); res.send(`<html><body><h1>Thanks for your order, ${customer.name}!</h1></body></html>`); }); app.listen(4242, () => console.log(`Listening on port ${4242}!`));
我的代码(已更新)
成功路由地址为:http://localhost:5173/success?session_id=cs_test_123456789
我的success路由包含+page.svelte文件,它会向+server.js发送fetch请求,该文件代码如下:
import Stripe from 'stripe'; import { STRIPE_SECRET_KEY } from '$env/static/private'; import { json } from '@sveltejs/kit'; const stripe = new Stripe(STRIPE_SECRET_KEY); export async function GET ( req ) { console.log(req.url.searchParams.get('session_id')); const session = await stripe.checkout.sessions.retrieve(req.url.searchParams.get('session_id')); const customer = await stripe.customers.retrieve(session.customer); console.log(`${customer.name}, thanks for subscribing!`); return json(customer); }
目前遇到的问题:console.log(req.url.searchParams.get('session_id'));返回null,理论上应返回session_id字符串,随后Stripe报错:Error: Stripe: Argument "session" must be a string, but got: null (on API request to GET /v1/checkout/sessions/{session})。若手动替换为实际session_id(如'cs_test_123456789')则可正常获取客户名称。
寻求解决方案
我知道可以创建+page.js文件,通过export function load({ url })提取searchParams后再传递给GET请求,但有没有更简洁优雅的处理方式?
替代方案
参考他人思路后,我将+server.js重命名为+page.server.js,代码如下:
import Stripe from 'stripe'; import { STRIPE_SECRET_KEY } from '$env/static/private'; const stripe = new Stripe(STRIPE_SECRET_KEY); export async function load({ url }) { const session_id = url.searchParams.get('session_id') // 获取完整的Stripe会话对象 const session = await stripe.checkout.sessions.retrieve(session_id) // 获取会话关联的客户信息 const customer = await stripe.customers.retrieve(session.customer) // 提取客户名称 let customer_name = customer.name return { customer_name } }
内容的提问来源于stack exchange,提问作者maxmax
相关产品推荐
相关产品推荐

