Automate Invoice Generation for SaaS: Implementation & Integration

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
Automate Invoice Generation for SaaS: Implementation & Integration
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Typical scenario: A B2B SaaS product growing 20% monthly, but invoicing is still manual. Managers spend up to 15 minutes per invoice—copying data, pasting into Word, losing amounts, making mistakes in tax IDs. Clients complain about 2-3 day delays, accounting spends hours on reconciliation. Invoice automation reduces this process to 30 seconds—30x faster, saving up to $10,000 per year for a company with 500 monthly invoices. We implement the full cycle: from Stripe setup to custom PDF generation with S3 storage and 1C synchronization.

In a SaaS business with hundreds of clients and subscriptions in different currencies, manual invoicing becomes a bottleneck. Every error in details or taxes can cost thousands of dollars. We've seen projects where 15% of invoices had errors—after automation, that figure dropped to 0.5%. "Invoice automation saved us 40 hours per month and reduced late payments by 30%"—CFO of one client. Proper configuration of Stripe Invoicing and custom PDF generation not only speeds up the process but also builds client trust: invoices look professional and contain correct data.

Our team has implemented invoicing for 30+ SaaS projects, from startups to enterprise. We know all the pitfalls: from tax IDs to time zones. If you're facing growing invoice volumes, get a consultation with an engineer.

Why Invoice Automation Is Critical for SaaS

With each new client, the accounting workload increases. Errors in details, taxes, and currencies lead to payment delays and loss of trust. Automated invoicing eliminates human errors in invoice generation, speeds up issuance to seconds after subscription payment, supports multiple currencies (USD, EUR, RUB) and tax regimes (VAT, US sales tax), and generates custom-branded PDF invoices for each client. Integration with accounting automatically syncs data with 1C and other systems.

Problems We Solve

  1. Tax ambiguity — Stripe supports tax IDs (INN for RU, VAT for EU) but requires proper configuration. We set up automatic tax rate determination based on client country.
  2. Custom branding — Standard Stripe invoices rarely satisfy clients. We create custom PDF templates using @react-pdf/renderer, fully controlling design and field placement.
  3. Storage and delivery — PDF invoices must be accessible from the client portal and sent via email. We use S3 with pre-signed URLs and SendGrid for delivery.
  4. Accounting synchronization — via Stripe webhook or custom generation, we transfer data to 1C and other systems.

How to Ensure Tax Accuracy in Invoices

Tax rules differ by country and state. Stripe allows you to set tax rates globally, but for complex scenarios (e.g., EU Intra-community VAT), additional logic is required. We use the Stripe Tax API to automatically calculate taxes based on client address and product type. For custom PDFs, taxes are computed server-side using trusted libraries. Testing on real scenarios (Stripe sandbox) ensures every transaction passes without blocks.

How We Implemented Invoicing for a SaaS Startup

Client: US-based SaaS for freelancer management. Requirements: issue invoices in USD and EUR, with client logo, payment terms 15/30 days, and automatically save PDFs to S3. We chose a hybrid approach: subscriptions via Stripe Invoicing, PDF generation via React PDF with a custom component.

Example Stripe Customer Setup
// Customer configuration with invoice details
const customer = await stripe.customers.create({
  email: '[email protected]',
  name: 'Acme Corp',
  address: {
    line1: '1 Lenin St',
    city: 'Moscow',
    country: 'RU',
    postal_code: '101000',
  },
  tax_ids: [{
    type: 'ru_inn',
    value: '7727563778',
  }],
  metadata: { tenantId },
});

// Custom branding via Stripe Dashboard:
// Settings → Branding → Logo, colors, footer text
// Update billing details by client
export async function updateBillingDetails(
  tenantId: string,
  data: BillingDetailsInput
): Promise<void> {
  const subscription = await db.subscription.findUnique({
    where: { tenantId }
  });

  await stripe.customers.update(subscription!.stripeCustomerId, {
    name: data.companyName,
    email: data.billingEmail,
    address: {
      line1: data.address,
      city: data.city,
      country: data.country,
      postal_code: data.postalCode,
    },
  });

  // Tax ID (INN for RU, VAT for EU)
  if (data.taxId) {
    // First delete old tax IDs
    const existingCustomer = await stripe.customers.retrieve(
      subscription!.stripeCustomerId,
      { expand: ['tax_ids'] }
    ) as Stripe.Customer;

    for (const taxId of (existingCustomer.tax_ids as Stripe.ApiList<Stripe.TaxId>).data) {
      await stripe.customers.deleteTaxId(subscription!.stripeCustomerId, taxId.id);
    }

    // Add new
    await stripe.customers.createTaxId(subscription!.stripeCustomerId, {
      type: data.taxIdType as Stripe.TaxIdCreateParams.Type,
      value: data.taxId,
    });
  }
}

