How to Integrate Phonepe Payment Gateway in Flutter [2024]

How to Integrate Phonepe Payment Gateway in Flutter

In today’s digital world, facilitating secure and efficient payment options within mobile applications is an extremely important task, but developers can Integrate Phonepe Payment Gateway in Flutter to provide a seamless transaction experience.

Let’s take a look and understand how this comprehensive guide outlines the essential steps and insights required to integrate the PhonePe payment gateway into Flutter applications.

How to Integrate Phonepe Payment Gateway in Flutter

How to Integrate Phonepe Payment Gateway in Flutter 1 - Papaya Coders

Before Integrate Phonepe Payment Gateway in Flutter app, it is important to ensure that you have:-

Now let us know the step-by-step guide to Integrate Phonepe Payment Gateway in Flutter:-

Setting up payment gateway

Create a PhonePe Business Account: Register your business on this PhonePe online platform and then complete the verification process.

Generate API Key: Now you need to access the PhonePe developer console and generate the API key required for integration (this is a very important key).

Implementing Payment Gateway in Flutter

Install Dependencies: Install the plugins in your Flutter project and add the dependencies as per your need.

Write integration code: Now you need to implement the PhonePe SDK and then configure it in your Flutter app.

Testing and Troubleshooting

Test the integration: You conduct test transactions to ensure successful integration.

Common Issues & Solutions: Troubleshoot potential issues such as callback failures or misconfigurations.


<meta-data android:name="com.phonepe.android.sdk.isUAT" android:value="true"/>
    <meta-data android:name="com.phonepe.android.sdk.isSimulator" android:value="true"/>
    <meta-data android:name="com.phonepe.android.sdk.MerchantId" android:value="PGTESTPAYUAT"/>
 build.gradle Project Level
      maven {
        url  "https://phonepe.mycloudrepo.io/public/repositories/phonepe-intentsdk-android"
    }
phonepe_payment_sdk: ^1.0.4
crypto: ^3.0.3
http: ^1.1.0
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:phonepe_payment_sdk/phonepe_payment_sdk.dart';

import 'package:http/http.dart' as http;

class PhonePePayment extends StatefulWidget {
  const PhonePePayment({super.key});

  @override
  State<PhonePePayment> createState() => _PhonePePaymentState();
}

class _PhonePePaymentState extends State<PhonePePayment> {
  String environment = "UAT_SIM";
  String appId = "";
  String transactionId = DateTime
      .now()
      .millisecondsSinceEpoch
      .toString();

  String merchantId = "PGTESTPAYUAT";
  bool enableLogging = true;
  String checksum = "";
  String saltKey = "099eb0cd-02cf-4e2a-8aca-3e6c6aff0399";

  String saltIndex = "1";

  String callbackUrl =
      "https://webhook.site/f63d1195-f001-474d-acaa-f7bc4f3b20b1";

  String body = "";
  String apiEndPoint = "/pg/v1/pay";

  Object? result;

  getChecksum() {
    final requestData = {
      "merchantId": merchantId,
      "merchantTransactionId": transactionId,
      "merchantUserId": "90223250",
      "amount": 1000,
      "mobileNumber": "9999999999",
      "callbackUrl": callbackUrl,
      "paymentInstrument": {"type": "PAY_PAGE"}
    };

    String base64Body = base64.encode(utf8.encode(json.encode(requestData)));

    checksum =
    '${sha256.convert(utf8.encode(base64Body + apiEndPoint + saltKey))
        .toString()}###$saltIndex';

