App Development

How to Integrate Phonepe Payment Gateway in Flutter [2024]

AAdminDecember 22, 20237 min read
How to Integrate Phonepe Payment Gateway in Flutter [2024]

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 = &quot;Flow complete - status : SUCCESS&quot;;

         await checkStatus();
        } else {
          result =
          &quot;Flow complete - status : $status and error $error&quot;;
        }
      } else {
        result = &quot;Flow Incomplete&quot;;
      }
  })
      .catchError((error) {
    handleError(error);
    return &lt;dynamic&gt;{};
  });
} 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 =
          &quot;/pg/v1/status/$merchantId/$transactionId$saltKey&quot;;

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

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

  Map&lt;String, String&gt; headers = {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        &quot;X-MERCHANT-ID&quot;: merchantId,
        &quot;X-VERIFY&quot;: xVerify,
      };


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

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

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

}

}

Need help with your project?

Talk to the Papaya Coders team for a free consultation.

Contact Us