Signature in ruby to php

All we need is an easy explanation of the problem, so here it is.

I have create api to recive data of Typeform(surveys https://www.typeform.com/). It works fine.
But, in secure webhooks, https://developer.typeform.com/webhooks/secure-your-webhooks/, shows example of how create signature in ruby, to compare in request.

In laravel i use this:

$body = $req->getContent();
$sig_internal = base64_encode(hash_hmac('sha256', 'testing', $body, true));

My “secret” configured in webhooks of the typeform is “testing”.
But the values is different always.
Somebody have try this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Before running the code make sure that you set your secret properly with Typeform:
How to set up your webhook

More info here:
https://developer.typeform.com/webhooks/secure-your-webhooks/

Once that’s done let’s jump into the code. I paste here what you need to do step by step:

<?php

  namespace App\Http\Controllers;
  use Illuminate\Http\Request;

  class WebhookController extends Controller
  {
     public function index(Request $request){

     // Get your data (toString) and the typeform signature
     $data = (string) $request->getContent();
     $typeformSignature = $request->header('typeform-signature');        

     // Set your key 
     $key = 'test'; // <-- In prod I recommend adding it to the .env file and referring it here 

     // Run your hash
     $hashed = hash_hmac('sha256', $data, $key, $raw_output = TRUE);

     // Encode to Base64
     $base64 = base64_encode($hashed);

     // Append to string
     $endValue = "sha256=". $base64;

     // This bit here will output stuff to your console if you are running artisan
     error_log($endValue);
     error_log($request->header('typeform-signature'));

     // If it's good it should praise the good Bro, otherwise you are a bad bro. :) 
     if($request->header('typeform-signature') === $endValue){
        error_log('Well done bro!');
     } else {
        error_log('Sorry bro!');
     }        
    }  
  }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply