Search code examples
phprubylaravelapitypeform

Signature in ruby to php


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?


Solution

  • 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!');
         }        
        }  
      }