如何通过GoCardless API同时自动设置Direct Debit授权与订阅?
自动为GoCardless Direct Debit授权绑定订阅的可行方案
方案一:通过Webhook自动触发订阅创建
当客户完成授权流程后,GoCardless会发送mandate_created事件到你配置的webhook地址,你可以在后端监听这个事件,自动创建订阅。
步骤:
- 在GoCardless仪表盘配置webhook端点,确保端点能接收POST请求,并且开启
mandate_created事件通知。 - 后端实现webhook处理逻辑:
- 验证GoCardless的webhook签名(必须做,防止恶意请求)。
- 解析webhook的JSON payload,判断事件类型为
mandate_created。 - 从payload中提取
mandate_id和关联的customer_id。 - 调用GoCardless订阅API创建订阅,绑定该mandate。
示例代码:
// webhook处理脚本 $payload = file_get_contents('php://input'); $signature = $_SERVER['HTTP_GOCARDLESS_SIGNATURE']; // 替换为你的webhook密钥 $webhookSecret = 'your_webhook_secret'; if (!$client->webhooks()->validateSignature($payload, $signature, $webhookSecret)) { http_response_code(403); exit('Invalid signature'); } $event = json_decode($payload, true); if ($event['event_type'] === 'mandate_created') { $mandateId = $event['links']['mandate']; $customerId = $event['links']['customer']; // 创建订阅(金额单位为便士,示例为10英镑) $subscription = $client->subscriptions()->create([ 'params' => [ 'amount' => '1000', 'currency' => 'GBP', 'interval' => 'monthly', 'links' => [ 'mandate' => $mandateId, 'customer' => $customerId ], 'name' => '月度会员订阅' ] ]); } http_response_code(200); exit('OK');
方案二:在授权完成的回调页面创建订阅
客户完成授权后会跳转到你设置的redirect_uri(即http://localhost/success),你可以在这个页面查询Billing Request的状态,获取已创建的mandate,然后立即创建订阅。
步骤:
- 在创建Billing Request时,将其ID安全存储到session中(或通过其他方式传递到回调页面)。
- 在回调页面中:
- 取出Billing Request ID。
- 调用API获取Billing Request详情,确认其状态为
completed。 - 从详情中提取
links->mandate(已创建的授权ID)。 - 调用订阅API创建订阅。
示例代码:
// success.php 页面代码 session_start(); $brId = $_SESSION['billing_request_id']; // 假设之前已存储该ID // 获取Billing Request详情 $billingRequest = $client->billingRequests()->get($brId); // 确认授权已完成后创建订阅 if ($billingRequest->status === 'completed') { $mandateId = $billingRequest->links->mandate; $customerId = $billingRequest->links->customer; $subscription = $client->subscriptions()->create([ 'params' => [ 'amount' => '1000', 'currency' => 'GBP', 'interval' => 'monthly', 'links' => [ 'mandate' => $mandateId, 'customer' => $customerId ], 'name' => '月度会员订阅' ] ]); // 这里可添加订阅成功后的提示或业务逻辑 }
注意事项
- 两种方案都要处理API调用的异常情况(如网络错误、参数非法),保证逻辑健壮性。
- Webhook方案需保证处理逻辑的幂等性,避免重复创建订阅(可通过事件ID去重)。
- 回调页面方案要确保session的安全性,防止ID被篡改。
内容的提问来源于stack exchange,提问作者MrCarrot
相关产品推荐
相关产品推荐

