使用 Stripe Checkout 获取客户数据并集成到数据库

碧海醫心
发布: 2025-09-30 19:42:02
原创
684人浏览过

使用 stripe checkout 获取客户数据并集成到数据库

本文档旨在指导开发者如何在使用 Stripe 预构建 Checkout 集成到网站后,获取客户数据(特别是 Customer ID),并将其存储到 MySQL 数据库中。重点介绍如何通过 Stripe Webhooks 监听 checkout.session.completed 事件,并从中提取所需的客户信息。

Stripe 预构建 Checkout 提供了一种快速且安全的方式来接受付款,但有时我们需要在自己的数据库中存储客户信息,例如 Customer ID。由于 Checkout 会自动根据用户提供的邮箱等信息创建客户,我们需要一种方法来获取这个 Customer ID。本文将介绍如何通过 Stripe Webhooks 实现这一目标。

1. 创建 Checkout Session

首先,我们需要创建一个 Checkout Session。以下是一个示例 PHP 代码:

<?php

require_once 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test_51J...........esLwtMQx7IXNxp00epljtC43');

header('Content-Type: application/json');

$YOUR_DOMAIN = 'mydomain.com';

$checkout_session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => [[
      'price'=>"price_1Jt.....vImqj",
      'quantity'=>1,
    ]],
    'mode' => 'subscription',
    'success_url' => $YOUR_DOMAIN . '/success.php',
    'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
  ]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);
登录后复制

注意: sk_test_51J...........esLwtMQx7IXNxp00epljtC43 替换为你自己的 Stripe 测试密钥。mydomain.com 替换为你自己的域名。

在创建 Checkout Session 时,我们没有显式地传递 customer 参数。这意味着 Stripe 将根据用户在 Checkout 流程中提供的信息自动创建一个新的 Customer 对象。

2. 设置 Stripe Webhooks

Webhooks 允许你的应用程序在 Stripe 上发生特定事件时接收实时通知。 为了获取 Customer ID,我们需要监听 checkout.session.completed 事件。

2.1. 创建 Webhook Endpoint

首先,你需要创建一个 Webhook endpoint,Stripe 将向其发送事件数据。 这个 endpoint 应该是一个可以接收 POST 请求的 URL。

<?php

require_once 'vendor/autoload.php';

// Replace with your actual secret key
$stripeSecretKey = 'whsec_YOUR_WEBHOOK_SECRET';

// The library needs to have its signature validation disabled if using
// a Webhook signing secret.
\Stripe\Stripe::setApiKey('sk_test_51J...........esLwtMQx7IXNxp00epljtC43');

// Use setWebhookSignatureValidation if you want to use a Webhook signing secret
\Stripe\Stripe::setWebhookSignatureValidation($stripeSecretKey);

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;

try {
    $event = \Stripe\Webhook::constructEvent(
        $payload, $sig_header, $stripeSecretKey
    );
} 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:
  // $mysqli = new mysqli("localhost", "user", "password", "database");
  // $stmt = $mysqli->prepare("INSERT INTO customers (customer_id) VALUES (?)");
  // $stmt->bind_param("s", $customer_id);
  // $stmt->execute();

  echo "Customer ID: " . $customer_id . "\n";
}

http_response_code(200); // Return a 200 OK response
登录后复制

注意: whsec_YOUR_WEBHOOK_SECRET 替换为你自己的 Webhook Secret。 sk_test_51J...........esLwtMQx7IXNxp00epljtC43 替换为你自己的 Stripe 测试密钥。 确保你的 Webhook endpoint 可以公开访问。

2.2. 配置 Webhook

  1. 登录你的 Stripe 仪表盘。
  2. 导航到 "开发者" -youjiankuohaophpcn "Webhooks"。
  3. 点击 "添加 endpoint"。
  4. 在 "Endpoint URL" 字段中输入你的 Webhook endpoint 的 URL。
  5. 在 "要发送的事件" 部分,选择 "checkout.session.completed"。
  6. 点击 "添加 endpoint"。

3. 处理 checkout.session.completed 事件

当 Checkout Session 成功完成时,Stripe 会向你的 Webhook endpoint 发送一个 checkout.session.completed 事件。 在你的 Webhook endpoint 中,你需要解析这个事件并提取 Customer ID。

知我AI·PC客户端
知我AI·PC客户端

离线运行 AI 大模型,构建你的私有个人知识库,对话式提取文件知识,保证个人文件数据安全

知我AI·PC客户端 0
查看详情 知我AI·PC客户端

在上面的示例代码中,我们已经演示了如何处理 checkout.session.completed 事件,并从中提取 Customer ID。

4. 将 Customer ID 存储到数据库

最后,你需要将提取到的 Customer ID 存储到你的 MySQL 数据库中。 在上面的示例代码中,我们提供了一个简单的示例,展示了如何使用 PHP 和 MySQLi 扩展来将 Customer ID 插入到 customers 表中。 你需要根据你的实际数据库结构和需求进行修改。

注意: 请务必对数据库操作进行适当的错误处理和安全措施,以防止 SQL 注入等安全问题。

5. 可选: 传递现有 Customer ID

如果你希望在创建 Checkout Session 时使用现有的 Customer ID,可以在创建 Checkout Session 时传递 customer 参数。

<?php

require_once 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test_51J...........esLwtMQx7IXNxp00epljtC43');

header('Content-Type: application/json');

$YOUR_DOMAIN = 'mydomain.com';

// Replace with your existing Customer ID
$existing_customer_id = 'cus_XXXXXXXXXXXXXXX';

$checkout_session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => [[
      'price'=>"price_1Jt.....vImqj",
      'quantity'=>1,
    ]],
    'mode' => 'subscription',
    'success_url' => $YOUR_DOMAIN . '/success.php',
    'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
    'customer' => $existing_customer_id, // Pass the existing Customer ID
  ]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);
登录后复制

注意: cus_XXXXXXXXXXXXXXX 替换为你自己的 Customer ID。

如果传递了 customer 参数,Stripe 将不会创建新的 Customer 对象,而是使用指定的 Customer 对象。

总结

通过使用 Stripe Webhooks,我们可以轻松地获取 Stripe Checkout 创建的 Customer ID,并将其存储到我们的数据库中。 这使得我们可以更好地管理客户信息,并将其与其他业务数据集成。 请务必仔细阅读 Stripe 官方文档,并根据你的实际需求进行调整。 此外,请始终关注安全性,并采取必要的措施来保护你的数据。

以上就是使用 Stripe Checkout 获取客户数据并集成到数据库的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号