How To Easily Integrate Telr Payment Gateway With Your Flutter App

CodeTrade
813 Views

Payment gateway integration is crucial for any Flutter app like PhonePe, Google Pay, and Paytm that involves monetary transactions, as it allows businesses to accept payments from customers. Telr payment gateway provides a seamless and secure solution for Flutter apps to accept a variety of payment methods. In this blog, we’ll explore the process of integrating the Telr payment gateway into your Flutter app.

What is Telr?

Telr is a widely utilized payment gateway that enables businesses to accept online and mobile payments. It is a favored option for businesses of various scales that encompass small enterprises and large corporations. Diverse businesses, such as e-commerce shops, travel platforms, and online gaming websites, make use of the Telr payment gateway. This payment gateway complies with PCI DSS standards and accommodates payments from more than 170 countries and a multitude of currencies.

Why Choose Telr Payment Gateway?

Before diving into the integration process, it's essential to understand why Telr is a preferred choice for many developers. Telr is known for its:

  • International Reach

    Supports payments in multiple currencies which makes it more suitable for apps that cater to a global audience.

  • Security

    Ensures the highest level of security for transactions and offers both tokenization and fraud prevention features.

  • Easy Integration

    Provides well-documented APIs and SDKs that simplify the integration process for developers.

  • Robust Support

    Offer excellent customer support which is crucial when dealing with financial transactions.

Let's dive into the step-by-step integration process of the Telr Payment gateway with the Flutter app.

Flutter App Integration with Telr Payment Gateway

To easily integrate the Telr payment gateway with your Flutter app, you can follow these steps:

Step 1: Create a Telr Account

To get started, you need to sign up for a Telr account. Follow these steps:

  • Visit the Telr website and click on the "Sign Up" or "Create Account" button.

  • Include your business details and contact information.

  • Verify your email address to activate your Telr account.

Step 2: Obtain Your API Credentials

Once you have successfully created a Telr account, you'll need to obtain your API credentials. These credentials will enable your Flutter app to communicate with the Telr Payment Gateway.

  • Log in to your Telr account.

  • Navigate to the developer section and look for the API credentials.

  • Generate your API key and API secret. These will be used in your app's code for authentication.

Step 3: Add Required Dependencies

We will build an XML file to integrate the Telr Mobile API and then load it in a web view. To make successful API requests, add the following latest dependencies to your pubspec.yaml file:

Add-Required-Dependencies-for-telr-payment-gateway-in-flutter-app-1

Step 4: Add Required Text Fields and Pay button

Next, we’ll add text fields for the amount and currency code and add a pay button to initiate payment.

TextField(
 controller: _amount,
 textAlign: TextAlign.center,
 style: TextStyle(fontSize: 13, color: Colors.red),
 decoration: InputDecoration(
   hintText: "Enter Amount",
   errorStyle: TextStyle(fontSize: 10),
    ),
),
TextField(
 controller: _currency,
 textAlign: TextAlign.center,
 style: TextStyle(fontSize: 13),
 decoration: InputDecoration(
   hintText: "Enter currency",
   errorStyle: TextStyle(fontSize: 10),
    ),
),
ElevatedButton(
   child: Container(
     height: 50,
     color: Colors.grey,
     child: Center(
         child: Text(
       'PAY',
       style: TextStyle(color: Colors.black, fontSize: 12),
     )),
   ),
   onPressed: () {
     // XML Processing code for payment
   }
)

Step 5: Build XML for Payment Processing

Follow the given code to create an XML structure for processing payments.

onPressed: ()
{
 final builder = XmlBuilder();
 builder.processing('xml', 'version="1.0"');
 builder.element('mobile', nest: () {
   builder.element('store', nest: () {
     builder.text('your store id');
   });
   builder.element('key', nest: () {
     builder.text('your authentication key for mobile api');
   });

   builder.element('device', nest: () {
     builder.element('type', nest: () {
       builder.text('iOS');
     });
     builder.element('id', nest: () {
       builder.text(id);
     });
   });

   // app
   builder.element('app', nest: () {
     builder.element('name', nest: () {
       builder.text('Telr');
     });
     builder.element('version', nest: () {
       builder.text('1.1.6');
     });
     builder.element('user', nest: () {
       builder.text('2');
     });
     builder.element('id', nest: () {
       builder.text('123');
     });
   });

   //tran
   builder.element('tran', nest: () {
     builder.element('test', nest: () {
       builder.text('1');
     });
     builder.element('type', nest: () {
       builder.text('auth');
     });
     builder.element('class', nest: () {
       builder.text('paypage');
     });
     builder.element('cartid', nest: () {
       builder.text(
           100000000 + Random().nextInt(999999999));
     });
     builder.element('description', nest: () {
       builder.text('Test for Mobile API order');
     });
     builder.element('currency', nest: () {
       builder.text(_currency.text);
     });
     builder.element('amount', nest: () {
       builder.text(_amount.text);
     });
     builder.element('language', nest: () {
       builder.text('en');
     });
     builder.element('firstref', nest: () {
       builder.text('first');
     });
     builder.element('ref', nest: () {
       builder.text('null');
     });
   });

   //billing
   builder.element('billing', nest: () {
     // name
     builder.element('name', nest: () {
       builder.element('title', nest: () {
         builder.text('');
       });
       builder.element('first', nest: () {
         builder.text('Div');
       });
       builder.element('last', nest: () {
         builder.text('V');
       });
     });
     // address
     builder.element('address', nest: () {
       builder.element('line1', nest: () {
         builder.text('Dubai');
       });
       builder.element('city', nest: () {
         builder.text('Dubai');
       });
       builder.element('region', nest: () {
         builder.text('');
       });
       builder.element('country', nest: () {
         builder.text('AE');
       });
     });

     builder.element('phone', nest: () {
       builder.text('551188269');
     });
     builder.element('email', nest: () {
       builder.text([email protected]');
     });
   });
 });

 final bookshelfXml = builder.buildDocument();

 // print(bookshelfXml);
 pay(bookshelfXml);
}
)

