Search code examples
webhookssquare-connect

Square-Connect Webhook PHP post no data


I have Square-Connect Webhooks endabled. I am receiving POST's to my server script. Yet the $_POST array seems to be empty.

Here is my code:

<?php
  $sRM = $_SERVER['REQUEST_METHOD'] ;
  $sH = null ;
  
  if ( 'PUT' == $sRM )
  {
    $sH = file_get_contents( 'php://input' ) ;
  }
  else if ( 'POST' == $sRM )
  {
    $sS = '' ;
    
    foreach( $_POST as $sK => $sV )
    {
      $sH .= $sK.'=>'.$sV ;
      $sS = ', ' ;
    }
  }
  
  if ( ConnectDB() )
  {
    $_SESSION[ 'DB' ]->real_escape_string( trim( $sH ) ) ;  //  Prevent SQL Injection
    $rR = $_SESSION[ 'DB' ]->query( 'INSERT INTO `Hooks` ( `Method`,`Message` ) VALUES ( "'.$sRM.'", "'.$sH.'" ) ;' ) ;
  }
?>

Thanks, Rob


Solution

  • The square docs state that the POST body will be in JSON format, so PHP will not parse it like a form and populate the $_POST array. You need to do something like this:

    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    

    as described in the answers to Reading JSON POST using PHP.