PDF generation via React PDF with S3 caching: the first request generates and stores, subsequent requests serve the cached file. This reduces load and speeds up delivery.

// npm install @react-pdf/renderer
import { pdf } from '@react-pdf/renderer';
import { InvoicePDF } from '@/components/pdf/InvoicePDF';

export async function generateInvoicePDF(invoiceId: string): Promise<Buffer> {
  const invoice = await db.invoice.findUnique({
    where: { id: invoiceId },
    include: {
      tenant: { include: { branding: true } },
      lineItems: true,
    }
  });

  const pdfStream = await pdf(
    <InvoicePDF invoice={invoice!} />
  ).toBuffer();

  return pdfStream;
}

// Save to S3 and return URL
export async function getInvoicePdfUrl(invoiceId: string): Promise<string> {
  const key = `invoices/${invoiceId}.pdf`;

  // Check if already exists
  try {
    await s3.headObject({ Bucket: process.env.AWS_BUCKET!, Key: key }).promise();
    return `https://${process.env.AWS_BUCKET}.s3.amazonaws.com/${key}`;
  } catch {
    // Not found — generate
  }

  const pdfBuffer = await generateInvoicePDF(invoiceId);
  await s3.putObject({
    Bucket: process.env.AWS_BUCKET!,
    Key: key,
    Body: pdfBuffer,
    ContentType: 'application/pdf',
    ContentDisposition: `attachment; filename="invoice-${invoiceId}.pdf"`,
  }).promise();

  return `https://${process.env.AWS_BUCKET}.s3.amazonaws.com/${key}`;
}

The invoice component is detailed: a table with description, quantity, price, total; "From" and "To" blocks; payment status. All data comes from the database, ensuring accuracy.

// components/pdf/InvoicePDF.tsx
import {
  Document, Page, Text, View, Image, StyleSheet
} from '@react-pdf/renderer';

const styles = StyleSheet.create({
  page: { padding: 40, fontSize: 11, fontFamily: 'Helvetica' },
  header: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 40 },
  title: { fontSize: 24, fontWeight: 'bold' },
  table: { marginTop: 20 },
  tableRow: { flexDirection: 'row', borderBottom: '1px solid #eee', padding: '8px 0' },
  tableHeader: { backgroundColor: '#f5f5f5', fontWeight: 'bold' },
});

export function InvoicePDF({ invoice }: { invoice: Invoice }) {
  return (
    <Document>
      <Page size="A4" style={styles.page}>
        <View style={styles.header}>
          <View>
            {invoice.tenant.branding?.logoUrl && (
              <Image src={invoice.tenant.branding.logoUrl} style={{ height: 40 }} />
            )}
            <Text style={styles.title}>INVOICE</Text>
            <Text>No. {invoice.number}</Text>
            <Text>Date: {invoice.createdAt.toLocaleDateString('en-US')}</Text>
          </View>
          <View style={{ alignItems: 'flex-end' }}>
            <Text style={{ fontSize: 18, color: '#6366f1' }}>
              {formatCurrency(invoice.total, invoice.currency)}
            </Text>
            <Text style={{ color: invoice.status === 'paid' ? '#22c55e' : '#f59e0b' }}>
              {invoice.status === 'paid' ? 'Paid' : 'Pending'}
            </Text>
          </View>
        </View>

        {/* Company details */}
        <View style={{ flexDirection: 'row', gap: 40, marginBottom: 30 }}>
          <View>
            <Text style={{ fontWeight: 'bold', marginBottom: 4 }}>From:</Text>
            <Text>{process.env.COMPANY_NAME}</Text>
            <Text>Tax ID: {process.env.COMPANY_INN}</Text>
          </View>
          <View>
            <Text style={{ fontWeight: 'bold', marginBottom: 4 }}>To:</Text>
            <Text>{invoice.customerName}</Text>
            {invoice.taxId && <Text>Tax ID: {invoice.taxId}</Text>}
          </View>
        </View>

        {/* Invoice lines */}
        <View style={styles.table}>
          <View style={[styles.tableRow, styles.tableHeader]}>
            <Text style={{ flex: 3 }}>Description</Text>
            <Text style={{ flex: 1, textAlign: 'right' }}>Quantity</Text>
            <Text style={{ flex: 1, textAlign: 'right' }}>Unit Price</Text>
            <Text style={{ flex: 1, textAlign: 'right' }}>Amount</Text>
          </View>
          {invoice.lineItems.map((item) => (
            <View key={item.id} style={styles.tableRow}>
              <Text style={{ flex: 3 }}>{item.description}</Text>
              <Text style={{ flex: 1, textAlign: 'right' }}>{item.quantity}</Text>
              <Text style={{ flex: 1, textAlign: 'right' }}>
                {formatCurrency(item.unitAmount, invoice.currency)}
              </Text>
              <Text style={{ flex: 1, textAlign: 'right' }}>
                {formatCurrency(item.amount, invoice.currency)}
              </Text>
            </View>
          ))}
        </View>

        {/* Total */}
        <View style={{ alignItems: 'flex-end', marginTop: 20 }}>
          <Text style={{ fontSize: 14, fontWeight: 'bold' }}>
            Total: {formatCurrency(invoice.total, invoice.currency)}
          </Text>
        </View>
      </Page>
    </Document>
  );
}

