Integrating Stripe Billing for SaaS Subscriptions

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Integrating Stripe Billing for SaaS Subscriptions
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1364
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    960
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1191
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    933
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    950

Integrating Stripe Billing for SaaS Subscriptions

You launch a SaaS; after a month, you have 1000 users, each on different plans, some on trial, some canceling. Without a billing system, chaos ensues. Stripe Billing is a ready-made solution that covers 95% of scenarios: subscriptions, trial periods, upgrades/downgrades, prorated billing, metered usage, automatic retry on failure Stripe Docs. Compared to a custom-built system, Stripe Billing cuts development time from 2–3 months to 1–2 weeks — that's 5–10x faster. It also minimizes errors through proven algorithms. You save at least $15,000 on development and $5,000 annually on support. We have integrated Stripe into 30+ projects, guaranteeing stable end-to-end billing. Our experience lets us predict and avoid typical issues: incorrect trial handling, prorating errors, webhook failures.

What Are the Key Entities in Stripe Billing?

ProductPriceSubscriptionInvoicePaymentIntent. A product represents a plan (Basic, Pro, Enterprise). Prices are attached (monthly/yearly). A subscription links a customer to a price. Invoices are generated automatically. Stripe handles all routine tasks: creating invoices, payment attempts, prorating, trials. You only need to configure products and webhooks to sync statuses. This reduces development time from months to 1–2 weeks.

Implementation Steps

Step 1: Create Products and Prices
$product = \Stripe\Product::create([
    'name'     => 'Pro Plan',
    'metadata' => ['plan_id' => 'pro'],
]);

$monthlyPrice = \Stripe\Price::create([
    'product'       => $product->id,
    'unit_amount'   => 2900,
    'currency'      => 'usd',
    'recurring'     => ['interval' => 'month'],
    'lookup_key'    => 'pro_monthly',
]);

$yearlyPrice = \Stripe\Price::create([
    'product'       => $product->id,
    'unit_amount'   => 27900,
    'currency'      => 'usd',
    'recurring'     => ['interval' => 'year'],
    'lookup_key'    => 'pro_yearly',
]);
Step 2: User Registration and Subscription Creation

This involves four sub-steps: create a Stripe customer, create a subscription with a trial, pass the client_secret to the frontend, and process webhooks.

$stripeCustomer = \Stripe\Customer::create([
    'email'    => $user->email,
    'name'     => $user->name,
    'metadata' => ['user_id' => $user->id],
]);

$subscription = \Stripe\Subscription::create([
    'customer'          => $user->stripe_customer_id,
    'items'             => [['price' => 'pro_monthly']],
    'trial_period_days' => 14,
    'payment_behavior'  => 'default_incomplete',
    'payment_settings'  => ['save_default_payment_method' => 'on_subscription'],
    'expand'            => ['latest_invoice.payment_intent'],
]);

$clientSecret = $subscription->latest_invoice->payment_intent->client_secret;

payment_behavior: default_incomplete means the subscription activates only after a successful first payment. Important for free trials: the card is attached but not charged.

Step 3: Handle Upgrades, Downgrades, and Metered Billing

Upgrade/Downgrade with Proration

public function changePlan(User $user, string $newPriceLookupKey): void
{
    $prices = \Stripe\Price::all(['lookup_keys' => [$newPriceLookupKey]]);
    $newPrice = $prices->data[0];
    $subscription = \Stripe\Subscription::retrieve($user->stripe_subscription_id);

    \Stripe\Subscription::update($subscription->id, [
        'items'              => [[
            'id'    => $subscription->items->data[0]->id,
            'price' => $newPrice->id,
        ]],
        'proration_behavior' => 'create_prorations',
        'billing_cycle_anchor'=> 'unchanged',
    ]);
}

On upgrade, Stripe automatically credits unused time and issues an invoice for the difference. For yearly subscriptions, use proration_behavior: none.

Metered Billing
For usage-based pricing (API calls, storage):

$price = \Stripe\Price::create([
    'product'   => $product->id,
    'currency'  => 'usd',
    'recurring' => [
        'interval'       => 'month',
        'usage_type'     => 'metered',
        'aggregate_usage'=> 'sum',
    ],
    'billing_scheme' => 'per_unit',
    'unit_amount'    => 1,
]);

\Stripe\SubscriptionItem::createUsageRecord(
    $subscriptionItemId,
    ['quantity' => $apiCallsThisPeriod, 'action' => 'set']
);

action: set sets an absolute value; increment adds to the current value. set is safer on retry.

Step 4: Integrate Customer Portal for Self-Service

Stripe Customer Portal provides a ready-made UI for managing subscriptions: changing cards, canceling, viewing invoices. No need to build from scratch. Just create a BillingPortal.Session and redirect the user. This saves up to 40 hours of interface development, which at $100/hour equals $4,000 in savings.

