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

Stop Undervaluing Your Work: Why ₹3000 for a Website Is an Insult, Not a Deal

In the ever-growing world of freelancing and digital agencies , one challenge continues to plague developers, designers, and IT professionals alike — clients who treat our industry like a vegetable market. We recently experienced this firsthand at TechCognita . The Incident: From ₹10K to ₹3K? Seriously? A potential client reached out, asking for a static website with modern design, responsive layout , SEO optimization , and fast performance. We quoted them a fair price of ₹10,000 for a 4-5 page site built using React.js and Tailwind CSS — one-time cost. Their response? “Someone is doing it in ₹5,000…” We remained calm and explained the difference: Custom UI design Responsive performance Deployed on the client’s server SEO-friendly structure Long-term value They nodded along — until they dropped this line: “Another person will do it for ₹3,000.” Wait… what? From ₹10,000 to ₹3,000 — is this really a negotiation, or a...

Agentic AI: The Rise of Autonomous Digital Workers in 2025

In 2025, Artificial Intelligence (AI) is no longer just a tool—it’s a collaborator. The emergence of Agentic AI , capable of making autonomous decisions and actions, is transforming the way we work, build, and innovate. What is Agentic AI? Agentic AI refers to autonomous systems that can interpret goals, make decisions, learn from outcomes, and adapt to new environments—without the need for constant human supervision. Unlike traditional models, these agents are designed to reason, act, and iterate. Real-World Applications Customer Service: AI agents are managing conversations, resolving support tickets, and providing tailored solutions at scale. Healthcare: Digital agents assist in diagnostics, monitor patient health, and manage medical data intelligently. Finance: Autonomous systems handle trades, manage risk, and detect fraud in real-time. Education: Adaptive AI tutors create personalized learning ...