Razorpay Payment Gateway Integration in Flutter with PHP Backend — Step-by-Step Guide

Integrating a payment gateway is one of the most crucial parts of any mobile application that handles transactions. In India, Razorpay is one of the most popular payment solutions because of its easy setup, fast transactions, and support for multiple payment methods.

razorpay_integration_pradeepthedeveloper


In this tutorial, we’ll walk you through integrating Razorpay in a Flutter app using a PHP backend. We’ll create orders in Razorpay via PHP, handle payments in Flutter, and ensure security by keeping sensitive keys on the backend.

Why Use PHP Backend for Razorpay Integration?

  • Security: Your Razorpay Key Secret is never exposed in the app.
  • Scalability: Easier to manage payment logic, refunds, and webhooks in one place.
  • Flexibility: Can connect to databases for order history and wallet balance updates.

Step 1: Setting Up a Razorpay Account

  • Go to Razorpay’s website and sign up.
  • Switch to Live Mode when ready for production.
  • Note down your Key ID and Key Secret from the Razorpay Dashboard.

Step 2: Install PHP SDK for Razorpay

  • We’ll use Composer to install the official Razorpay PHP SDK.
composer require razorpay/razorpay

Step 3: Create PHP API to Generate Razorpay Order

<?php
header('Content-Type: application/json');
require 'vendor/autoload.php';

use Razorpay\Api\Api;

$keyId = 'rzp_live_XXXX'; // Your Razorpay Key ID
$keySecret = 'YYYYYYYYYYYY'; // Your Razorpay Key Secret
$api = new Api($keyId, $keySecret);

// Get amount from Flutter request
$input = json_decode(file_get_contents("php://input"), true);
$amount = isset($input['amount']) ? intval($input['amount']) : 0;

if ($amount <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid amount']);
    exit;
}

try {
    $order = $api->order->create([
        'amount' => $amount * 100, // Convert to paise
        'currency' => 'INR',
        'receipt' => 'wallet_' . uniqid(),
        'payment_capture' => 1
    ]);
    echo json_encode($order);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

What this script does:

  • Accepts an amount from the Flutter app.
  • Creates a Razorpay order on the server.
  • Returns the order details to Flutter.

Step 4: Add Razorpay Dependency in Flutter

  • In your pubspec.yaml file:
dependencies:
  razorpay_flutter: ^1.3.4
  http: ^1.1.0
Run:
flutter pub get

Step 5: Flutter Code to Open Razorpay Checkout

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:razorpay_flutter/razorpay_flutter.dart';

class RazorpayPayment extends StatefulWidget {
  @override
  _RazorpayPaymentState createState() => _RazorpayPaymentState();
}

class _RazorpayPaymentState extends State<RazorpayPayment> {
  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);
  }

  Future<void> _createOrder(int amount) async {
    final response = await http.post(
      Uri.parse("https://yourdomain.com/create_order.php"),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode({"amount": amount}),
    );

    final orderData = jsonDecode(response.body);
    if (response.statusCode == 200 && orderData['id'] != null) {
      var options = {
        'key': 'rzp_live_XXXX',
        'amount': amount * 100,
        'name': 'Your App Name',
        'order_id': orderData['id'],
        'description': 'Wallet Recharge',
        'prefill': {'contact': '9999999999', 'email': 'test@example.com'}
      };
      _razorpay!.open(options);
    } else {
      print("Error creating order: ${orderData['error']}");
    }
  }

  void _handlePaymentSuccess(PaymentSuccessResponse response) {
    print("Payment Successful: ${response.paymentId}");
    // Call backend to verify payment & update wallet
  }

  void _handlePaymentError(PaymentFailureResponse response) {
    print("Payment Failed: ${response.message}");
  }

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Razorpay Payment")),
      body: Center(
        child: ElevatedButton(
          onPressed: () => _createOrder(100), // ₹100
          child: Text("Pay ₹100"),
        ),
      ),
    );
  }
}

Step 6: Verifying Payment (Recommended)

After successful payment, always verify on the backend by fetching the payment details from Razorpay API using paymentId. This ensures no one can fake a payment status.

Conclusion

You have now successfully integrated Razorpay payment gateway into your Flutter app with a secure PHP backend. This setup is ideal for eCommerce, wallet systems, subscription apps, and booking platforms.

Post a Comment

Previous Post Next Post