Validate the v3 request signature HUBSPOT using PHP

I am trying to connect a Hubspot CRM with my internal application, to send values from Hubspot to my app using Webhooks, with Authentication: Hubspot app id. But the HTTP_X_HUBSPOT_SIGNATURE_V3 does not match my hashed string.

Here is the code:

<?php $request_method = $_SERVER['REQUEST_METHOD']; //returns: POST
$request_uri = $_SERVER['REQUEST_URI']; // returns: /hubspot/webhook.php
$request_body = file_get_contents('php://input'); 
//returns: {"email":"test@gmail.com","field1":null,"field2":null,"field3":null,"field4":null}
$request_timestamp = $_SERVER['HTTP_X_HUBSPOT_REQUEST_TIMESTAMP'];// returns: 1679654017505
$string = utf8_encode("{$request_method}{$request_uri}{$request_body}{$request_timestamp}"); //POST/hubspot/webhook.php{"email":"test@gmail.com","field1":null,"field2":null,"field3":null,"field4":null}1679654017505
$HUBSPOT_APP_SECRET = '...';
$hash = hash_hmac('sha256', $string, $HUBSPOT_APP_SECRET, true); //returns odd characters
$encoded = base64_encode($hash);
$valid = hash_equals($_SERVER['HTTP_X_HUBSPOT_SIGNATURE_V3'], $encoded);
if($valid == 1) {
 echo 'yes';
}else {
 echo 'no';
}?>

In the end, it returns ‘no’. I do not understand what I am doing wrong. Please help!

Hey, @SFlorina :waving_hand: Thanks for reaching out. One place to get started is this post from our community member @tominal — PHP and v3 Signature.

Best,

Jaycee

Hello. Thank you for the answer.

I read the post you gave me, and I modified my code to look like the one in that post. Still not working well.

<?php
$document = ‘POSThttps://www…/hubspot/webhook.php{“email":"test@test.com”,“field1”:null,“field1”:null,“field1”:null,“field1”:null}1679654017505’;
$secret = ‘pat-eu1-..’;
$hash = hash_hmac(‘sha256’, $document, $secret, true);

$encoded = base64_encode($hash);
$valid = hash_equals($_SERVER[‘HTTP_X_HUBSPOT_SIGNATURE_V3’], $encoded);
if($valid == 1) {
echo ‘yes’;
}else {
echo ‘no’;
}
?>

But I understand that the secret key that the client gave me and starts with ‘pat-eu1’ in not the right key, ‘The secret keys the documentation is referring to are developer apps where you are given a client ID and client secret key.’.

I will ask for the proper key and I will try again.

Thank you!