Integrating Razorpay with Flutter and using Provider state management



Integrating Razorpay with Flutter and using Provider state management is a simple process. By using Provider, we can manage the payment status and easily implement payment functionalities in our Flutter application.

To start, you will need to install the Razorpay Flutter plugin and the Provider package. You can do this by adding the following lines in your pubspec.yaml file:


dependencies:

  razorpay_flutter: <latest_version>

  provider: <latest_version>

Once you have installed these packages, you can start integrating Razorpay into your Flutter application.

First, create a new file named payment_provider.dart and import the following packages:

import 'package:flutter/foundation.dart';

import 'package:razorpay_flutter/razorpay_flutter.dart';

import 'package:provider/provider.dart';

Next, create a new class named PaymentProvider that extends ChangeNotifier:

class PaymentProvider extends ChangeNotifier {

  Razorpay _razorpay;

  String _paymentStatus = 'Waiting';

 

  String get paymentStatus => _paymentStatus;

 

  void setPaymentStatus(String value) {

    _paymentStatus = value;

    notifyListeners();

  }

 

  Future<void> initiatePayment({int amount, String currency}) async {

    _razorpay = Razorpay();

    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);

    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);

    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);

 

    var options = {

      'key': '<razorpay_key>',

      'amount': amount,

      'currency': currency,

      'name': 'MyApp',

      'description': 'Test payment',

      'prefill': {'contact': '', 'email': ''}

    };

 

    try {

      _razorpay.open(options);

    } catch (e) {

      print(e.toString());

    }

  }

 

  void _handlePaymentSuccess(PaymentSuccessResponse response) {

    setPaymentStatus('Success');

    _razorpay.clear();

  }

 

  void _handlePaymentError(PaymentFailureResponse response) {

    setPaymentStatus('Error');

    _razorpay.clear();

  }

 

  void _handleExternalWallet(ExternalWalletResponse response) {

    setPaymentStatus('External Wallet');

    _razorpay.clear();

  }

}

The PaymentProvider class has a paymentStatus property that returns the current status of the payment process. We are using notifyListeners() method to update the status whenever there is a change.

We are also defining the initiatePayment method, which is responsible for opening the Razorpay payment gateway. You need to replace the <razorpay_key> placeholder with your Razorpay key.

Finally, we are defining three methods to handle the different payment events: _handlePaymentSuccess, `_handlePaymentError, and _handleExternalWallet`. These methods set the payment status based on the response and clear the Razorpay instance.

Next, you can use the PaymentProvider in your main file. To do this, wrap your MaterialApp widget with a ChangeNotifierProvider:

void main() {

  runApp(

    ChangeNotifierProvider(

      create: (_) => PaymentProvider(),

      child: MyApp(),

    ),

  );

}

 

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      home: HomePage(),

    );

  }

}

Now, you can access the PaymentProvider instance anywhere in your app by using Provider.of<PaymentProvider>(context).

For example, in your HomePage widget, you can create a button to initiate the payment:

class HomePage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('Razorpay with Provider'),

      ),

      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,

          children: [

            Text('Payment status: ${Provider.of<PaymentProvider>(context).paymentStatus}'),

            RaisedButton(

              onPressed: () {

                Provider.of<PaymentProvider>(context, listen: false)

                    .initiatePayment(amount: 100, currency: 'INR');

              },

              child: Text('Initiate Payment'),

            ),

          ],

        ),

      ),

    );

  }

}

Here, we are using Provider.of<PaymentProvider>(context) to access the payment status and initiate the payment. The listen: false argument is used to prevent the widget from being rebuilt when the payment status changes.

And that's it! You have successfully integrated Razorpay with Flutter and used Provider state management.

Note: The code in this blog is for demonstration purposes only. You should add error handling and other necessary checks in a real-world application.

 







Post a Comment

0 Comments