Search code examples
phpfacebookbotsmessenger

Facebook - Messaging webhook keeps infinitely looping the callback php file


while my page recive any notification .. the callback file infinitely running itself without stopping here is the code:

require_once 'vendor/autoload.php';   
$fb = new \Facebook\Facebook([
  'app_id' => '{app-id}',           
  'app_secret' => '{app_secret}',   
  'graph_api_version' => 'v5.0',
]);
$feedData = file_get_contents('php://input');
$data = json_decode($feedData);
if ($data->object == "page") {   
  try {
    $response = $fb->post(
      '/me/messages',
      array (
        'recipient' => '{
          "id": "{id}"
        }',
        'message' => '{
          "text": "{text}"
        }'
      ),
     $accesstoken
    );
  } catch(FacebookExceptionsFacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
  } catch(FacebookExceptionsFacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
  }
  $graphNode = $response->getGraphNode();  
  }

so the user will infinitely recive the same message without stopping

i tried the solution here infinite loop in a WebHook

anyone can help me with this please to make it run just once? thank you


Solution

  • try {
      // Returns a `FacebookFacebookResponse` object
      $response = $fb->get(
        '/{to_id}?fields=conversations{messages{message}}',
        $accesstoken
      );
    } catch(FacebookExceptionsFacebookResponseException $e) {
      echo 'Graph returned an error: ' . $e->getMessage();
      exit;
    } catch(FacebookExceptionsFacebookSDKException $e) {
      echo 'Facebook SDK returned an error: ' . $e->getMessage();
      exit;
    }
    $idchk = $response->getGraphNode();
    $datachk = json_decode($idchk);
    if (($data->object == "page")&&(strpos($idchk,'hey')=="")) {   
      try {
        $response = $fb->post(
          '/me/messages',
          array (
            'recipient' => '{
              "id": "{to_id}"
            }',
            'message' => '{
              "text": "hey"
            }'
          ),
         $accesstoken
        );
    
        exit;
      } catch(FacebookExceptionsFacebookResponseException $e) {
        echo 'Graph returned an error: ' . $e->getMessage();
    
        exit;
    
      } catch(FacebookExceptionsFacebookSDKException $e) {
    
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
    
    }}
    
        exit;