Handle Webhooks with PHP SDK


PhonePe sends payment status updates to your configured webhook URL. Setting this up is crucial to ensure accurate payment confirmations. To handle these updates, create a PHP script that listens for incoming POST requests at your specified callbackUrl.

The validateCallback() method is used to validate webhook or callback responses. You can use this method by passing all the necessary parameters:

Parameter NameData TypeDescription
usernameStringYour unique username configured for the callback URL
passwordStringYour unique password configured for the callback URL
authorizationStringThe Authorization token sent in the callback response
responseBodyStringThe actual response body received in the callback as a string
Sample Request
<?php

require_once "vendor/autoload.php";

use PhonePe\payments\v2\standardCheckout\StandardCheckoutClient;
use PhonePe\common\exceptions\PhonePeException;

// Retrieve headers and request body
$headers = getallheaders();
$requestBody = file_get_contents("php://input");

// Your username and password for callback verification
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";

// Initialize PhonePe Client
$clientId = "YOUR_CLIENT_ID"; // Replace with your Client ID
$clientVersion = CLIENT_VERSION; // Replace with your Client Version
$clientSecret = "YOUR_CLIENT_SECRET"; // Replace with your Client Secret
$env = \PhonePe\Env::PRODUCTION; // Replace with your Environment

$standardCheckoutClient = StandardCheckoutClient::getInstance(
    $clientId,
    $clientVersion,
    $clientSecret,
    $env
);

try {
    $callbackResponse = $standardCheckoutClient->verifyCallbackResponse(
        $headers,
        json_decode($requestBody, true),
        $username,
        $password
    ); // Process the callback response
} catch (\PhonePe\common\exceptions\PhonePeException $e) {
    // Handle exceptions (e.g., log the error)
    echo "Error validating callback response: " . $e->getMessage();
}

?>

PhonePe uses Basic Authentication to authenticate callbacks to the your server. You need to verify the authenticity of the callbacks from PhonePe by validating the username and password in the authorization header.

Steps to Verify the Callback

  • Extract Headers
    • Use getallheaders() to retrieve all request headers.
  • Read Request Body
    • Use file_get_contents('php://input') to get the raw request body.
  • Verify and Parse
    • Call verifyCallbackResponse() to validate the callback and parse the response.
  • Respond with Proper HTTP Status Codes
    • 200 OK: Indicates successful processing of the callback.  The PhonePe system will retry callbacks that don’t receive a 200 OK response.
    • 400 Bad Request: Indicates an error in the request or verification failure.
    • 500 Internal Server Error: Indicates a server-side error.
  • Log Errors
    Always log errors to help with troubleshooting and debugging.

The function returns a CallbackResponse object containing two main parameters: type, which indicates the event type, and payload, which holds all the event-specific details.

Parameter NameData TypeDescription
typeCallbackTypeTells you what type of event happened (e.g., order completed, refund failed, etc.)
payloadCallbackDataContains all the details related to that event
  • The event type are explained below:
Callback TypeDescription
CHECKOUT_ORDER_COMPLETEDThe payment was successfully completed
CHECKOUT_ORDER_FAILEDThe payment failed
PG_REFUND_COMPLETEDA refund was successfully processed
PG_REFUND_FAILEDA refund request failed
PG_REFUND_ACCEPTEDPhonePe Payment Gateway acknowledged the refund request, but it’s not completed yet
  • The payload details are explained below:
Parameter NameData TypeDescription
merchantIdStringMerchant ID from which the request was initiated
orderIdStringOrder ID generated by PhonePe Payment Gateway (only for order callbacks)
originalMerchantOrderIdStringOrder ID generated by you (only for order callbacks)
refundIdStringRefund ID generated by PhonePe PG (only for refund callbacks)
merchantRefundIdStringRefund ID generated by you (only for refund callbacks)
stateStringThe current state of the order or refund.
amountLongThe amount processed in paisa.
expireAtLongThe expiry timestamp in epoch format
errorCodeStringThe error code (only for failed transactions)
detailedErrorCodeStringA more detailed error code (only for failures)
metaInfoMetaInfoMetadata passed during order initialization
paymentDetailsList<PaymentDetail>The Payment details of the transaction

The PaymentRefundDetail property contains a list of payment details for each payment attempt made against an order. The details of each payment are explained in the table below.

PaymentDetail
AttributeData TypeDescription
transactionIdStringMerchant ID from which the request was initiated
paymentModeStringOrder ID generated by PhonePe Payment Gateway (only for order callbacks)
timestampLongOrder ID generated by you (only for order callbacks)
stateStringAttempted transaction state. It can be any one of the following states:
COMPLETED
FAILED
PENDING
errorCodeStringError code (only present when the state is failed)
detailedErrorCodeStringA more specific error code (only present when the state is failed)

This document outlines how exceptions are handled within the PhonePe SDK, particularly focusing on the PhonePeException and associated response models that provide detailed error information.

PhonePeException is thrown when there are errors related to PhonePe SDK. It provides comprehensive error information which can be used for debugging and logging.

AttributeTypeDescription
codeStringThe status code of the http response.
messageStringThe http error message.
httpStatusCodeIntegerThe status code of the http response.
dataMap<String, String>The details of the error that happened while calling PhonePe.
Sample Request
<?php
use PhonePe\common\exceptions\PhonePeException;

try {
    // API call
} catch (PhonePeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo "HTTP Status Code: " . $e->getHttpStatusCode() . "\n";
}
?>

Now that you have learned how to verify the payment and what happens when the webhook fails, this concludes your website integration. The next step is to complete UAT testing and understand the process to go live.

Is this article helpful?