← Back to Blog

The Developer's Guide to Integrating a Payment Gateway in Your SaaS Application

By WovLab Team | April 26, 2026 | 15 min read

Choosing the Right Payment Gateway for Your Indian SaaS (Stripe vs. Razorpay vs. PayU)

Embarking on the journey of understanding how to integrate payment gateway in saas application requires a critical first step: selecting the right payment gateway. For a SaaS operating in or targeting the Indian market, this decision profoundly impacts everything from transaction success rates to operational costs and developer effort. The Indian fintech landscape is dynamic, with global players like Stripe competing fiercely with homegrown champions like Razorpay and established entities like PayU. Each offers distinct advantages and disadvantages that must be weighed carefully against your SaaS's specific needs, user base, and future expansion plans.

Stripe is renowned globally for its developer-friendly APIs, extensive documentation, and robust infrastructure for recurring payments, making it a strong contender for SaaS applications with international ambitions or those prioritising a top-tier developer experience. However, its pricing for Indian domestic transactions might be slightly higher compared to local players, and while its local presence is growing, its primary focus remains global. Razorpay, on the other hand, has carved out a dominant niche in India. It offers highly competitive domestic transaction fees, an excellent suite of developer tools tailored for the Indian ecosystem (including UPI, Net Banking, and Wallet support), and superior local support. Its product offerings, like Payment Links, Subscriptions, and Payment Pages, are designed with the Indian merchant in mind, making it often the go-to choice for India-first SaaS. PayU (part of Prosus) is another well-established player in India, offering a comprehensive set of payment options. It boasts extensive fraud detection capabilities and high success rates, particularly for a wide array of domestic payment methods. While it's reliable, some developers report its API and documentation to be slightly less modern or intuitive compared to Stripe or Razorpay.

Key Insight: For Indian SaaS applications, the choice often boils down to a balance between global scalability (Stripe), local market optimisation and cost-effectiveness (Razorpay), and robust domestic payment coverage (PayU). Prioritise recurring billing features, developer SDKs, and transparent pricing structures.

Here's a quick comparison to aid your decision:

