单个用户多订阅Stripe批量扣费异常排查与方案优化咨询
Stripe订阅计费问题排查解答
背景说明
我们的平台通过记录订阅金额、每个用户唯一的Stripe订阅ID、订阅创建时间与到期时间来追踪用户订阅情况。用户可以在账户中添加多个订阅,新增时会即时扣费,后续遵循Stripe官方合并账单规则,在下个月1号通过Stripe账单合并批量扣费。
现有核心实现逻辑
订阅首次创建逻辑
if($this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY')) { return new Response($this->redirect($request->getUri())); } $user = $this->getUser(); if(!$user->isVerified()) { return new Response("must be verified"); } $token = $_POST['csrf']; $amount = $_POST['quantity']; $project_id = $_POST['project']; $tier_id = $_POST['tier']; //Create a new user subscription $userSub = new UserSubscription(); //Get all the repos for the project, tier and users. $projectRepo = $this->getDoctrine()->getRepository(Project::class); $tierRepo = $this->getDoctrine()->getRepository(ProjectTier::class); $userRepo = $this->getDoctrine()->getRepository(User::class); //Find the right project through the project ID $project = $projectRepo->findOneBy([ "id" => $project_id ]); //Find the right tier through the tier ID + the project $tier = $tierRepo->findOneBy([ "id" => $tier_id, 'project' => $project_id ]); //Find the project owner. $owner = $project->getProjectOwner(); //Get the owner stripe connect ID. $owner_id = $owner->getStripeConnectId(); if(!$this->isCsrfTokenValid('subscription-form', $token)) { return new Response("failure csrf"); } if(!$project) { return new Response("failure project"); } if(!$tier) { return new Response("failure tier"); } if($owner_id == null) { return new Response("failure owner"); } if(!is_numeric($amount)) { return new Response("amount invalid"); } if($amount < $tier->getTierPrice() || $amount < 1) { return new Response("amount too little"); } //Get the stripe customer ID from the user. $id = $user->getStripeCustomerId(); //Call the stripe API $stripe = new \Stripe\StripeClient($this->stripeSecretKey); //Get the user object in stripe. $customerData = $stripe->customers->retrieve($id); //If there is no payment source for the user, let them know. if($customerData->default_source == null) { return new Response("No card"); } //Retrieve all products -- there is only one in stripe with a $0/month payment. $allPrices = $stripe->prices->all(['active'=>true]); //Cycle all through them, really if there is one, it will only pick that one up and stuff it into the var. foreach($allPrices['data'] as $item) { if($item->type == "recurring" && $item->billing_scheme == "per_unit" && $item->unit_amount == "0") { $price = $item; break; } } //Get the first of next month. $firstofmonth = strtotime('first day of next month'); // //$first2months = strtotime('first day of +2 months'); //Grab the customer's payment source. $card = $stripe->customers->retrieveSource( $id, $customerData->default_source ); //If its not in the US, change the stripe percent fee. if($card->country != "US") { $stripePercent = 0.039; } else { //Otherwise regular percentage fee. $stripePercent = 0.029; } //30 cents per transaction $stripeCents = 30; //Platform fee. $platformfee = 0.025; $chargeAmount = number_format($amount,2,"",""); $subscription_expiration = $firstofmonth; //Calculate the full fees. $fees = number_format(($chargeAmount*$stripePercent+$stripeCents), -2,"", "")+number_format(($chargeAmount*$platformfee), -2,"", ""); //Create a payment intent for the intial payment. $pi = $stripe->paymentIntents->create([ 'amount' => $chargeAmount, 'currency' => 'usd', 'customer' => $user->getStripeCustomerId(), 'application_fee_amount' => $fees, 'transfer_data' => [ 'destination' => $owner_id ], 'payment_method' => $customerData->default_source ]); //Confirm the payment intent. $confirm = $stripe->paymentIntents->confirm( $pi->id, ['payment_method' => $customerData->default_source] ); //Get "all" the subscriptions from from the user -- its only 1 $subscriptions = $stripe->subscriptions->all(["customer" => $id]); //If only one, then proceed. if(count($subscriptions) == 1) { $subscription = $subscriptions['data'][0]; } else if(count($subscriptions) == 0) { //If not, create an entirely new one for the user. $subscription = $stripe->subscriptions->create([ 'customer' => $user->getStripeCustomerId(), 'items' => [ [ 'price' => $price->id //0/month subscription ], ], 'billing_cycle_anchor' => $firstofmonth ]); } //If the subscription is created and the payment is confirmed... if($confirm && $subscription) { //Create the new subscription with the user, the project, tier, the stripe subscription ID, when it expires, when it was created and how much. $userSub->setUser($user) ->setProject($project) ->setProjectTier($tier) ->setStripeSubscription($subscription->id) ->setExpiresOn($subscription_expiration) ->setCreatedOn(time()) ->setSubscriptionAmount($amount); //Propogate to DB. $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($userSub); $entityManager->flush(); //Notify the user on the front end $this->addFlash( 'success', 'You successfully subscribed to '.$project->getProjectName() ); //Take them to their feed. return new Response($this->generateUrl('feed')); }
webhook账单明细添加逻辑
case 'invoice.created': $stripe = new \Stripe\StripeClient($this->stripeSecretKey); $obj = $event->data->object; $invoice_id = $obj->id; $sub_id = $obj->subscription; $subRepo = $userSubscriptionRepository->findBy([ "StripeSubscription" => $sub_id ]); $user = $userSubscriptionRepository->findOneBy([ "StripeSubscription" => $sub_id ]); $customerID = $user->getUser()->getStripeCustomerId(); $firstofmonth = strtotime('first day of next month'); foreach($subRepo as $item) { if($item->getDisabled() == false && date("d/m/Y", $item->getExpiresOn()) == date("d/m/Y", $obj->created)) { $stripe->invoiceItems->create([ 'customer' => $customerID, 'amount' => $item->getSubscriptionAmount()."00", 'currency' => 'usd', 'description' => 'For project with ID: '.$item->getProject()->getId(), 'metadata' => [ 'sub_id' => $item->getId() ] ]); } } break;
该逻辑会在监听到invoice.created事件时获取Stripe事件对象,查询数据库中关联的用户订阅,为未禁用且到期时间与账单创建日期匹配的订阅添加账单明细。
问题解答
1. 账单明细被归入下一期的原因、现有实现合理性与优化方案
原因
- Stripe的
invoice.created事件在当期账单生成完成后触发,此时创建的账单明细默认归属到下一期账单,你现有代码未在创建invoice item时显式指定归属的账单ID,所以明细自动落到了下一期。 - 日期匹配逻辑存在时区风险:你用本地时区格式化时间做匹配,而Stripe的事件时间为UTC时区,时区差会导致日期匹配偏差,本该匹配当期的明细等到下一期账单生成时才匹配成功,进一步加重了归属错误。
现有实现合理性
整体设计符合Stripe合并账单的规范思路:通过0元基础订阅统一所有用户的计费锚点,用账单明细实现多订阅合并收费,大方向没有问题,仅细节处理存在漏洞。
优化方案
- 创建invoice item时新增
'invoice' => $invoice_id参数,强制明细归属到当前刚生成的账单中。 - 所有时间处理统一使用UTC时区,避免时区差异导致的匹配错误。
- 批量整理符合条件的订阅后再统一操作,或引入异步队列处理账单明细添加逻辑,降低Stripe接口调用超时风险。
2. 计费周期不符合设定的原因
- 时区不统一:你计算的
firstofmonth是服务器本地时区的下月1号,而Stripe后台使用UTC时间,若服务器为东八区,你计算的6月1号0点对应UTC的5月31号16点,Stripe识别到锚点已过,会自动将锚点顺延到下一个周期。 - 未显式配置锚点相关参数:创建订阅时你仅指定了
billing_cycle_anchor,未配置proration_behavior和payment_behavior参数,Stripe对0元订阅的短周期锚点有默认调整逻辑,当锚点距离订阅创建时间不足72小时时会自动延后到下一个自然月的对应日期,导致5月30号创建的订阅锚点被调整到了6月30号。
内容的提问来源于stack exchange,提问作者UXerUIer
相关产品推荐
相关产品推荐

