Laravel Stripe:如何删除Stripe账户下所有银行卡(Sources)
在Laravel中删除Stripe账户下的所有银行卡(Sources)
Stripe没有提供直接“删除”Source的API,但可以通过**解除Source与Customer的关联(detach)**达到等效效果——解除后该银行卡将不再属于目标账户,无法用于后续支付操作。以下是具体实现步骤:
1. 获取目标账户下的所有银行卡Sources
调用Stripe API获取关联到指定Customer的所有银行卡类型Source:
use Stripe\Stripe; use Stripe\Customer; // 初始化Stripe API密钥 Stripe::setApiKey(config('services.stripe.secret')); // 替换为你的Stripe Customer ID $customer = Customer::retrieve('cus_xxxxxxx'); // 筛选出类型为银行卡的Source $cardSources = $customer->sources->all(['object' => 'card']);
2. 批量解除银行卡关联
遍历所有银行卡Source,调用detach()方法解除与Customer的绑定:
foreach ($cardSources->data as $source) { $source->detach(); }
扩展:使用Laravel Cashier的简化操作
如果项目中使用了Laravel Cashier,可以直接通过关联的User模型操作:
// 获取关联了Stripe账户的用户 $user = User::find(1); // 获取该用户的所有银行卡Sources $cardSources = $user->stripeCustomer->sources->all(['object' => 'card']); // 批量解除关联 foreach ($cardSources->data as $source) { $source->detach(); }
关于Stripe Payment Methods的说明
Stripe目前推荐使用Payment Methods替代旧的Sources体系,如果你用Payment Methods管理银行卡,解除关联的逻辑类似:
// 获取用户的所有银行卡Payment Methods $paymentMethods = $customer->payment_methods->list(['type' => 'card']); // 批量解除关联 foreach ($paymentMethods->data as $pm) { $pm->detach(); }
注:解除关联后的Source/Payment Method不会被Stripe彻底删除,但无法再关联到任何Customer,也无法用于原账户的支付,完全满足“删除银行卡”的业务需求。
内容的提问来源于stack exchange,提问作者Priyanka Patel
相关产品推荐
相关产品推荐

