Verify GitHub Webhooks with PHP

Craig Blanchette on Google+ on May 28th 2014

The following is some basic code to get you going with verifying your GitHub Hooks. I've seen some other examples that just to check the existence of the payload and then execute the webhook regardless. If you're planning on using anything valuable in the payload then you should be sure it's from who it's supposed to be from. If someone found your webhook for some reason they could spam it causing your code to keep running or send a bogus payload. 

You can set a key when you setup the webhook and calculate the same hash in your script, if they match then there's a much more likely chance the source is trusted.

Use the $secret when you create your hook on GitHub.com

  1. $secret = '[some secret here]';
  2.  
  3. $headers = getallheaders();
  4. $hubSignature = $headers['X-Hub-Signature'];
  5.  
  6. // Split signature into algorithm and hash
  7. list($algo, $hash) = explode('=', $hubSignature, 2);
  8.  
  9. // Get payload
  10. $payload = file_get_contents('php://input');
  11.  
  12. // Calculate hash based on payload and the secret
  13. $payloadHash = hash_hmac($algo, $payload, $secret);
  14.  
  15. // Check if hashes are equivalent
  16. if ($hash !== $payloadHash) {
  17. // Kill the script or do something else here.
  18. die('Bad secret');
  19. }
  20.  
  21. // Your code here.
  22. $data = json_decode($payload);