    return base64Body;
  }

  @override
  void initState() {
    super.initState();

    phonepeInit();

    body = getChecksum().toString();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Phonepe Payment Gateway"),
        ),
        body: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                startPgTransaction();
              },
              child: Text("Start Transaction"),
            ),
            const SizedBox(
              height: 20,
            ),
            Text("Result \n $result")
          ],
        ),
      ),
    );
  }

  void phonepeInit() {
    PhonePePaymentSdk.init(environment, appId, merchantId, enableLogging)
        .then((val) =>
    {
      setState(() {
        result = 'PhonePe SDK Initialized - $val';
      })
    })
        .catchError((error) {
      handleError(error);
      return <dynamic>{};
    });
  }

  void startPgTransaction() async {
    try {
      var response = PhonePePaymentSdk.startPGTransaction(
          body, callbackUrl, checksum, {}, apiEndPoint, "");
      response
          .then((val)

      async
      {
          if (val != null) {
            String status = val['status'].toString();
            String error = val['error'].toString();

            if (status == 'SUCCESS') {
              result = "Flow complete - status : SUCCESS";

             await checkStatus();
            } else {
              result =
              "Flow complete - status : $status and error $error";
            }
          } else {
            result = "Flow Incomplete";
          }
      })
          .catchError((error) {
        handleError(error);
        return <dynamic>{};
      });
    } catch (error) {
      handleError(error);
    }
  }

  void handleError(error) {
    setState(() {
      result = {"error": error};
    });
  }

   checkStatus() async {
    try {
      String url =
              "https://api-preprod.phonepe.com/apis/pg-sandbox/pg/v1/status/$merchantId/$transactionId"; //Test


      String concatenatedString =
              "/pg/v1/status/$merchantId/$transactionId$saltKey";

      var bytes = utf8.encode(concatenatedString);
      var digest = sha256.convert(bytes);
      String hashedString = digest.toString();

      //  combine with salt key
      String xVerify = "$hashedString###$saltIndex";

      Map<String, String> headers = {
            "Content-Type": "application/json",
            "X-MERCHANT-ID": merchantId,
            "X-VERIFY": xVerify,
          };


      await http.get(Uri.parse(url), headers: headers).then((value) {
            Map<String, dynamic> res = jsonDecode(value.body);

            try {
              if (res["code"] == "PAYMENT_SUCCESS" &&
                        res['data']['responseCode'] == "SUCCESS") {
                      Fluttertoast.showToast(msg: res["message"]);
                    }else{
                      Fluttertoast.showToast(msg:" Something went wrong");

                    }
            } catch (e) {
              Fluttertoast.showToast(msg:" Something went wrong");
            }
          });
    } catch (e) {
      Fluttertoast.showToast(msg:" Error");
    }
  }


}

Strategies:-Phonepe Integration in Flutter Applications

  • Optimizing User Experience with Phonepe Integration
  • Navigating challenges during integration is common.
  • Future-proof the app by considering scalability aspects.

Benefits of Using PhonePe in Flutter Apps

Security Features

PhonePe users enjoy strong security including encrypted transactions and two-factor authentication to ensure secure payment processing.

Enhanced User Experience

By integrating PhonePe, Flutter Apps provides users with a variety of benefits and features as well as a seamless and familiar payment experience while enhancing trust.

What is PhonePe?

It is one of India’s leading digital payment platforms using which you can make online transactions, pay bills, recharge mobile phones, and much more. It offers a user-friendly interface and it supports and supports various payment methods including UPI, credit/debit cards, and wallets. PhonePe is currently known as the market leader in the digital payments sector in India and is rising quite fast.

FAQ:-Payment Gateway integration in Flutter

Is Phonepe Payment Gateway Integration in Flutter Complex?

Yes, might seem complex at the initial stage.

How Can I Ensure Security While Integrating Phonepe Gateway in Flutter?

Security measures such as encryption methods as well as callback URL configuration are also important during integration.

Conclusion:-

This is an important step towards providing a seamless and secure payment experience. This guide promotes confidence as well as efficiency and equips these developers with a comprehensive understanding and step-by-step insights to successfully Integrate Phonepe Payment Gateway in Flutter.

If you like this How to integrate Phonepe payment gateway in Flutter post then comment down and share your opinion with us. You can also make ???? #Papayacoders on Instagram, Youtube, Twitter, Pinterest, Linkedin, and more and we mention them on Story. #FlutterDevelopment #PhonePeIntegration #CodingMagic #AppDevelopment #SmoothTransactions

In my previous blog on Create Best App for Your Business, I ended the post by linking to one of our final guides.

Tags :

Latest Post

Your Cart

No Item Found
Subtotal0.00
Shipping0.00
Tax0.00
Total0.00
0