How Webhook Synchronization Works

The invoice.finalized webhook sends data about a new invoice. We upsert the record in our database and store the PDF URL from Stripe. For custom invoices, we generate the PDF and upload to S3. This gives the client real-time visibility of invoices.

case 'invoice.finalized': {
  const stripeInvoice = event.data.object as Stripe.Invoice;

  await db.invoice.upsert({
    where: { stripeInvoiceId: stripeInvoice.id },
    create: {
      stripeInvoiceId: stripeInvoice.id,
      tenantId: stripeInvoice.metadata.tenantId,
      number: stripeInvoice.number!,
      total: stripeInvoice.amount_due,
      currency: stripeInvoice.currency,
      status: 'open',
      pdfUrl: stripeInvoice.invoice_pdf,
      periodStart: new Date(stripeInvoice.period_start * 1000),
      periodEnd: new Date(stripeInvoice.period_end * 1000),
    },
    update: { status: 'open' }
  });
  break;
}

What's Included

Stage Details
Analysis Audit current process, agree on invoice format, tax requirements, currencies
Design Architecture: choose between Stripe Invoicing and custom generation, webhook schema, data model
Implementation Stripe setup, PDF template development, webhook handlers, S3 & email integration
Testing Verify all scenarios: create, update, cancel, refund, different currencies
Documentation API spec, accounting instructions, branding guide
Deploy Production deployment, error monitoring, alert setup
Support 1-month warranty (free bug fixes), optional team training

Common Issues and Solutions

Issue Consequence Solution
Incorrect tax ID Tax not calculated Validate format via Stripe validation
No PDF caching High load Store in S3 with pre-signed URLs
Ignoring idempotency Duplicate invoices Use idempotency_key
Not accounting for time zones Date mismatches Set client time zone

Estimated Timelines

  • Basic Stripe Invoicing configuration — 3 to 5 days (without custom PDFs).
  • Custom PDF generation with S3 and webhooks — 7 to 10 days.
  • Full cycle with 1C integration — 10 to 14 days.

Cost is calculated individually after an audit—contact us for a consultation.

Our experience: 10+ years in production, 40+ projects. We guarantee correct setup and support. Contact us to discuss your project and get a free consultation.

What Does SaaS Platform Development Involve? Multi-Tenancy, Billing, and Beyond

We know this pain by heart. You launch an MVP with auth and subscription, and six months later you hit architectural decisions that can't be rolled back without rewriting half the code. Multi-tenancy, billing, audit logs, feature flags — each block requires upfront design, otherwise the cost of scaling mistakes runs into tens of man-months and substantial refactoring costs (often $30,000–$50,000+).

Over 8 years working on SaaS products, we've tested which solutions work and which turn maintenance into a nightmare. Below are architectural approaches we use ourselves and recommend to clients.

How we build multi-tenancy: isolation without overhead

The first decision is the data separation scheme. Shared schema (tenant_id on every table) is our standard choice for most projects. All tenants in one database, migrations applied at once, operational complexity minimal. In Laravel we implement it via Global Scope:

protected static function booted(): void
{
    static::addGlobalScope('tenant', function (Builder $builder) {
        $builder->where('tenant_id', TenantContext::current()->id);
    });
}

The global scope is only the first line of defense. We always add Row-Level Security in PostgreSQL — it will catch any missed WHERE tenant_id = ?:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
    USING (tenant_id = current_setting('app.tenant_id')::uuid);