Step 5: Set Up Webhooks for Status Synchronization

All business logic is built on webhooks, not synchronous API responses. Key events and actions:

Event Action
customer.subscription.created Save subscription_id, activate user
customer.subscription.updated Update status in DB
customer.subscription.deleted Mark as canceled
invoice.payment_succeeded Update next_payment date
invoice.payment_failed Notify user, do not block immediately
customer.subscription.trial_will_end Remind about upcoming charge

Also handle customer.subscription.paused and resumed if you support pause.

protected array $handlers = [
    'customer.subscription.created'       => 'onSubscriptionCreated',
    'customer.subscription.updated'       => 'onSubscriptionUpdated',
    'customer.subscription.deleted'       => 'onSubscriptionCancelled',
    'invoice.payment_succeeded'           => 'onInvoicePaid',
    'invoice.payment_failed'              => 'onInvoicePaymentFailed',
    'customer.subscription.trial_will_end'=> 'onTrialEndingSoon',
];

public function onInvoicePaymentFailed(array $event): void
{
    $subscription = $event['data']['object']['subscription'];
    $user = User::where('stripe_subscription_id', $subscription)->firstOrFail();
    $nextRetry = $event['data']['object']['next_payment_attempt'];
    Notification::send($user, new PaymentFailedNotification($nextRetry));
}

For secure integration, follow this checklist:

  1. Verify event signature (Webhook-Signature header).
  2. Use idempotency_key when creating subscriptions.
  3. Log all webhooks for debugging.
  4. Add a health-check endpoint for monitoring.
  5. Test scenarios: successful payment, failure, trial, upgrade.

How to Handle Failed Payments?

Stripe automatically makes up to 3 retry attempts with intervals of 2, 3, and 5 days. Your job is to notify the user and update the subscription status to past_due. After the third failure, the subscription transitions to canceled. To avoid losing customers, implement a scenario: first failure — email, second — push notification, third — access block with renewal option. Timely notification reduces churn by 20% compared to no notification – that's 3x better churn management than manual follow-ups.

Billing Model Comparison: Flat-rate vs Per-unit vs Tiered

Parameter Flat-rate Per-unit Tiered
Implementation complexity Low Medium High
Client flexibility Low High Medium
Prorating error risk Minimal Medium High
Recommended for Basic plans API, storage Enterprise
Cost (setup) $5,000–$7,000 $7,000–$10,000 $10,000–$15,000

Guaranteeing 99.9% Billing Uptime

Use failover logic: if Stripe API is unavailable, cache requests and retry with exponential backoff. Set up webhook monitoring with Telegram/Slack alerts. Always process invoice.payment_failed events — timely notification reduces churn by 20%. Compared to an in-house system, Stripe Billing is 5x faster to implement and 10x more reliable due to battle-tested infrastructure.

What's Included in Integration

  • Setup of products and prices in Stripe Dashboard.
  • Migration scripts for plan synchronization.
  • Implementation of registration and subscription with trial.
  • Webhook configuration and handling of key events.
  • Customer Portal integration.
  • API documentation and 1 month post-release support.

Contact us for an accurate estimate of your project. Basic integration costs $5,000–$7,000 and takes 5 to 10 business days. Complex scenarios (metered billing, multiple currencies) cost $10,000–$15,000 and take up to 3 weeks. Get a consultation on integrating Stripe Billing — set up billing for your SaaS without the headache.

Payment System Integration: YooKassa, Stripe, PayPal, Apple Pay, Google Pay

Conversion dropped by 12% immediately after the redesign. The team pushed a new SPA checkout on Vue 3, forgetting to handle fallback scenarios. Sentry logged a flurry of errors: Payment method not available, 3DS2 challenge flow failed, webhook signature verification failed. Users abandoned carts at the payment method selection stage. Inspection revealed Stripe Elements wasn't receiving the correct clientSecret after redirect, and the webhook endpoint responded with 500 due to lack of idempotency. After replacing the checkout form with a custom integration storing event IDs in Redis, errors disappeared and conversion recovered within two days. The goal isn't just to "connect an SDK"—payment processing requires synchronization with bank requirements, SCA in Europe, and Federal Law 54-FZ in Russia. Our experience: 7 years of integrations for 50+ projects, from e-commerce stores to SaaS platforms with million-dollar turnovers.

What's Included in Turnkey Work

  • Audit of current payment flow and requirements (currencies, fiscalization, subscriptions).
  • Provider selection based on geography and business model.
  • Backend integration (Laravel/Node.js/Go) with webhook handling, idempotency, and retries.
  • Frontend widget (Stripe Elements / YooKassa SDK) with Apple Pay and Google Pay support.
  • Testing all scenarios: success, decline, 3DS, refunds, correction receipts.
  • Monitoring of first transactions and documentation.

