Skip to main content

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

Want to integrate a robust and reliable payment gateway into your Flutter app? Look no further than Razorpay! This comprehensive guide will walk you through the entire process, step-by-step, making it easy for beginners to start accepting payments securely in their Flutter applications. We'll cover everything from setting up your Razorpay account to writing the Dart code that handles the payment flow.

1. Setting Up Your Razorpay Account and Obtaining API Keys

Before diving into the code, you'll need a Razorpay account. Head over to the Razorpay website and sign up. You'll likely start in test mode, which is perfect for development. Once you're happy with your integration, you can apply to go live. After creating your account, navigate to the API Keys section within the Razorpay dashboard. Here, you'll find your Key ID and Key Secret. Treat these keys like passwords; never commit them directly to your codebase. Use environment variables or secure storage mechanisms instead!

Important Tip: Always start with the test keys and switch to live keys only when you're ready to accept real payments.

2. Adding the Razorpay Flutter Package to Your Project

Now, let's integrate the Razorpay Flutter package into your Flutter project. Open your pubspec.yaml file and add the following dependency:

dependencies:
  flutter:
    sdk: flutter
  razorpay_flutter: ^1.3.6 # Use the latest version

Save the file and run flutter pub get in your terminal to install the package. This command fetches the necessary libraries and dependencies for your project.

3. Implementing the Payment Flow in Dart

Here's a basic example of how to initiate a Razorpay payment in your Flutter app. This code snippet assumes you have a button that triggers the payment process.

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 paise = ₹100)
      'name': 'My Awesome App',
      'description': 'Payment for awesome features',
      'prefill': {
        'contact': '9876543210',
        'email': 'test@example.com'
      },
      'theme': {
        'color': '#F37254'
      }
    };

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

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    print("Payment Successful: ${response.paymentId}");
    // Handle successful payment (e.g., update database, show confirmation)
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    print("Payment Error: ${response.code} - ${response.message}");
    // Handle payment failure (e.g., show error message to the user)
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    print("External Wallet: ${response.walletName}");
    // Handle external wallet selection (optional)
  }

  @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 in paise (Indian currency). Multiply your desired amount by 100.
  • The prefill section allows you to pre-populate user information.
  • The theme section lets you customize the payment interface's color.
  • The _razorpay.on methods listen for payment success, error, and external wallet events.
  • Remember to 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 result. In _handlePaymentSuccess, you'll typically want to update your database, fulfill the order, and show a confirmation message to the user. In _handlePaymentError, you should display an appropriate error message to the user and allow them to retry the payment.

5. Going Live and Security Considerations

Before going live, thoroughly test your integration using the test keys. Once you're satisfied, apply for live access on the Razorpay dashboard. Remember to replace your test keys with your live keys. Security is paramount. Never store API keys directly in your code. Use environment variables or a secure key management system. Also, ensure that your server-side code validates the payment status before fulfilling any orders.

Conclusion

Integrating Razorpay into your Flutter app allows you to securely and efficiently accept payments from your users. By following these steps, you can create a seamless payment experience within your application. Remember to prioritize security, test thoroughly, and handle payment success and failure gracefully. 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...