
本文档介绍了如何在使用 Stripe 预构建结账页面后获取客户数据,特别是客户 ID,以便将其存储在数据库中。重点在于利用 Stripe Webhooks 监听 checkout.session.completed 事件,并提供相关文档链接,帮助开发者成功集成和处理客户信息。
使用 Stripe Webhooks 获取客户 ID
Stripe 预构建结账页面简化了支付流程,但有时需要获取客户信息,例如客户 ID,以便在自己的系统中进行管理。由于 Stripe 会自动处理客户的创建,因此需要使用 Webhooks 来获取相关信息。
方法:通过 Webhooks 监听 checkout.session.completed 事件
当用户成功完成结账流程后,Stripe 会触发 checkout.session.completed 事件。我们可以设置 Webhook 来监听此事件,并在事件处理程序中获取客户 ID。
步骤 1:配置 Webhook 端点
首先,需要在 Stripe 控制台中配置一个 Webhook 端点。这个端点是一个 URL,Stripe 会将事件数据以 POST 请求的形式发送到这个 URL。
- 登录 Stripe 控制台:https://www.php.cn/link/65b6edfd9f135a6a1dbe075fb82c411f
- 导航到 "开发者" -> "Webhooks"。
- 点击 "添加端点"。
- 输入你的 Webhook URL。
- 选择要监听的事件:checkout.session.completed。
- 保存配置。
步骤 2:编写 Webhook 处理程序
接下来,需要编写 Webhook 处理程序来接收和处理 checkout.session.completed 事件。以下是一个使用 PHP 的示例:
type == 'checkout.session.completed') {
$session = $event->data->object;
// Get the customer ID
$customer_id = $session->customer;
// TODO: Store the customer ID in your database
// Example:
// $db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// $stmt = $db->prepare("INSERT INTO customers (stripe_customer_id) VALUES (?)");
// $stmt->execute([$customer_id]);
error_log("Customer ID: " . $customer_id);
}
http_response_code(200); // Acknowledge receipt of the event代码解释:
- 首先,引入 Stripe PHP 库并设置 API 密钥。
- 然后,从请求中获取事件负载和签名,并使用 Stripe Webhook Secret 验证事件的真实性。
- 如果事件类型是 checkout.session.completed,则从事件数据中提取 customer 字段,该字段包含客户 ID。
- 最后,将客户 ID 存储到数据库中。
步骤 3:配置 Checkout Session (可选)
如果在创建 Checkout Session 时已经有 Customer ID,可以直接传入:
\Stripe\Stripe::setApiKey('sk_test_51J...........esLwtMQx7IXNxp00epljtC43');
header('Content-Type: application/json');
$YOUR_DOMAIN = 'mydomain.com';
$customer_id = 'cus_...'; // Replace with your existing customer ID
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price'=>"price_1Jt.....vImqj",
'quantity'=>1,
]],
'mode' => 'subscription',
'customer' => $customer_id, // Pass existing customer ID
'success_url' => $YOUR_DOMAIN . '/success.php',
'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);注意事项:
- 务必验证 Webhook 事件的签名,以确保事件来自 Stripe,而不是恶意攻击者。
- 在生产环境中,使用安全的数据库连接和参数化查询,以防止 SQL 注入攻击。
- 处理 Webhook 事件时,要快速响应,避免长时间阻塞 Stripe 的 Webhook 服务器。如果需要执行耗时操作,可以使用队列或异步任务。
- endpoint_secret 可以在 Stripe 控制台的 Webhook 端点配置中找到。
总结
通过设置 Stripe Webhook 并监听 checkout.session.completed 事件,可以有效地获取使用 Stripe 预构建结账页面创建的客户的 ID。 这使得您可以将 Stripe 的支付功能与自己的数据库和客户管理系统集成,从而实现更完善的业务流程。 记住要验证 Webhook 事件的签名,并安全地存储客户数据。










