如何在PHP中从customer.subscription.created事件获取Payment Link元数据?
解决Stripe customer.subscription.created事件获取Payment Link元数据的PHP方案
有两种可靠的方案可以实现你的需求,以下是具体实现方式:
方案一:通过订阅关联的Checkout Session拉取元数据
customer.subscription.created事件返回的订阅对象中包含checkout_session字段(对应创建订阅的Checkout会话ID),你可以通过这个ID调用Stripe API查询会话详情,从而获取Payment Link传递的元数据。
PHP实现代码:
require_once('vendor/autoload.php'); \Stripe\Stripe::setApiKey('你的Stripe Secret Key'); // 接收Webhook payload $payload = file_get_contents('php://input'); $event = \Stripe\Event::constructFromJson($payload); if ($event->type === 'customer.subscription.created') { $subscription = $event->data->object; // 获取关联的Checkout Session ID $checkoutSessionId = $subscription->checkout_session; if ($checkoutSessionId) { try { // 查询Checkout Session详情 $checkoutSession = \Stripe\Checkout\Session::retrieve($checkoutSessionId); // 提取Payment Link携带的元数据 $registrationData = $checkoutSession->metadata; // 执行系统注册逻辑,例如: // $username = $registrationData['username']; // $email = $registrationData['email']; // saveUserToDatabase($username, $email); } catch (\Stripe\Exception\ApiErrorException $e) { // 记录异常日志 error_log('Stripe API调用失败: ' . $e->getMessage()); } } }
方案二:直接将元数据附加到订阅对象(推荐)
创建Payment Link时,通过subscription_data.metadata字段将注册数据直接绑定到订阅对象上,这样customer.subscription.created事件触发时可以直接从订阅对象中读取元数据,无需额外API调用。
PHP实现代码(创建Payment Link时):
$paymentLink = \Stripe\PaymentLink::create([ 'line_items' => [ [ 'price' => '你的订阅价格ID', 'quantity' => 1, ], ], 'mode' => 'subscription', // 将用户注册数据存入订阅元数据 'subscription_data' => [ 'metadata' => [ 'username' => '用户注册用户名', 'email' => '用户注册邮箱', // 其他需要的注册字段 ], ], ]);
处理Webhook事件时直接读取:
require_once('vendor/autoload.php'); \Stripe\Stripe::setApiKey('你的Stripe Secret Key'); $payload = file_get_contents('php://input'); $event = \Stripe\Event::constructFromJson($payload); if ($event->type === 'customer.subscription.created') { $subscription = $event->data->object; $registrationData = $subscription->metadata; // 执行系统注册逻辑 }
注意事项
- 若用户在Checkout页面填写自定义注册信息,可通过Checkout的
custom_fields收集,再将这些字段同步到subscription_data.metadata中。 - 务必为Webhook配置签名验证,防止恶意请求伪造事件。
- 方案二无需额外API调用,性能更优,优先推荐使用。
内容的提问来源于stack exchange,提问作者techdog
相关产品推荐
相关产品推荐