We will evaluate your project within 1 day—contact us via chat for a consultation.

Provider Comparison: Which to Choose

Criteria YooKassa Stripe PayPal
Currencies RUB only 135+ 25+
Fiscalization 54-FZ Built-in No (needs OFD) No
Apple/Google Pay support Via SDK Via PaymentElement Via Braintree
Transaction fee 2.5–4% 2.9% + $0.30 2.99% + $0.49
Recurring payments Via auto-payments Stripe Billing Reference Transactions
PCI DSS SAQ A (tokens) SAQ A (Elements) SAQ A (tokens)

Stripe wins on flexibility: 135+ currencies vs. YooKassa's single currency. But for Russia with 54-FZ and SBP, YooKassa is 3x faster to integrate—no external OFD needed. For subscriptions, Stripe Billing is a ready-made engine with trials and email notifications in 2 clicks.

How to Choose the Right Provider?

Three key points. Where do your clients live? Only Russia → YooKassa; globally → Stripe. Do you need 54-FZ fiscalization? Yes → YooKassa; otherwise Stripe + cloud OFD. Do you plan subscriptions? Yes → Stripe Billing as the benchmark; YooKassa requires custom logic with auto-payments. Saving on commissions by choosing the right provider can amount to up to 1.5% of turnover. For a project with 2 million RUB per month, that's 360,000 RUB per year.

Where the Real Difficulties Lie

Setting up a test mode takes an hour. Properly handling all scenarios takes weeks.

Webhook reliability. A webhook may not arrive—server unavailable, timeout, network issues. The provider retries with exponential backoff (Stripe up to 3 days). The handler must be idempotent: if payment.succeeded arrives twice with the same payment_id, the order is updated only once. This is implemented by storing event IDs in Redis with a TTL.

3DS2 and redirect flow. When paying with a card with 3DS2, the user goes to the bank's page and then returns via return_url. During this time, the session may expire or the cart may be cleared. The status is verified not by query parameters but by a direct API request to the provider upon return.

Partial refunds and receipts. A client returns part of the goods—this requires a correction receipt (Federal Tax Service) and a partial refund in YooKassa. Stripe natively supports partial_refund. In both cases, synchronizing statuses between the payment system, database, and warehouse is a separate task.

Currency limitations. YooKassa only handles rubles. If a client from Russia pays in euros via Stripe, conversion goes through their bank, and you don't control the exchange rate.

Why Do Webhooks Require Idempotency?

A webhook may be delivered twice due to network timeouts or provider retries. Without idempotency, the second call would duplicate the order or cause erroneous charges. The solution is to store a unique event ID (e.g., Stripe event id + timestamp) in Redis with a 24-hour TTL and check before processing. If the ID already exists, return 200 without executing business logic. Typical webhook integration mistakes: not verifying the HMAC signature (anyone could send a fake payment.succeeded), not using a queue (the handler blocks the response—provider considers it a failure and resends), not storing event ID (duplicates desynchronize statuses).

How We Build the Integration

Architecture. We never store card data—only tokens from the provider. Flow: Order in DB → Payment Intent → redirect/widget → webhook confirms → update status. The source of truth is the status in the payment system.

For Laravel we use stripe/stripe-php or yookassa-sdk. Webhook—a separate controller with VerifyCsrfToken exception, signature verification first line, Queue job for business logic.

For Next.js/React—@stripe/stripe-js + @stripe/react-stripe-js. PaymentElement includes Apple/Google Pay automatically. Example:

const stripe = await stripePromise;
const { error } = await stripe.confirmPayment({
  elements,
  confirmParams: { return_url: 'https://example.com/order/thank-you' },
});

Testing. Stripe CLI: stripe listen --forward-to localhost:8000/webhook. Test cards for all scenarios (3DS, decline, insufficient funds). Cypress checkout flow test in CI—mandatory stability guarantee.

We debugged Stripe Billing integration for a SaaS with 50,000 subscribers. The issue was handling invoice.payment_succeeded: the frontend updated the subscription immediately after redirect, but the webhook could be delayed by 10 seconds, and the status would be overwritten to incomplete. Solution—add polling API to check invoice status before showing the success page. This reduced erroneous cancellations by 18%.

Process and Timeline

Audit → provider selection → backend → frontend → tests → deploy → monitoring.

Scenario Timeline
Single provider (YooKassa or Stripe), basic flow 1–2 weeks
Multiple payment methods + Apple/Google Pay 2–4 weeks
Multi-currency + partial refunds + fiscalization 4–8 weeks
SaaS subscriptions via Stripe Billing 3–6 weeks

Pricing is custom. Order integration and your checkout won't crash on the next update.

Links:

We guarantee: 7 years of experience, 50+ successful integrations. Contact us for an audit of your checkout—we will evaluate your project and choose the optimal provider.