
本文档介绍了如何在使用 Stripe 预构建结账页面后获取客户数据,特别是客户 ID,以便将其存储在数据库中。重点在于利用 Stripe Webhooks 监听 checkout.session.completed 事件,并提供相关文档链接,帮助开发者成功集成和处理客户信息。
Stripe 预构建结账页面简化了支付流程,但有时需要获取客户信息,例如客户 ID,以便在自己的系统中进行管理。由于 Stripe 会自动处理客户的创建,因此需要使用 Webhooks 来获取相关信息。
当用户成功完成结账流程后,Stripe 会触发 checkout.session.completed 事件。我们可以设置 Webhook 来监听此事件,并在事件处理程序中获取客户 ID。
步骤 1:配置 Webhook 端点
首先,需要在 Stripe 控制台中配置一个 Webhook 端点。这个端点是一个 URL,Stripe 会将事件数据以 POST 请求的形式发送到这个 URL。
步骤 2:编写 Webhook 处理程序
接下来,需要编写 Webhook 处理程序来接收和处理 checkout.session.completed 事件。以下是一个使用 PHP 的示例:
<?php
require 'vendor/autoload.php';
// Replace with your actual secret key
\Stripe\Stripe::setApiKey('sk_test_51J...........esLwtMQx7IXNxp00epljtC43');
// You need to configure the webhook endpoint secret in your Stripe dashboard
$endpoint_secret = 'whsec_...';
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
// Handle the checkout.session.completed event
if ($event->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代码解释:
步骤 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',
]);注意事项:
通过设置 Stripe Webhook 并监听 checkout.session.completed 事件,可以有效地获取使用 Stripe 预构建结账页面创建的客户的 ID。 这使得您可以将 Stripe 的支付功能与自己的数据库和客户管理系统集成,从而实现更完善的业务流程。 记住要验证 Webhook 事件的签名,并安全地存储客户数据。
以上就是从 Stripe 预构建结账页面获取客户数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号