如何在Laravel中为Stripe配置多账户转账及佣金收取
解决方案:Stripe分账实现平台佣金与商家收款
核心问题分析
你的代码存在两个关键错误:
- Charge金额不足:原代码只收取了商家的
clubPrice金额,导致账户中没有平台佣金ourPrice的资金,无法完成后续转账。 - 不必要的自转账:平台佣金会直接留在你的Stripe主账户中,不需要额外调用
Transfer转给自己的账户——Transfer是用于从主账户向商家连接账户转账的操作。
修正后的完整代码
class StripePayment { private ?Authenticatable $user; public function __construct( private readonly Stripe $stripe, private StripeClient $stripeClient, private readonly Charge $charge, private readonly Transfer $transfer ) { $this->user = auth()->user(); $this->stripe::setApiKey(env('STRIPE_SECRET')); // 移除重复实例化的StripeClient,依赖注入已提供实例 } public function charge(array $prices, string $paymentToken) { $stripeResponse = $this->createOrUpdateCustomer($paymentToken); // 计算总收款金额:商家费用 + 平台佣金 $totalAmount = ($prices['clubPrice'] + $prices['ourPrice']) * 100; // 先收取用户的全部款项到平台主账户 $payment = $this->charge::create([ 'amount' => $totalAmount, 'currency' => 'eur', 'customer' => $stripeResponse->id, 'description' => __('Reservation created') ]); // 将商家应得金额转至其Stripe连接账户 $clubTransfer = $this->transfer::create([ 'amount' => $prices['clubPrice'] * 100, 'currency' => 'eur', 'destination' => 'acct_你的商家测试连接账户ID', // 替换为实际测试账户ID 'transfer_group' => $payment->id, ]); // 平台佣金自动留在主账户,无需额外转账 // 若需将佣金提现至自己的银行账户,可调用Payout API(可选,Stripe默认自动结算) // $payout = $this->transfer::create([ // 'amount' => $prices['ourPrice'] * 100, // 'currency' => 'eur', // ]); return [ 'payment_status' => $payment->status, 'club_transfer_status' => $clubTransfer->status, 'our_commission' => $prices['ourPrice'] ]; } public function createOrUpdateCustomer(string $token) { if ($this->user->stripe_id) { $stripeResponse = $this->stripeClient->customers->update( $this->user->stripe_id, [ 'name' => $this->user->name, 'email' => $this->user->email, 'source' => $token, ] ); } else { $stripeResponse = $this->stripeClient->customers->create([ 'name' => $this->user->name, 'email' => $this->user->email, 'source' => $token, ]); $this->user->stripe_id = $stripeResponse->id; $this->user->save(); } return $stripeResponse; } }
关键注意事项
- 连接账户有效性:开发模式下,需在Stripe测试后台创建商家的连接账户,获取对应的
acct_xxxID,并确保账户已完成测试环境的激活流程(填写基本邮箱、地址等信息即可)。 - 测试支付方式:使用Stripe官方测试卡号(如
4242 4242 4242 4242)进行测试,过期日期填未来任意日期,CVC填任意3位数字。 - 金额单位:Stripe API使用分作为金额单位,确保所有金额都乘以100转换为整数。
内容的提问来源于stack exchange,提问作者Dani Murcia
相关产品推荐
相关产品推荐

