You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

访问Stripe Webhook页面时出现Undefined array key 'HTTP_STRIPE_SIGNATURE'警告

解决Stripe Webhook手动访问时的"Undefined array key 'HTTP_STRIPE_SIGNATURE'"警告

问题原因

  • 手动通过浏览器访问webhook URL时,浏览器不会发送Stripe回调所需的Stripe-Signature请求头,导致$_SERVER["HTTP_STRIPE_SIGNATURE"]未定义,触发警告。
  • Stripe后台发送的合法请求会自动携带该头,所以实际业务流程中不会出现这个问题,仅手动访问时会报错。

解决方案

在代码中先检查签名头是否存在,若不存在则直接返回错误响应,避免后续代码执行引发警告。同时可以使用PHP的空合并运算符处理变量赋值,彻底消除未定义索引的警告。

修改后的代码示例

<?php

require "..../stripe-php-11.0.0/init.php";

// Your Stripe webhook endpoint secret
$webhook_secret = "whsec_...";

// Initialize Stripe with your secret API key
\Stripe\Stripe::setApiKey("sk_test_....");

// 检查是否存在Stripe签名头,不存在则直接返回400
if (!isset($_SERVER["HTTP_STRIPE_SIGNATURE"])) {
    http_response_code(400);
    exit("This endpoint only accepts Stripe webhook requests.");
}

// 获取原始请求体和签名头,用空合并运算符避免未定义警告
$payload = file_get_contents("php://input");
$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"] ?? null;

try {
    // Verify the signature
    $event = \Stripe\Webhook::constructEvent(
        $payload,
        $sig_header,
        $webhook_secret,
    );
} catch (\Exception $e) {
    // Invalid signature or other error
    http_response_code(400);
    exit();
}

// Handle the event
switch ($event->type) {
    case "checkout.session.completed":
        $session = $event->data->object;

        // Process the 'checkout.session.completed' event here
        // You can retrieve information about the completed session in $session

        // Example: Send a confirmation email to the customer
        // mail($session->customer_email, 'Order Confirmation', 'Thank you for your purchase!');
        $sessionId = $session->id;

        // Implement your logic to initiate the file download here
        http_response_code(200); // Acknowledge receipt of the event
        break;

    // Add more cases to handle other types of events as needed
    // case 'invoice.paid':
    //     // Handle invoice paid event
    //     break;

    default:
        // Unknown event type
        http_response_code(200);
        break;
}

补充说明

这个webhook端点的设计目的是接收Stripe服务器的回调请求,而非供用户手动访问。添加上述判断后,既解决了手动访问的警告问题,也能防止非法请求进入业务逻辑。

内容的提问来源于stack exchange,提问作者Max Velox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:52:40