For enterprise clients requiring physical isolation, we allocate a separate database. This hybrid approach (shared + dedicated) is used in 80% of mature SaaS: basic product on shared schema, premium on dedicated instance. We implement it from the first sprint to avoid rewriting logic later. Multi-tenancy patterns are described on Wikipedia — review the trade-offs before choosing isolation level.

Why Is Billing the Most Underestimated Block?

Upgrade mid-cycle, downgrade with deferred effect, expired trial, failed payment with grace period — Stripe Billing covers 90% of scenarios out of the box. We always process webhooks (customer.subscription.updated, invoice.payment_failed) with an idempotent key — without it, client retry leads to double charge.

For CIS markets — YooKassa or Tinkoff recurring. Their APIs are less convenient but cover 54-FZ requirements.

Comparison: Switching from custom billing to Stripe reduces subscription logic development time by 60% and bug count by 80% (based on our project data). That translates to $15,000–$25,000 savings on a typical SaaS MVP.

Onboarding: how not to lose the user before aha-moment

Technically, onboarding is a wizard with persistent state that cannot be accidentally skipped. Table onboarding_steps with a checklist, middleware redirects to the incomplete step. After completion — a flag in user settings, middleware disabled.

Critical nuance: show real product progress, not abstract steps. "Create your first report" instead of "Complete step 3 of 5." We use drip campaigns via Customer.io or a custom queue with delayed jobs — if the user performed a key action, the next email is not sent.

How to Implement Feature Flags and Access Control?

SaaS with plans requires granular control. Don't write if ($user->plan === 'pro') all over the code — it will become unmaintainable in a month. Instead:

  • Backend: Gate + Policy with checks via features table linked to plans.
  • Frontend: context with flags loaded at app initialization.
  • Open-source tools: Unleash or Growthbook — UI for A/B testing and rollout.

Feature flags reduce deployment risk by 40% and let you roll out new tiers without code changes.

How to Protect API from Aggressive Clients?

Rate limiting is a must for public API. One client can bring down all others. In Laravel we use Redis with sliding window counter:

Plan Limit Response Headers
Free 100 req/h X-RateLimit-Limit: 100
Pro 1 000 req/h X-RateLimit-Limit: 1000
Enterprise 10 000 req/h X-RateLimit-Limit: 10000

Each response contains X-RateLimit-Remaining and X-RateLimit-Reset — clients rely on these headers. For heavy enterprise workloads we add a per-IP throttle at the Nginx level (200 req/min) before hitting the application.

Audit Logs and Monitoring: What, Who, and When?

Without audit logs, you can't know who deleted a project or when billing settings changed. Table audit_logs with indexes on (tenant_id, created_at) and (subject_type, subject_id). In Laravel — Observers on key models.

Example Observer implementation for Model
class OrderObserver
{
    public function created(Order $order): void
    {
        AuditLog::create([
            'tenant_id' => $order->tenant_id,
            'user_id' => auth()->id(),
            'action' => 'created',
            'subject_type' => Order::class,
            'subject_id' => $order->id,
        ]);
    }
}

Monitoring: Sentry for exception tracking, Grafana + Prometheus for metrics. Alerts on error rate > 5% and response time p95 > 2s. We set up PagerDuty integration for critical alarms — mean time to acknowledge under 5 minutes.

Our Team's Experience and Guarantees

Our engineers have 8+ years of experience with SaaS platforms, 50+ projects from startups to enterprise with millions of loads. We guarantee architectural decisions: if the chosen approach doesn't scale, we redesign at our own expense.

Deliverables and Guarantees

  • Architecture documentation: diagrams, ERD, sequence diagrams.
  • CI/CD setup (GitHub Actions / GitLab CI).
  • Access to repository, staging, and production.
  • Team training: 2–3 sessions on code review and runbook.
  • Post-launch support for 1 month.
  • Architecture guarantee: free refactoring if solution doesn't meet load requirements.

Work Process

  1. Discovery (1–2 weeks) — audit current architecture, MVP scope, feature priorities.
  2. Design (1 week) — stack selection, multi-tenancy scheme, billing plan.
  3. Development (4–12 weeks) — 2-week sprints, demo after each.
  4. Testing (1 week) — load tests under target load, security audit.
  5. Deployment and training (1 week) — rollout, monitoring setup, documentation handover.

Timeline Estimates

Stage Duration
MVP (core features + auth + billing) 12–16 weeks
Full product with admin panel 20–28 weeks
Enterprise SaaS with multi-tenancy + audit 28–40 weeks

Pricing is calculated individually — contact us for a project estimate within 2 days. Order turnkey development: from design to deployment with architecture guarantee. Get a consultation on your product architecture — first hour free.