Note: XML values for the payment

  • Store ID

    Replace your store ID from the Telr Dashboard and substitute it as the XML value.

  • Key

    Use your mobile API authentication key from the Telr Dashboard.

  • Language

    Choose your preferred Language.

  • Test

    Set the test mode to "1" for testing purposes, and modify it to any other number for the live mode.

Step 6: Add Pay Method

To add a pay method to make a payment in your Flutter app, follow the given code.


void alertShow(String text) {
 showDialog(
   context: context,
   builder: (_) => AlertDialog(
     title: Text(
       '$text',
       style: TextStyle(fontSize: 15),
     ),
     actions: <Widget>[
       ElevatedButton(
           child: Text('Ok'),
           onPressed: () {
             Navigator.pop(context);
           }),
     ],
   ),
 );
}

void pay(XmlDocument xml) async {
 NetworkHelper _networkHelper = NetworkHelper();
 var response = await _networkHelper.pay(xml);
 print(response);
 if (response == 'failed' || response == null) {
   // failed
   alertShow('Failed');
 } else {
   final doc = XmlDocument.parse(response);
   final url = doc.findAllElements('start').map((node) => node.text);
   final code = doc.findAllElements('code').map((node) => node.text);
   print(url);
   _url = url.toString();
   String _code = code.toString();
   if (_url.length > 2) {
     _url = _url.replaceAll('(', '');
     _url = _url.replaceAll(')', '');
     _code = _code.replaceAll('(', '');
     _code = _code.replaceAll(')', '');
     _launchURL(_url, _code);
   }
   print(_url);
   final message = doc.findAllElements('message').map((node) => node.text);
   print('Message =  $message');
   if (message.toString().length > 2) {
     String msg = message.toString();
     msg = msg.replaceAll('(', '');
     msg = msg.replaceAll(')', '');
     alertShow(msg);
   }
 }
}

Step 7: Create Helper Class

Create a Helper Class to make API requests.

class NetworkHelper {
 NetworkHelper();

 Future pay(XmlDocument xml) async {
   String url = 'https://secure.telr.com/gateway/mobile.xml';
   var data = {xml};
   var body = xml.toString();
   // print('body = $body');

   http.Response response = await http.post(
     Uri.parse(url),
     body: body,
     headers: {
       "Content-Type": "application/xml",
     },
   );
   print("Response = ${response.statusCode}");
   // print("Response body = ${response.body}");
   if (response.statusCode == 200 || response.statusCode == 400) {
     return response.body;
   } else {
     return 'failed';
   }
 }

 Future completed(XmlDocument xml) async {
   String url = 'https://secure.telr.com/gateway/mobile_complete.xml';
   var data = {xml};

   var body = xml.toString();
   // print('body = $body');

   http.Response response = await http.post(
     Uri.parse(url),
     body: body,
     headers: {
       "Content-Type": "application/xml",
     },
   );
   print("Response = ${response.statusCode}");
   // print("Response body = ${response.body}");
   if (response.statusCode == 200 || response.statusCode == 400) {
     return response.body;
   } else {
     return 'failed';
   }
 }
}

Step 8: Launch WebView Screen

After getting the URL, launch the WebView Screen.

void _launchURL(String url, String code) async {
 Navigator.push(
     context,
     MaterialPageRoute(
         builder: (BuildContext context) => WebViewScreen(
               url: url,
               code: code,
             )));
}

Step 9: Add WebView Screen

We will add a webview screen to allow users to add their card details and integrate payment processing.


class WebViewScreen extends StatefulWidget {
 final url;
 final code;
 WebViewScreen({@required this.url, @required this.code});

 @override
 _WebViewScreenState createState() => _WebViewScreenState();
}

