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

 

 

Learn Flutter, FlutterFlow,
Firebase & Angular.

Looking to learn how to create the production-ready apps
from scratch? Well, you are at the right place.

₹1299 or $15.56

Learn to create the Dating App using No-Code Tool FlutterFlow

Level: Advanced

Explore Curriculum
₹1299 or $15.56

Flutter Mobile App Development Course

Explore Curriculum
₹1299 or $15.56

The Complete Angular Course

Explore Curriculum
₹1299 or $15.56

Dart Programming for Absolute Beginners

Coming Soon
FREE

Next.js course

Start Watching
FREE

Fundamentals of Computer Programming Languages

Start Watching
FREE

Learn HTML, CSS & Bootstrap

Start Watching

Latest Web Stories

1

Learn how to open WhatsApp using FlutterFlow | Step by Step Guide

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test

Download the Codzify
Mobile App


Learn Anytime, Anywhere at your own pace. Scan the QR Code with your Mobile Camera to Download the Codzify Mobile App.

Codzify Mobile App Codzify Mobile App
Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer