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.
Request
The validateCallback() method is used to validate webhook or callback responses. You can use this method by passing all the necessary parameters:
| Parameter Name | Data Type | Description |
username | String | Your unique username configured for the callback URL |
password | String | Your unique password configured for the callback URL |
authorization | String | The Authorization token sent in the callback response |
responseBody | String | The actual response body received in the callback as a string |
<?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();
}
?>Authenticating Callbacks from PhonePe
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.
- Use
- Read Request Body
- Use
file_get_contents('php://input')to get the raw request body.
- Use
- Verify and Parse
- Call
verifyCallbackResponse()to validate the callback and parse the response.
- Call
- 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.
Response
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 Name | Data Type | Description |
| type | CallbackType | Tells you what type of event happened (e.g., order completed, refund failed, etc.) |
| payload | CallbackData | Contains all the details related to that event |
- The event
typeare explained below:
| Callback Type | Description |
CHECKOUT_ORDER_COMPLETED | The payment was successfully completed |
CHECKOUT_ORDER_FAILED | The payment failed |
PG_REFUND_COMPLETED | A refund was successfully processed |
PG_REFUND_FAILED | A refund request failed |
PG_REFUND_ACCEPTED | PhonePe Payment Gateway acknowledged the refund request, but it’s not completed yet |
- The
payloaddetails are explained below:
| Parameter Name | Data Type | Description |
merchantId | String | Merchant ID from which the request was initiated |
orderId | String | Order ID generated by PhonePe Payment Gateway (only for order callbacks) |
originalMerchantOrderId | String | Order ID generated by you (only for order callbacks) |
refundId | String | Refund ID generated by PhonePe PG (only for refund callbacks) |
| merchantRefundId | String | Refund ID generated by you (only for refund callbacks) |
state | String | The current state of the order or refund. |
amount | Long | The amount processed in paisa. |
expireAt | Long | The expiry timestamp in epoch format |
errorCode | String | The error code (only for failed transactions) |
detailedErrorCode | String | A more detailed error code (only for failures) |
metaInfo | MetaInfo | Metadata passed during order initialization |
paymentDetails | List<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.
| Attribute | Data Type | Description |
transactionId | String | Merchant ID from which the request was initiated |
paymentMode | String | Order ID generated by PhonePe Payment Gateway (only for order callbacks) |
timestamp | Long | Order ID generated by you (only for order callbacks) |
state | String | Attempted transaction state. It can be any one of the following states: • COMPLETED • FAILED • PENDING |
errorCode | String | Error code (only present when the state is failed) |
detailedErrorCode | String | A more specific error code (only present when the state is failed) |
Exception Handling
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
PhonePeException is thrown when there are errors related to PhonePe SDK. It provides comprehensive error information which can be used for debugging and logging.
| Attribute | Type | Description |
| code | String | The status code of the http response. |
message | String | The http error message. |
| Integer | The status code of the http response. |
data | Map<String, String> | The details of the error that happened while calling PhonePe. |
<?php
use PhonePe\common\exceptions\PhonePeException;
try {
// API call
} catch (PhonePeException $e) {
echo "Error: " . $e->getMessage() . "\n";
echo "HTTP Status Code: " . $e->getHttpStatusCode() . "\n";
}
?>What’s Next?
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.