要实现 Stripe 的 PHP 回调接口(Webhook 接收器),你需要编写一个 PHP 脚本来接收 Stripe 的异步事件通知,比如支付成功、退款、订阅续费等。

下面是一个完整的 Stripe 支付回调实现教程,包括验证签名、处理事件、日志记录等关键点。


✅ 一、准备工作

  1. 登录 Stripe Dashboard
  2. 进入:Developers > Webhooks
  3. 添加你的 PHP 回调地址,例如:https://example.com/stripe/webhook.php
  4. 复制 Webhook Signing Secret(例如 whsec_xxxx

🔧 二、安装 Stripe PHP SDK(推荐 Composer 安装)

composer require stripe/stripe-php

🧪 三、创建 webhook.php 文件(回调入口)

<?php
require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test_xxxx'); // 可选,不一定需要

// 签名密钥(在 Stripe Dashboard 中获得)
$endpoint_secret = 'whsec_xxxx';

// 从请求体中读取原始内容
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];

try {
    $event = \Stripe\Webhook::constructEvent(
        $payload, $sig_header, $endpoint_secret
    );
} catch(\UnexpectedValueException $e) {
    // 无效 payload
    http_response_code(400);
    exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
    // 签名验证失败
    http_response_code(400);
    exit();
}

// 处理事件类型
switch ($event->type) {
    case 'payment_intent.succeeded':
        $paymentIntent = $event->data->object;
        // 处理成功支付逻辑,如写入数据库、发邮件等
        file_put_contents('stripe_log.txt', "支付成功订单:" . $paymentIntent->id . "\n", FILE_APPEND);
        break;

    case 'charge.refunded':
        $charge = $event->data->object;
        // 处理退款逻辑
        break;

    // 处理其他类型事件
    default:
        // 忽略未处理的事件
        break;
}

http_response_code(200); // 告诉 Stripe 接收成功
echo "success";

🧠 四、验证签名的重要性(防止伪造请求)

Stripe\Webhook::constructEvent() 会根据 HTTP_STRIPE_SIGNATURE 和你配置的密钥自动验证请求是否来自 Stripe。

不要使用:

json_decode($_POST['data'])

这种方式是不安全的!


🗂️ 五、推荐目录结构

/stripe/
  ├── webhook.php
  ├── stripe_log.txt
  └── vendor/

📊 六、Stripe 常见事件类型

事件类型描述
payment_intent.succeeded支付成功
payment_intent.failed支付失败
charge.refunded用户退款成功
invoice.paid订阅账单支付成功
customer.subscription.created创建订阅

可查看完整列表:https://stripe.com/docs/api/events/types


🧩 七、调试建议

  • 使用 Stripe CLI 本地测试:stripe listen --forward-to localhost/stripe/webhook.php
  • 日志写入 file_put_contents 或数据库,便于调试
  • 保证 webhook.php 可公网访问,否则 Stripe 发不进来

🔐 八、安全建议

  • 强烈建议启用签名验证(已在示例中实现)
  • 不要公开暴露敏感密钥
  • 限制 webhook 访问频率(可配置防火墙或 Nginx)

✅ 九、总结

步骤说明
配置 Webhook在 Stripe 后台设置回调地址
接收数据使用 php://input 接收原始数据
验证签名使用 constructEvent() 验证来源
处理逻辑根据事件类型进行业务处理(如发货、通知)