How to fetch response from a callback URL using php?

2.6k views Asked by At

I want to build a WhatsApp bot, for that, we are using Gupshup WhatsApp bot API, for integration they asked to give a callback URL, so created index.php in cPanel of one domain(https://sample_url/WhatsappBot/index.php), and gave the URL (https://sample_url/WhatsappBot/). As per their API documentation, they will pass a response to that URL, so I want to fetch that. Here is the remaining part of API documentation API documentation2, API documentation3, API documentation4. So I created one curl.php named file, that code is given below.

<?php
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'https://sample_url/WhatsappBot/');
  // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);

  $headers = array();
  $headers[] = 'Content-Type: application/json';

  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $result = curl_exec($ch);

  if (curl_errno($ch)) 
   {
      echo 'Error:' . curl_error($ch) ."\n";
   }
  else
   {
      $result_value = json_decode($result,true,JSON_PRETTY_PRINT);
      echo $result_value;
      // var_dump($result_value);   
   }
 curl_close($ch);
?>

they provided a collection of API for reference, but I am getting the wrong result. In their collection API have the result, Collection API result

but I am getting this, myresult

What is the wrong in this code? Can anyone please help me...

1

There are 1 answers

6
Apollos Geofrey On BEST ANSWER

Your Callback URL should contain a program that receive a POST data as JSON, Go ahead to decode the JSON data, using the data received, proceed with what ever logic you plan to execute.

//this should be in your call back URL index.php

$post_data_expected = file_get_contents("php://input");

$decoded_data = json_decode($post_data_expected, true);

You can your POSTMAN to always test your callback URL to see it behaves the way you expects.