Feature Stripe Razorpay PayU
Developer Experience Excellent (API-first, comprehensive docs) Very Good (India-focused SDKs/docs) Good (Established, but less modern API)
Indian Domestic Fees ~2.0-2.2% + GST ~1.8-2.0% + GST ~2.0-2.3% + GST
International Payments Strong (Global coverage) Good (Supports major cards, PayPal) Moderate (Focus on India, some int'l)
Recurring Billing Advanced, highly customisable Robust, well-suited for India Available, but less flexible
Local Payment Methods Growing (UPI, Netbanking) Extensive (UPI, Netbanking, Wallets) Very Extensive (UPI, Netbanking, Wallets)
Onboarding/KYC Streamlined (digital-first) Streamlined (India-specific process) Traditional, can be slower
Support Global focus, email/chat Excellent local support (phone/email) Good local support

Pre-Integration Checklist: PCI DSS Compliance, SSL Certificates, and API Key Management

Before writing a single line of code for how to integrate payment gateway in saas application, a critical pre-integration checklist must be rigorously addressed. Neglecting these foundational elements can lead to significant security vulnerabilities, legal non-compliance, and ultimately, a loss of customer trust. We're talking about safeguarding sensitive financial data, which is paramount for any SaaS operating online.

First and foremost is PCI DSS Compliance (Payment Card Industry Data Security Standard). As a SaaS provider, you will likely handle sensitive customer payment information. PCI DSS is a set of security standards designed to ensure that all companies that process, store, or transmit credit card information maintain a secure environment. The key takeaway for most SaaS applications is to never store raw credit card numbers, CVVs, or full magnetic stripe data on your own servers. By leveraging your payment gateway's hosted fields or SDKs (like Stripe Elements or Razorpay Checkout), you effectively outsource the majority of your PCI DSS burden. This reduces your scope significantly, often qualifying you for simpler SAQ (Self-Assessment Questionnaire) levels like SAQ A or SAQ A-EP, rather than the more complex and costly SAQ D. However, even with outsourcing, you are still responsible for your own application's security and ensuring your integration points are secure.

Secondly, SSL Certificates are non-negotiable. All communication between your users' browsers, your SaaS application, and the payment gateway must be encrypted using HTTPS. An SSL/TLS certificate ensures that data transmitted between your web server and a browser remains private and secure. Major cloud providers like AWS, Google Cloud, and Azure offer free SSL certificates, and services like Let's Encrypt provide widely accepted, free certificates for domains. Always ensure your entire application runs on HTTPS, not just the checkout pages.

Key Insight: Security is not an afterthought; it's a foundational pillar of payment integration. Adhere to PCI DSS by outsourcing sensitive card data handling and ensure all communications are encrypted via SSL.

Finally, robust API Key Management is vital. Your payment gateway will provide you with API keys – typically a publishable key (safe for client-side use) and a secret key (must be kept server-side and highly confidential). The secret key grants full access to your payment gateway account for making charges, issuing refunds, managing subscriptions, and more. Never hardcode secret API keys directly into your application code, especially not in client-side code. Instead, use environment variables (`.env` files for development) and secure secret management services in production (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault). Implement strict access controls, rotate keys periodically, and monitor their usage for any anomalies. Additionally, for webhooks, always implement signature verification to ensure incoming webhook events genuinely originate from your payment gateway and haven't been tampered with or spoofed.

Step-by-Step: Server-Side Integration for Recurring Subscriptions with Node.js

Integrating recurring subscriptions is a core functionality for many SaaS applications. This section details how to integrate payment gateway in saas application on the server-side, focusing on Node.js and using a generic gateway API structure (similar to Stripe or Razorpay) to illustrate the key steps. The server-side handles the sensitive operations, ensuring security and compliance.

1. Initialize the Gateway SDK: First, install the gateway's official Node.js SDK and initialize it with your secret key. This usually goes at the top of your payment processing module.

const gateway = require('stripe')('sk_test_YOUR_SECRET_KEY'); // Example with Stripe

2. Create a Customer: When a new user signs up or decides to subscribe, create a customer object in your payment gateway. This object will represent your user and will hold their payment methods and subscriptions.

async function createGatewayCustomer(email, userId) { try { const customer = await gateway.customers.create({ email: email, metadata: { userId: userId } // Link to your internal user ID }); // Store customer.id in your database, linked to your user return customer.id; } catch (error) { console.error('Error creating gateway customer:', error); throw new Error('Failed to create payment customer.'); } }

3. Attach a Payment Method: The frontend (as discussed in the next section) will securely collect card details and tokenize them, sending a `paymentMethodId` (e.g., `pm_xxxxxxxxxxxx`) to your backend. Your backend then attaches this payment method to the customer. For subscriptions, it's crucial to set this as the customer's default payment method.

async function attachPaymentMethod(customerId, paymentMethodId) { try { await gateway.paymentMethods.attach(paymentMethodId, { customer: customerId }); // Set as default payment method await gateway.customers.update(customerId, { invoice_settings: { default_payment_method: paymentMethodId } }); return true; } catch (error) { console.error('Error attaching payment method:', error); throw new Error('Failed to attach payment method.'); } }

Key Insight: The server-side is the only place your secret API key should reside. All sensitive operations like customer creation and subscription management must originate from your secure backend.

4. Create a Subscription: With a customer and a default payment method, you can now subscribe them to a predefined plan (or product/price in some gateways). This operation initiates the recurring billing cycle.

async function createSubscription(customerId, priceId) { // priceId refers to your plan ID try { const subscription = await gateway.subscriptions.create({ customer: customerId, items: [{ price: priceId }], expand: ['latest_invoice.payment_intent'] // Important for immediate payment }); // Store subscription.id and status in your database return subscription; } catch (error) { console.error('Error creating subscription:', error); throw new Error('Failed to create subscription.'); } }

5. Handle Webhook Events: Subscriptions are asynchronous. Your gateway will send webhook events to your server for lifecycle changes (e.g., `invoice.paid`, `invoice.payment_failed`, `customer.subscription.deleted`). You must set up a dedicated endpoint to receive and process these events, ensuring idempotency and signature verification.

// Example using Express.js app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => { const sig = req.headers['stripe-signature']; // Or Razorpay signature let event; try { // Verify webhook signature (crucial for security) event = gateway.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET); } catch (err) { console.error(`Webhook Error: ${err.message}`); return res.status(400).send(`Webhook Error: ${err.message}`); } // Handle the event switch (event.type) { case 'customer.subscription.updated': case 'invoice.paid': // Update your database with the new subscription status, entitlement etc. console.log('Subscription updated or invoice paid:', event.data.object); break; case 'invoice.payment_failed': // Trigger dunning process, notify user console.log('Payment failed:', event.data.object); break; // ... other event types default: console.log(`Unhandled event type ${event.type}`); } res.json({ received: true }); });

This server-side setup forms the backbone of your SaaS billing system, securely managing sensitive payment flows and subscription logic.

Building a Secure and Frictionless Frontend Checkout Flow in React

The frontend is where user experience (UX) meets security in how to integrate payment gateway in saas application. A well-designed React checkout flow can significantly boost conversion rates while ensuring PCI DSS compliance. The core principle is to avoid ever touching sensitive card data on your own servers or directly in your frontend application. Instead, delegate this responsibility to the payment gateway's client-side SDK.

1. Initialise the Gateway SDK and Render Hosted Fields: For optimal security and PCI compliance, use the payment gateway's UI components (e.g., Stripe Elements, Razorpay Checkout). These are essentially iframes that securely collect card details directly from the user's browser to the payment gateway, bypassing your server entirely. This offloads the heavy lifting of PCI DSS compliance to the gateway. First, load the gateway's client-side library in your `index.html` or through your React app's entry point.

// public/index.html (for Stripe.js example) <script src="https://js.stripe.com/v3/"></script>

Then, in your React component, use `useEffect` to initialize the payment gateway client and mount the UI elements:

// MyCheckoutForm.js import React, { useState, useEffect, useRef } from 'react'; import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js'; // Example for Stripe Elements

function MyCheckoutForm({ customerId, priceId }) { const stripe = useStripe(); const elements = useElements(); const [error, setError] = useState(null); const [loading, setLoading] = useState(false);

const handleSubmit = async (event) => { event.preventDefault(); setLoading(true); setError(null);

if (!stripe || !elements) { // Stripe.js has not yet loaded. return; } // Create a PaymentMethod token from the CardElement const { error: cardError, paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card: elements.getElement(CardElement), });

if (cardError) { setError(cardError.message); setLoading(false); return; }

// Send the paymentMethod.id to your backend try { const response = await fetch('/api/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ customerId, paymentMethodId: paymentMethod.id, priceId }), }); const data = await response.json(); if (data.error) { setError(data.error); } else { // Handle success: redirect or update UI console.log('Subscription successful:', data); } } catch (apiError) { setError('An API error occurred.'); } finally { setLoading(false); } };

return ( <form onSubmit={handleSubmit}> <div> <CardElement /> {/* Stripe's secure iframe for card input */} </div> {error && <div style={{ color: 'red' }}>{error}</div>} <button type="submit" disabled={!stripe || loading}> {loading ? 'Processing...' : 'Subscribe'} </button> </form> ); }

Key Insight: Never handle raw card data on your frontend. Always use the payment gateway's official client-side SDK and UI components (e.g., Hosted Fields, Elements, Checkout) to securely collect and tokenize payment information, ensuring maximum PCI DSS compliance.

2. Tokenize Card Data and Send to Backend: Once the user enters their card details, the gateway's SDK tokenizes this information into a single-use token or `paymentMethodId`. This token is then sent to your backend (as shown in the `handleSubmit` function above). Your backend (Node.js in the previous section) uses this token to perform the actual customer and subscription creation without ever seeing the raw card details.

3. Handle Client-Side Errors and User Feedback: Provide immediate and clear feedback to the user. If the card number is invalid, show an error message. If the payment is processing, display a loading spinner and disable the submit button. After the backend responds, update the UI to reflect success or failure. For 3D Secure authentication (common in India), the gateway's SDK will often handle the redirection or modal, and your frontend will need to listen for the authentication result to complete the payment.

By following these steps, you create a secure, compliant, and user-friendly checkout experience that is crucial for retaining subscribers in your SaaS application.

Automating Invoicing, Handling Failed Payments, and Managing Dunning

Integrating a payment gateway in your SaaS application extends far beyond the initial transaction. A robust system for automating invoicing, effectively managing failed payments, and executing dunning strategies is essential for revenue retention and a smooth customer experience. Neglecting these post-transaction processes can lead to significant revenue leakage and customer churn.

Automating Invoicing: Modern payment gateways like Stripe and Razorpay come with powerful invoicing capabilities built directly into their subscription platforms. When a recurring charge is successful, the gateway automatically generates a professional, compliant invoice. This invoice can be customised with your branding, company details, and tax information. These invoices are typically sent directly to your customers via email and are also accessible through the gateway's dashboard. Your SaaS application should integrate with these invoice events via webhooks (e.g., `invoice.created`, `invoice.paid`) to link them to your user accounts, allow users to download past invoices from their dashboard, and ensure your internal accounting records are updated automatically. This reduces manual effort and ensures transparency for your subscribers.

Handling Failed Payments: Payment failures are an inevitable part of recurring billing. Common reasons include insufficient funds, expired cards, or fraud blocks. Your payment gateway will notify you of these failures via webhooks (`invoice.payment_failed`). It's crucial for your SaaS to:

  1. Log Failures: Keep a record of failed payments, including the reason code provided by the gateway.
  2. Notify Users: Immediately inform the customer about the failed payment, clearly stating the issue and providing a clear path to update their payment method.
  3. Update Subscription Status: Temporarily mark the subscription as `past_due` or `unpaid` in your system, potentially limiting access to certain features until the payment is resolved.

Key Insight: Proactive dunning management and transparent communication around failed payments are critical for revenue recovery. Every day a subscription remains unpaid increases the likelihood of churn.

Managing Dunning: Dunning is the process of reminding customers about overdue payments to recover lost revenue. Most leading payment gateways offer automated dunning features that are highly customisable:

  1. Automated Retries: Gateways typically attempt to retry failed charges several times over a period (e.g., 3 retries over 7 days), often using smart retry logic to attempt at optimal times.
  2. Email Sequences: Configure automated email sequences to notify customers about upcoming payment failures, failed payments, and impending subscription cancellations if payment isn't updated. These emails should be clear, concise, and include a direct link to a secure page where customers can update their payment information.
  3. Grace Periods: Define grace periods during which users still have full access to your SaaS even after a payment failure, giving them time to update their details before their service is interrupted.

Effective dunning can significantly improve your revenue retention rates. Beyond automation, consider offering incentives for users to update their payment methods promptly or providing options for pausing subscriptions instead of outright cancellation. Additionally, ensure your system can handle refunds and cancellations gracefully through the gateway's API, accurately reflecting these changes in your user's subscription status and billing history.

Finally, leverage your gateway's built-in analytics and reporting dashboards. These provide invaluable insights into your subscription metrics, payment success rates, churn, and dunning effectiveness, allowing you to continually optimise your billing processes.

Accelerate Your Go-to-Market: Partner with WovLab for Your FinTech Integration

The journey of how to integrate payment gateway in saas application is complex, demanding a blend of technical expertise, security acumen, and an understanding of regulatory compliance. From selecting the right gateway and ensuring PCI DSS compliance to building robust server-side logic and crafting a seamless frontend experience, each step is critical. For many SaaS businesses, especially startups or those with lean development teams, dedicating extensive internal resources to FinTech integration can divert focus from core product development, delay launch, and potentially introduce vulnerabilities.

This is where partnering with an experienced digital agency like WovLab (wovlab.com) becomes a strategic advantage. As an Indian agency with deep expertise in various digital domains including Payments and Development, WovLab is uniquely positioned to handle the intricacies of FinTech integration for your SaaS application. We understand the nuances of the Indian market, from specific payment methods like UPI to local compliance requirements, ensuring your integration is not only technically sound but also optimally aligned with your target audience.

WovLab can accelerate your go-to-market by:

Instead of navigating the complex world of payment gateways and FinTech regulations yourself, trust WovLab to deliver a robust, secure, and efficient integration. This allows your internal team to focus on what they do best: innovating and enhancing your core SaaS product. Partnering with WovLab means you benefit from our proven track record, accelerate your time to market, and ensure your payment processes are not just functional, but truly best-in-class.

Don't let payment integration be a bottleneck. Visit wovlab.com today to discuss how we can streamline your FinTech integration and propel your SaaS application's success.

Ready to Get Started?

Let WovLab handle it for you — zero hassle, expert execution.

💬 Chat on WhatsApp