PhonePe Payment Gateway Integration Guide

Seamless Integration and Secure Transactions: The Complete Guide to Incorporating PhonePe Payment Gateway

Posted by Lecture Home on August 14, 2023

Businesses of all sizes now need to offer a secure and seamless payment experience due to the fast-changing world of digital transactions. An innovative and user-friendly payment gateway is available from PhonePe, a pioneer in the field of electronic payments, and it is simple to integrate into websites. This integration empowers businesses to accept payments efficiently and build trust among customers.

Understanding the Integration Process

The integration process of the PhonePe payment gateway involves the creation of a form on your website to gather payment details from customers. The collected data is then passed to the `payment.php` page using the POST method, where further processing takes place.



Step-by-Step Guide to Integrate PhonePe Payment Gateway

1. Create a Form : Begin by designing a form on your website's payment page. This form should collect essential payment-related information from users, including their unique user ID (`uid`) and the payment amount (`amount`).

2. Pass Data to `payment.php`: Utilize the POST method to send the collected data to the `payment.php` page. This page will handle the integration process with PhonePe's payment gateway.

3. Generate Payment Request: Inside the `payment.php` page, initiate the payment process by creating a JSON request. This request should include various parameters such as `merchantId`, `merchantTransactionId`, `merchantUserId`, `amount`, `redirectUrl`, and `callbackUrl`.

4. Encode Request Data: Encode the JSON request using the base64 encoding method. Combine the encoded request with the appropriate URL and a salt key to generate a hash value.

5. Initiate cURL Request: Utilize the cURL library to send the JSON request to PhonePe's API endpoint. Ensure that the encoded request, hash value, and necessary headers are included in the cURL request.

6. Handle Response: Receive the response from PhonePe's API. If the response indicates success, extract the redirect URL from the response data. This URL will be used to redirect the user to the PhonePe payment page for further processing.

Code For payment.php


                        
                            <?php
                            
                            if (isset($_POST)) {
                                $uid = $_POST["uid"]; // Unique user ID provided by the merchant
                                $amt = $_POST["amount"]; // Payment amount
                                $amt = $amt * 100; // Convert amount to rupees
                                
                                // Creating a JSON request
                            
                                $request["merchantId"] = "merchant_id"; // Input merchant ID provided by PhonePe
                                
                                $request["merchantTransactionId"] = "MT_" . $uid . "_" . time(); // Generating a unique transaction ID for each transaction, should be unique for each transaction
                                
                                $request["merchantUserId"] = "MUID_" . $uid . "_" . time(); // Generating a unique merchant ID for each transaction
                                
                                $request["amount"] = $amt; // Payment amount
                                
                                $request["redirectUrl"] = "https://lecturehome.com/payment_status.php"; // Redirect URL after a successful transaction or if any error occurred
                                
                                $request["redirectMode"] = "POST";
                                
                                $request["callbackUrl"] = "https://lecturehome.com/payment_status.php"; // Callback URL after a successful transaction or if any error occurred
                                $request["mobileNumber"] = "";
                                
                                $request_type["type"] = "PAY_PAGE";
                                $request["paymentInstrument"] = $request_type;
                                
                                $requestJson = json_encode($request);
                                
                                $base = base64_encode($requestJson);
                                
                                $salt = "salt_key"; // Input salt key provided by PhonePe
                                // Example: $salt = "099eb0cd-02cf-4e2a-8aca-3e6c6aff0399";
                                
                                $val = base64_encode($requestJson) . "/pg/v1/pay" . $salt;
                                
                                $hashRequest = hash("sha256", $val);
                                
                                $hashFinalRequest = $hashRequest . "###1"; // Input salt index after ###
                                
                                $curl = curl_init();
                                
                                curl_setopt_array($curl, [
                                    CURLOPT_URL => "https://api.phonepe.com/apis/hermes/pg/v1/pay",
                                    CURLOPT_RETURNTRANSFER => true,
                                    CURLOPT_ENCODING => "",
                                    CURLOPT_MAXREDIRS => 10,
                                    CURLOPT_TIMEOUT => 30,
                                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                                    CURLOPT_CUSTOMREQUEST => "POST",
                                    CURLOPT_POSTFIELDS => "{"request":"$base"}",
                                    CURLOPT_HTTPHEADER => [
                                        "Content-Type: application/json",
                                        "X-VERIFY: $hashFinalRequest",
                                        "accept: application/json"
                                    ],
                                ]);
                                
                                $response = curl_exec($curl);
                                $err = curl_error($curl);
                                
                                curl_close($curl);
                                
                                if ($err) {
                                    echo "Error encountered while processing the payment";
                                } else {
                                    $obj = json_decode($response);
                                    
                                    if ($obj->success == "") {
                                        echo "Error encountered while processing the payment (Error: " . $obj->message . ")";
                                    } else {
                                        header("Location: " . $obj->data->instrumentResponse->redirectInfo->url);
                                    }
                                }
                                
                            } else {
                                echo "Invalid Request";
                            }
                            ?>                            
                                                    

This PHP code snippet demonstrates the process of generating a JSON request for the PhonePe payment gateway and handling the response. It involves creating a request, encoding it, adding security measures, and sending it to PhonePe's API endpoint. The response is then processed to either display an error message or redirect the user for payment processing.

Please make sure to replace "merchant_id" with your actual merchant ID and "salt_key" with your actual salt key provided by PhonePe. Also, ensure that the URLs for redirectUrl and callbackUrl match your website's URLs accordingly.



Code For payment_status.php


                        
                            <?php
                            // payment_status.php
                            
                            // Display the received POST data
                            echo $_POST["code"];
                            
                            // Display a message and initiate redirection
                            echo ", Redirecting within 5 seconds";
                            
                            echo "
                                <script>
                                    setTimeout(function(){
                                        window.location.href = "[your_url]"; // URL for redirecting
                                    }, 5000); // Delay for 5 seconds before redirecting
                                </script>";
                            ?>
                                                    

This PHP code snippet is designed to be placed in a file named payment_status.php. It displays the value received via the POST request (presumably a payment status code), informs the user about redirection, and then uses JavaScript to automatically redirect the user to a specified URL after a 5-second delay.

Please replace the empty quotes '' within window.location.href with the actual URL to which you want to redirect the user after the payment status is displayed.


Enhancing Security and User Experience

Integrating the PhonePe payment gateway offers dual benefits:

Enhanced Security:

PhonePe employs robust encryption mechanisms to protect sensitive payment data, ensuring secure transactions.

User-Friendly Experience:

The integration ensures a smooth and intuitive payment process, reducing the likelihood of cart abandonment.




Handling Payment Status and Redirects

The `payment_status.php` page plays a crucial role in managing payment status updates and redirection after successful transactions. After the transaction is completed:

1. Display the transaction status, potentially using the `$_POST['code']` parameter to provide relevant information to users.

2. Offer a user-friendly message indicating that redirection will occur shortly.

3. Utilize JavaScript to automate the redirection process. After a brief delay, users are automatically redirected to a predefined URL.

Adding the PhonePe payment gateway to your website is a wise move that will raise the caliber of your online payment system, to sum up. You can instantly integrate PhonePe's cutting-edge payment solution and give clients a safe and efficient payment experience by following the thorough instructions provided below. By encouraging trust and improving customer happiness, this integration increases your business's bottom line.



Hide
Translate the page to your preferred language
Show Translator