Razorpay helps process online payments for online as well as offline businesses. Razor pay allows you to accept credit cards, debit cards, net banking, wallet, and UPI payments with the Mobile App integration. It uses a seamless integration, allowing the customer to pay on your app/website without being redirected away. In this article, we will take a look at the implementation of a payment gateway in our Flutter app.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Add Razorpay in pubspec.yaml file
Add Razorpay package to your flutter projects
Dart
// add package razorpay_flutter: ^1.3.4 |
Version may vary depending upon the time you read this article.
Step 3: Get API_key and API_secret for Razorpay
Browser the Razorpay site in Google or you can click on the link here. After clicking on this link you simply have to signup with your email and password and add some basic information such as your phone number.
Note: Here we are creating a testing credential for using Razor Pay.
Inside the setting screen, click on Create a new key option your key will be generated. We will be using key ID in our application to test Razor pay. The key-id will start with rzp_test.
To store Razor pay key and secret in the flutter app (Without sharing it on github,gitlabs). You can refer to this article: How to Add .env File in Flutter
Step 4: Create Razorpay Instance
To access all functions, and variables of Razorpay you have to create the instance for that.
Dart
// Instance of razor pay final Razorpay _razorpay = Razorpay(); |
Step 5: Attach Event listeners
To perform different functions on every event that happens in Razorpay you have to handle different scenarios.
1. Create functions to handle different events
Dart
void _handlePaymentSuccess(PaymentSuccessResponse response) { // Do something when payment succeeds } void _handlePaymentError(PaymentFailureResponse response) { // Do something when payment fails } void _handleExternalWallet(ExternalWalletResponse response) { // Do something when an external wallet is selected } |
2. Attach these functions to event listeners
In this, you have to attach the previous function to events listeners by this
Dart
initiateRazorPay() { // To handle different event with previous functions _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess); _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError); _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet); } |
Step 6: Create order in Razorpay
Either you can create an order id from the server using the Razorpay api secret and api key or you can create an order id in the app itself. This postman request you will be required to create an order id
curl -X POST https://api.razorpay.com/v1/orders -u [YOUR_KEY_ID]:[YOUR_KEY_SECRET] -H 'content-type:application/json' -d '{ "amount": 100, "currency": "INR", "receipt": "rcptid_11" //receipt id you want to give }'
To create order Id in the app itself:
Dart
import 'dart:convert' ; import 'package:flutter_dotenv/flutter_dotenv.dart' ; import 'package:http/http.dart' as http; class ApiServices { final razorPayKey = dotenv.get( "RAZOR_KEY" ); final razorPaySecret = dotenv.get( "RAZOR_SECRET" ); razorPayApi(num amount, String receiptId) async { var auth = 'Basic ' + base64Encode(utf8.encode( '$razorPayKey:$razorPaySecret' )); var headers = { 'content-type' : 'application/json' , 'Authorization' : auth}; var request = request.body = json.encode({ // Amount in smallest unit // like in paise for INR "amount" : amount * 100, // Currency "currency" : "INR" , // Receipt Id "receipt" : receiptId }); request.headers.addAll(headers); http.StreamedResponse response = await request.send(); print(response.statusCode); if (response.statusCode == 200) { return { "status" : "success" , "body" : jsonDecode(await response.stream.bytesToString()) }; } else { return { "status" : "fail" , "message" : (response.reasonPhrase)}; } } } |
Sample Response for this API
{ "id": "order_DBJOWzybf0sJbb", "entity": "order", "amount": 100, "amount_paid": 0, "amount_due": 100, "currency": "INR", "receipt": "rcptid_11", "status": "created", "attempts": 0, "notes": [], "created_at": 1566986570 }
Create order in Your flutter app:
How to call Create an order
Note: You can put your amount in place of 100. You have to add the amount in integer value only and razor pay takes the amount in a smaller unit for example in India it takes the amount in paise. For the USA it takes in cents.
Store this ID in a variable. It will be requiring in when you open checkout sessions.
Step 7: Add checkout sessions
Create order id by calling create order function and prepare the parameter to be sent to the Razorpay checkout page
Dart
// to get orderid by creating new order everytime // you try to open razorpay checkout page createOrder(amount: amount).then((orderId) { print(orderId); if (orderId.toString().isNotEmpty) { var options = { // Razorpay API Key 'key' : razorPayKey, // in the smallest // currency sub-unit. 'amount' : amount, 'name' : 'Company Name.' , // Generate order_id // using Orders API 'order_id' : orderId, // Order Description to be // shown in razor pay page 'description' : 'Description for order' , // in seconds 'timeout' : 60, 'prefill' : { 'contact' : '9123456789' , 'email' : 'flutterwings304@gmail.com' } // contact number and email id of user }; } else {} }); |
Step 8: Open Checkout Page
Now just open the checkout page and pay with different payment methods
Dart
_razorpay.open(options); |
Step 9: Store fields in the server
For a better user experience and data security kept these 3 fields in your database. This will be returned in the successful event function if the transaction is successfully made.
{ "razorpay_payment_id": "pay_29QQoUBi66xm2f", "razorpay_order_id": "order_9A33XWu170gUtm", "razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d" }
Step 10: Verify signature and payment
This step is necessary to verify the validity of the information returned to the Checkout form for successful payments.
generated_signature = hmac_sha256(order_id + "|" + razorpay_payment_id, secret); if (generated_signature == razorpay_signature) { payment is successful }
Output:
Github Source Code: Click here