Skip to main content

Razorpay Payment Gateway Integration with Flutter and Dart

In today's mobile-first world, seamless payment integration is crucial for any successful e-commerce or service-based application. Flutter, with its cross-platform capabilities and rich UI toolkit, is a popular choice for building such apps. Razorpay, a leading payment gateway in India, offers a robust and developer-friendly solution for processing payments. This guide will walk you through integrating Razorpay with your Flutter application using Dart, ensuring a smooth and secure payment experience for your users.

Setting Up Your Razorpay Account and Keys

Before diving into the code, you'll need a Razorpay account. Head over to the Razorpay website and create a business account. Once your account is activated, navigate to the 'Settings' section and generate API keys. You'll have two keys: a Key ID and a Key Secret. Keep your Key Secret safe and never expose it in your client-side code. For development purposes, you can use the test keys provided by Razorpay.

To obtain the Razorpay API keys:

  1. Go to Razorpay's website and create an account.
  2. Log in to your Razorpay dashboard.
  3. Navigate to Settings → API Keys → Generate Key.
  4. Copy and store your Key ID and Key Secret securely.

Integrating the Razorpay Flutter Package

The easiest way to integrate Razorpay into your Flutter project is by using the official Razorpay Flutter package. Add the following dependency to your pubspec.yaml file:

dependencies:
      razorpay_flutter: ^1.4.2 
    

Run flutter pub get to fetch the package. After successful installation, import the package in your Dart file:

import 'package:razorpay_flutter/razorpay_flutter.dart';
    

Implementing the Payment Flow

Now, let's implement the payment flow. First, initialize the Razorpay instance in your Flutter widget's initState() method:

Razorpay _razorpay = Razorpay();

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

    @override
    void dispose() {
      super.dispose();
      _razorpay.clear(); // Removes all listeners
    }
    

Next, create a function to open the Razorpay checkout form. This function will take the order amount and other relevant details as input. Remember to replace YOUR_KEY_ID with your actual Razorpay Key ID.

void _openCheckout() async {
      var options = {
        'key': 'YOUR_KEY_ID',
        'amount': (amount * 100).toInt(), // Amount in paise (e.g., 100 INR = 10000 paise)
        'name': 'Your Company Name',
        'description': 'Payment for your product/service',
        'prefill': {
          'name': 'John Doe',
          'email': 'john.doe@example.com',
          'contact': '9876543210'
        },
        'theme': {
          'color': '#F37254'
        }
      };

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

Finally, implement the event handlers for successful payments, payment errors, and external wallets:

void _handlePaymentSuccess(PaymentSuccessResponse response) {
      // Payment successful
      print("Payment Successful: ${response.paymentId}");
      // Implement your logic to verify the payment and update your database
    }

    void _handlePaymentError(PaymentFailureResponse response) {
      // Payment failed
      print("Payment Error: ${response.code} - ${response.message}");
      // Handle the error gracefully, inform the user
    }

    void _handleExternalWallet(ExternalWalletResponse response) {
      // External wallet selected
      print("External Wallet: ${response.walletName}");
    }
    

Remember to handle the payment success and error scenarios appropriately. You should verify the payment status on your server-side to prevent fraudulent transactions. Razorpay provides APIs for this purpose.

Important Note: For production environments, always verify payment signatures on your backend to ensure security and prevent tampering.

Best Practices and Security Considerations

  • Secure your API Keys: Never expose your Key Secret in client-side code. Use environment variables or a secure configuration management system.
  • Verify Payment Signatures: Implement server-side verification of payment signatures to prevent fraudulent transactions.
  • Handle Errors Gracefully: Provide informative error messages to the user in case of payment failures.
  • Implement Retry Mechanisms: Consider implementing retry mechanisms for failed payments.
  • Follow PCI DSS Compliance: Ensure your application and infrastructure comply with PCI DSS standards for secure handling of payment data.

Conclusion

Integrating Razorpay with Flutter and Dart empowers you to create robust and secure payment solutions within your mobile applications. By following the steps outlined in this guide, you can seamlessly integrate Razorpay's payment gateway and provide a smooth payment experience for your users. Remember to prioritize security and follow best practices to ensure the integrity of your payment processing system. Always verify payment signatures on your backend and keep your API keys secure.

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...