Skip to main content

Razorpay Payment Gateway Integration with Flutter: A Beginner's Guide

So, you're building a fantastic Flutter app and need to integrate a secure and reliable payment gateway? Look no further! Razorpay is a popular choice for Indian businesses, offering a seamless payment experience. This guide will walk you through the process of integrating Razorpay with your Flutter application, step-by-step, using Dart. We'll cover everything from setting up your Razorpay account to handling successful and failed transactions.

1. Setting Up Your Razorpay Account and Generating API Keys

Before diving into the code, you'll need a Razorpay account. Head over to the Razorpay website and sign up for a free account. Once you're logged in, switch to "Live Mode" or "Test Mode" (for development). In the dashboard, navigate to "Settings" -> "API Keys" and generate your API Key ID and API Key Secret. Important: Keep these keys secure and don't commit them directly to your codebase! Use environment variables or secure storage.

Important Note: For testing purposes, use Test Mode API Keys. Live Mode requires you to complete the KYC process.

2. Adding the Razorpay Flutter Package

Next, we'll add the official Razorpay Flutter package to your Flutter project. Open your pubspec.yaml file and add the following dependency:

dependencies:
  razorpay_flutter: ^1.3.5 # Check for the latest version on pub.dev

Save the file, and then run flutter pub get in your terminal to download and install the package.

3. Implementing the Payment Flow in Flutter

Now, let's write the Dart code to initiate the Razorpay payment. Here's a basic example:

import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';

class PaymentScreen extends StatefulWidget {
  @override
  _PaymentScreenState createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  Razorpay _razorpay = Razorpay();

  @override
  void initState() {
    super.initState();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);
  }

  void _openCheckout() {
    var options = {
      'key': 'YOUR_RAZORPAY_KEY_ID', // Replace with your Key ID
      'amount': 10000, // Amount in paise (e.g., 10000 for ₹100)
      'name': 'My Awesome App',
      'description': 'Payment for your awesome product',
      'prefill': {
        'name': 'John Doe',
        'email': 'john.doe@example.com',
        'contact': '9876543210'
      },
      'theme': {
        'color': '#F37254'
      }
    };

    try {
      _razorpay.open(options);
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    // Do something when payment succeeds
    print("Payment Successful: ${response.paymentId}");
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Payment Successful!"),
          content: new Text("Payment ID: ${response.paymentId}"),
          actions: [
            new ElevatedButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );

  }

  void _handlePaymentError(PaymentFailureResponse response) {
    // Do something when payment fails
    print("Payment Failed: ${response.code} - ${response.message}");
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Payment Failed!"),
          content: new Text("Error Code: ${response.code}\nMessage: ${response.message}"),
          actions: [
            new ElevatedButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    // Do something when an external wallet is selected
    print("External Wallet Selected: ${response.walletName}");
  }

  @override
  void dispose() {
    super.dispose();
    _razorpay.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Razorpay Integration'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _openCheckout,
          child: Text('Pay Now'),
        ),
      ),
    );
  }
}

Explanation:

  • Replace YOUR_RAZORPAY_KEY_ID with your actual Razorpay Key ID.
  • The amount is specified in paise (100 paise = ₹1). So, 10000 represents ₹100.
  • The options map contains various payment parameters like amount, name, description, prefill information, and theme.
  • The _razorpay.open(options) method initiates the Razorpay checkout process.
  • Event listeners are attached to handle payment success (_handlePaymentSuccess), failure (_handlePaymentError), and external wallet selection (_handleExternalWallet).
  • Always dispose of the `_razorpay` instance in the `dispose()` method to prevent memory leaks.

4. Handling Payment Success and Failure

The _handlePaymentSuccess and _handlePaymentError methods are crucial for handling the payment outcome. In the success handler, you can update your app's state, provide confirmation to the user, and process the order. In the failure handler, you should display an error message to the user and allow them to retry the payment.

Important: Always verify the payment status with Razorpay's servers using their APIs to prevent fraud. Don't rely solely on the client-side response.

Conclusion

Integrating Razorpay with your Flutter app allows you to accept payments securely and efficiently. Remember to keep your API keys safe, handle payment success and failure gracefully, and always verify payment status on the server-side. This guide provides a solid foundation for building a robust payment solution in your Flutter application. Good luck!

Automated post via TechCognita Automation Framework

Comments

Popular posts from this blog

Stripe vs Razorpay: Which Is Better for Indian Devs?

In the booming Indian startup and freelancer economy , online payments are the fuel that keeps projects running. Two names dominate this space for developers building SaaS products , client dashboards , or mobile apps: Stripe and Razorpay . But which one is better for Indian developers in 2025? Let’s break it down based on features, ease of use, integration, pricing, and local support. 💳 1. Onboarding & KYC Stripe: Offers international-level onboarding. But Stripe India requires you to be a registered business (no individual freelancers allowed). Razorpay: Allows both individuals and companies to sign up. Faster KYC for Indian users. 🏆 Winner: Razorpay (more accessible for freelancers & students) 🧑‍💻 2. Developer Experience Stripe: World-class documentation, SDKs for every language ( Node.js , Python , Flutter , etc.), sandbox testing, CLI tools . Razorpay: Good documentation, JS SDK , mobile SDKs available, but slightly less matu...

Google Summer of Code (GSoC) 2026 – Your Complete Guide to Getting Started

🎯 Introduction If you’re a coder with ambition—whether you’re a student, a self-taught developer, or early in your career—then the Google Summer of Code (GSoC) offers a powerful launchpad. Since its inception in 2005, GSoC has enabled thousands of developers from around the globe to contribute to open-source software , work with real mentors, and build impressive portfolio projects. As we look ahead to GSoC 2026 , there’s no better time to prepare deliberately—with strategy, clarity, and precision. This blog will give you the full scope: what GSoC is, why you should participate, how to position yourself for success, and actionable steps to get ahead. 💡 What Is GSoC? At its core, GSoC is a global, remote program where open-source organizations partner with contributors to complete meaningful projects during the summer. Key highlights: You’ll collaborate with open-source organizations and real mentors. You’ll work on live codebases impacting real users. The entire prog...

Razorpay vs PayU vs Cashfree: A Payment Gateway Integration Showdown

Choosing the right payment gateway is crucial for any business operating online. It's the bridge between your customers and your bank account, so a smooth, secure, and reliable integration is paramount. In India, Razorpay , PayU , and Cashfree are three of the most popular options, each offering a suite of features and benefits. This article dives deep into comparing these three giants to help you decide which one best suits your specific business needs. Understanding Key Features and Pricing Before diving into a head-to-head comparison, let's outline some of the core features each payment gateway offers and their general pricing structures. Razorpay is known for its developer-friendly APIs and a wide range of integrations. PayU boasts a strong focus on security and fraud prevention , while Cashfree is often praised for its efficient payouts and bulk payment options . Pricing varies, but generally includes transaction fees, setup fees (sometimes waived), and pos...