class _WebViewScreenState extends State<WebViewScreen> {
 String _url = '';
 String _code = '';
 bool _showLoader = false;
 bool _showedOnce = false;

 @override
 void initState() {
   // TODO: implement initState
   super.initState();
   if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
   _url = widget.url;
   _code = widget.code;
   print('url in webview $_url, $_code');
 }

 void complete(XmlDocument xml) async {
   setState(() {
     _showLoader = true;
   });
   NetworkHelper _networkHelper = NetworkHelper();
   var response = await _networkHelper.completed(xml);
   print(response);
   if (response == 'failed' || response == null) {
     alertShow('Failed. Please try again', false);
     setState(() {
       _showLoader = false;
     });
   } else {
     final doc = XmlDocument.parse(response);
     final message = doc.findAllElements('message').map((node) => node.text);
     if (message.toString().length > 2) {
       String msg = message.toString();
       msg = msg.replaceAll('(', '');
       msg = msg.replaceAll(')', '');
       setState(() {
         _showLoader = false;
       });
       if (!_showedOnce) {
         _showedOnce = true;
         alertShow('Your transaction is $msg', true);
       }
       // https://secure.telr.com/gateway/webview_start.html?code=a8caa483fe7260ace06a255cc32e
     }
   }
 }

 void alertShow(String text, bool pop) {
   print('popup thrown');
   showPlatformDialog(
     context: context,
     builder: (_) => BasicDialogAlert(
       title: Text(
         '$text',
         style: TextStyle(fontSize: 15),
       ),
       actions: <Widget>[
         BasicDialogAction(
             title: Text('Ok'),
             onPressed: () {
               print(pop.toString());
               if (pop) {
                 print('inside pop');
                 Navigator.pop(context);
                 Navigator.pop(context);
               } else {
                 print('inside false');
                 Navigator.pop(context);
               }
             }),
       ],
     ),
   );
 }

 void createXml() {
   final builder = XmlBuilder();
   builder.processing('xml', 'version="1.0"');
   builder.element('mobile', nest: () {
     builder.element('store', nest: () {
       builder.text('your store id');
     });
     builder.element('key', nest: () {
       builder.text('your authentication key');
     });
     builder.element('complete', nest: () {
       builder.text(_code);
     });
   });


   final bookshelfXml = builder.buildDocument();
   print(bookshelfXml);
   complete(bookshelfXml);
 }

 final Completer<WebViewController> _controller =
     Completer<WebViewController>();
 @override
 Widget build(BuildContext context) {
   return Scaffold(
       appBar: AppBar(
         backgroundColor: Colors.white,
         title: Text(
           'Payment',
           style: TextStyle(color: Colors.black),
         ),
         leading: Center(
           child: GestureDetector(
             onTap: () {
               Navigator.pop(context);
             },
             child: Text(
               'Cancel',
               style: TextStyle(color: Colors.blue),
             ),
           ),
         ),
       ),
       body: WebView(
         initialUrl: _url,
         javascriptMode: JavascriptMode.unrestricted,
         onWebViewCreated: (WebViewController webViewController) {
           _controller.complete(webViewController);
         },
         navigationDelegate: (NavigationRequest request) {
           print('allowing navigation to $request');
           return NavigationDecision.navigate;
         },
         onPageStarted: (String url) {
           print('Page started loading: $url');
           _showedOnce = false;
           if (url.contains('close')) {
             print('call the api');
           }
           if (url.contains('abort')) {
             print('show fail and pop');
           }
         },
         onPageFinished: (String url) {
           print('Page finished loading: $url');
           if (url.contains('close')) {
             print('call the api');
             createXml();
           }
           if (url.contains('abort')) {
             print('show fail and pop');
           }
         },
         gestureNavigationEnabled: true,
       ));
 }
}

Step 10: Test Payment Process

Test the payment process thoroughly before launching your app with Telr integration. Use Telr's sandbox or test mode to simulate transactions without any real financial impact.

That's it.! You can successfully integrate your Flutter app with the Telr payment gateway.

Conclusion

Flutter app integration with the Telr payment gateway is a valuable investment in providing a secure and convenient payment experience for your users. The dependability and straightforward integration of Telr make it an excellent choice for developers in search of a smooth payment solution.

By following the steps outlined in this guide, you can easily integrate Telr Payment Gateway into your Flutter app and empower your users to make payments with confidence. Enhance your app's functionality and improve the user experience by offering a secure and diverse range of payment options through Telr. Start today and boost your app's payment capabilities.

If you are looking for dedicated flutter developers, reach out to CodeTrade India. Our skilled Flutter developers are ready to assist you with any challenges you may encounter in Flutter app development. Contact CodeTrade today.

CodeTrade
CodeTrade, a Custom Software Development Company, provides end-to-end SME solutions in USA, Canada, Australia & Middle East. We are a team of experienced and skilled developers proficient in various programming languages and technologies. We specialize in custom software development, web, and mobile application development, and IT services.