Instamojo payment gateway integration in flutter

Md Sadab Wasim
Dec 20, 2018 · 6 min read

Integration of a payment gateway which doesn’t provide any plugin for flutter.

Photo by rawpixel on Unsplash

What is instamojo?

Instamojo provides free payment gateway in India. Trusted by 600000+ Indian Businesses, 100% Secure, No setup cost, No maintenance cost.

How to integrate instamojo in flutter app?

Instamojo doesn’t provide a plugin for flutter, so we have to integrate it using platform channel or any alternative method (if available).

Let’s think about the approach?

If we use platform channel for integration then we have to do the same work twice, once for Android and for Ios(We also need to understand basic java and swift for writing platform-specific code).

Let’s put on our Flutter cap and think about it, building apps in flutter is easy and fun, so integrating payment gateway should be easy, that’s why we are going to take another approach for instamojo integration.

Here comes the webview

We can use webview for taking payment without hassling through payment specific codes. Install the flutter_webview_plugin from the pub.

How to do it?

Let’s check the instamojo API docs for the answer-

  1. We request for payment by creating an HTTP request, with payment details like username, phone number, email address, the purpose for payment, amount etc.
  2. If the request is successful which means the phone number, email is valid then it’ll give the response, from which we can take the longurl(the Url for taking payment).
  3. Now we will open this Url(longurl) in a webview and that’s it, it’ll give a page to select a payment method and rest of the thing will be managed by the payment gateway server.

Let’s code —

Note:- Here we are using a test account, you can create a test account here, and you have to change all HTTP request URL from to

First of all, create a test instamojo account so that we can take our API key and Auth token, and then we are good to go.

  1. Create an HTTP request, and take longurl from the response, and finally launch it in a webview.

Create a Request

Body Params

amount: required string Amount to be paid in XX.YY format

purpose: required string Purpose of payment

buyer_name: string Name of payer

email: string Email of payer

phone: string Phone number of person paying

redirect_url: string

URL where we redirect the user after a payment. If provided, we will redirect the user to redirect_urlimmediately after the payment has been processed. Two additional query arguments payment_request_id and payment_id are also sent with the redirect URL.

webhook: string

URL where our server does POST request after a payment If provided, we will do a the POST request to the webhook (URL) with full details of the payment

allow_repeated_payments: boolean true

If allow_repeated_payments is false, only one payment can be paid on a payment request link. allow_repeated_payments is true by default.

send_email: boolean false

Flag to send request link via email. If send_email is true, a request email will be sent to the email supplied. If send_email is true but no email is supplied, request creation will throw an error.

send_sms: boolean false

Flag to send request link via SMS. If send_sms is true, a request SMS will be sent to the phone number supplied. If send_sms is true but no phone number is supplied, request creation will throw an error.

expires_at: datetime

Time after which the payment request will be expired. Max value is 600 seconds. Default is Null

Required Headers:



Let’s create a request —

const kAndroidUserAgent ="Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36";Future createRequest() async {Map<String, String> body = {"amount": "100", //amount to be paid"purpose": "Advertising","buyer_name": name,"email": email,"phone": phone,"allow_repeated_payments": "true","send_email": "false","send_sms": "false","redirect_url": "", //Where to redirect after a successful payment."webhook": "",};//First we have to create a Payment_Request.//then we'll take the response of our request.var resp = await""),headers: {"Accept": "application/json","Content-Type": "application/x-www-form-urlencoded","X-Api-Key": "Your-api-key","X-Auth-Token": "Your-auth-token"},body: body);if (json.decode(resp.body)['success'] == true) {//If request is successful take the longurl.String selectedUrl = json.decode(resp.body)["payment_request"
['longurl'].toString() +
"?embed=form";flutterWebviewPlugin.close();//Let's open the url in webview.flutterWebviewPlugin.launch(selectedUrl,rect: new Rect.fromLTRB(5.0,MediaQuery.of(context).size.height / 7,MediaQuery.of(context).size.width - 5.0,7 * MediaQuery.of(context).size.height / 7),userAgent: kAndroidUserAgent
_showSnackbar(json.decode(resp.body)['message'].toString());//If something is wrong with the data we provided to//create the Payment_Request. For Example, the email is in incorrect format, the payment_Request creation will fail.}}

When you open the longurl you can see a page like this

2. After payment, it’ll redirect the user to the redirect URL ( thank you page or anything you like your user to show after payment) which you have to provide in the first step(in the HTTP request).

That’s it if you just need to take payment from your app, but in real life that’s not the case, we have to do some stuff after payment completion like posting payment details in firebase or doing some stuff after successful payment.

Case 1 — posting payment details in firebase like payment amount, purpose, payment id, payment status etc. For this purpose instamojo provide us a way to accomplish this, WEBHOOK (if you want to use webhook, you can provide webhook URL while making an HTTP request)

What is a webhook?

Webhooks allow you to get notified of events that happen on Instamojo.

For example, when a buyer makes payment, Instamojo can send an HTTP POST request to your server. This avoids the need to keep polling Instamojo servers for updates.

A webhook is not a redirect. The buyer or the browser will never see it. Its a communication channel between Instamojo servers and your servers.

this is a broad topic and it’s out of the scope of this article.

Case 2 — Doing some stuff after successful payment, For this purpose, we have to check the payment status and by looking on API docs we get a method that’s there just for this sole purpose.

Get Payment Details

Path Params

id: required string ID of the payment

This endpoint returns the details of a payment related to a particular payment request.

To check whether the payment was successful or not use the "status" key inside the "payment" dictionary. If the status is "Credit" then the payment was successful otherwise it failed.

Required Headers:



But for getting status we have to know the payment id, fortunately, there’s a simple way to get the payment id. When instamojo server redirects the user to our redirect URL it adds payment id and payment request id in the URL, if our redirect URL is then the user will redirected to the URL like

Let’s get the payment_id from this URL —

1. First, we need to know when the user is redirected to our redirect_url, for this purpose we can use the onUrlChanged method of our flutter webview plugin.

final flutterWebviewPlugin = new FlutterWebviewPlugin();@overridevoid initState() {super.initState();createRequest(); //creating the HTTP request// Add a listener on url changedflutterWebviewPlugin.onUrlChanged.listen((String url) {if (mounted) {if (url.contains('')) {Uri uri = Uri.parse(url);//Take the payment_id parameter of the url.String paymentRequestId = uri.queryParameters['payment_id'];//calling this method to check payment status_checkPaymentStatus(paymentRequestId);}}});}

2. when we are in the redirect_url, call a method and pass this freshly baked URL to the method, and finally take the payment_id from the URL.

_checkPaymentStatus(String id) async {var response = await http.get(Uri.encodeFull("$id/"),+
headers: {
"Accept": "application/json","Content-Type": "application/x-www-form-urlencoded","X-Api-Key": "Your-api-key","X-Auth-Token": "Your-auth-token"});var realResponse = json.](response.body);print(realResponse);if (realResponse['success'] == true) {if (realResponse["payment"]['status'] == 'Credit') {//payment is successful.} else {//payment failed or pending.}} else {print("PAYMENT STATUS FAILED");}}

That’s it, folks. I hope it’ll help to integrate payment gateway in your flutter apps. If you like this post please tap the clap button and enjoy the moment 👏

Flutter Community

Articles and Stories from the Flutter Community

Md Sadab Wasim

Written by

Flutter programmer; Develop android apps, Founder of

Flutter Community

Articles and Stories from the Flutter Community

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade