Created
January 24, 2025 21:10
-
-
Save nicklozon/f51a069628af97d085410932757ec5db to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function validateAdyenWebhookHmac($hmacKey, $notificationData) { | |
// Required fields for HMAC calculation | |
$fields = [ | |
'amount.value', | |
'amount.currency', | |
'eventCode', | |
'eventDate', | |
'merchantAccountCode', | |
'merchantReference', | |
'pspReference', | |
'reason' | |
]; | |
// Construct the signing string | |
$signingString = ''; | |
foreach ($fields as $field) { | |
// Get nested field value using dot notation | |
$value = getNestedValue($notificationData, $field); | |
// Escape special characters | |
$escapedValue = str_replace(['\\', ':', ''], ['\\\\', '\\:', ''], $value ?? ''); | |
// Append to signing string | |
$signingString .= $escapedValue . ':'; | |
} | |
// Remove trailing colon | |
$signingString = rtrim($signingString, ':'); | |
// Calculate HMAC signature | |
$calculatedSignature = base64_encode( | |
hash_hmac('sha256', $signingString, pack('H*', $hmacKey), true) | |
); | |
// Compare with received signature | |
return hash_equals($calculatedSignature, $notificationData['additionalData']['hmacSignature'] ?? ''); | |
} | |
// Helper function to retrieve nested array values | |
function getNestedValue($array, $key) { | |
$keys = explode('.', $key); | |
$value = $array; | |
foreach ($keys as $nestedKey) { | |
if (!isset($value[$nestedKey])) { | |
return null; | |
} | |
$value = $value[$nestedKey]; | |
} | |
return $value; | |
} | |
// Example usage | |
function exampleAdyenWebhookValidation() { | |
$hmacKey = 'YOUR_HMAC_KEY_HERE'; | |
$notificationData = [ | |
'amount' => [ | |
'value' => '1000', | |
'currency' => 'USD' | |
], | |
'eventCode' => 'AUTHORISATION', | |
'eventDate' => '2024-01-24T12:34:56+01:00', | |
'merchantAccountCode' => 'YourMerchantAccount', | |
'merchantReference' => 'order123', | |
'pspReference' => '1234567890', | |
'reason' => 'Authorised', | |
'additionalData' => [ | |
'hmacSignature' => 'receivedSignatureFromAdyen' | |
] | |
]; | |
$isValid = validateAdyenWebhookHmac($hmacKey, $notificationData); | |
return $isValid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment