Unlocking the Power of PhonePe Payment Integration in Flutter: A Step-by-Step Guide

Article by: Manish Methani

Last Updated: September 15, 2021 at 10:04am IST
3 min 30 sec

Step 1:

Apply for the PhonePe Payment Gateway here: https://www.phonepe.com/business-solutions/payment-gateway/

Step 2

To integrate the PhonePe payment gateway in a Flutter app using the provided test environment credentials, you will need to make HTTP requests to the PhonePe API. Below is a sample Flutter code snippet that demonstrates how to make a POST request to PhonePe's API to initiate a payment transaction.

Before implementing this code, make sure you have the necessary packages added to your pubspec.yaml file:

dependencies:
       http: ^0.13.3 # For making HTTP requests 

Step 3

Now, you can use the following code as a starting point for integrating PhonePe payments into your Flutter app:

import "dart:convert";
import "package:flutter/material.dart";
import "package:http/http.dart" as http;

class PhonePePaymentScreen extends StatefulWidget {
  @override
  _PhonePePaymentScreenState createState() => _PhonePePaymentScreenState();
}

class _PhonePePaymentScreenState extends State {
  final String merchantId = "MERCHANTUAT";
  final String appId = "YOUR_APP_ID"; // Replace with your actual App ID
  final String keyIndex = "1";
  final String key = "a6334ff7-da0e-4d51-a9ce-76b97d518b1e";

  // The URL to PhonePes test environment
  final String apiUrl = "https://mercury-uat.phonepe.com";

  // Function to initiate the payment transaction
  Future initiatePayment() async {
    try {
      // Construct the request URL for initiating payment
      final String paymentUrl = "$apiUrl/v3/app/pay";

      // Construct the request headers
      final Map headers = {
        "Content-Type": "application/json",
      };

      // Construct the request body
      final Map requestBody = {
        "merchantId": merchantId,
        "transactionId": "YOUR_TRANSACTION_ID", // Replace with a unique transaction ID
        "transactionAmount": 100, // Replace with the transaction amount (in cents)
        "requestType": "Payment",
        "merchantOrderId": "YOUR_ORDER_ID", // Replace with your order ID
        "merchantAppName": "YOUR_APP_NAME", // Replace with your app name
        "merchantUPI": "YOUR_MERCHANT_UPI_ID", // Replace with your UPI ID
        "appUPI": "YOUR_APP_UPI_ID", // Replace with your Apps UPI ID
        "txnTime": DateTime.now().toUtc().toIso8601String(),
      };

      // Convert the request body to JSON
      final String requestBodyJson = json.encode(requestBody);

      // Send the POST request
      final http.Response response = await http.post(
        Uri.parse(paymentUrl),
        headers: headers,
        body: requestBodyJson,
      );

      // Handle the response
      if (response.statusCode == 200) {
        final Map responseData = json.decode(response.body);
        // Handle the response data as needed
        print("Response Data: $responseData");
      } else {
        // Handle error
        print("HTTP Error: ${response.statusCode}");
      }
    } catch (e) {
      // Handle exception
      print("Error: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("PhonePe Payment"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            initiatePayment();
          },
          child: Text("Initiate Payment"),
        ),
      ),
    );
  }
}

In this code:

  1. Replace "YOUR_APP_ID" with the actual App ID provided by PhonePe.
  2. Customize the initiatePayment function to include the required transaction details.
  3. Make sure you have proper error handling and response handling based on your specific use case.

This code initiates a payment transaction when the "Initiate Payment" button is pressed. It sends a POST request to the PhonePe API's test environment with the transaction details. Be sure to replace placeholders with your actual data.

For Phonpe Payment gateway official documentation, you can refer the integration steps here: https://developer.phonepe.com/v1/docs/integration-steps-2

 

 

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com