Facebook Messenger webhook setup, but not triggered

32,731

Solution 1

So my issue was I was calling GET when trying to subscribe instead of POST

https://graph.facebook.com/v2.6/:pageid/subscribed_apps?access_token=:token

GET will return the current subscriptions (empty {[]}), POST returns {"success" : "true"}

Some other gotchas I hit were,

One thing I'm still puzzled over is how to support managing multiple pages from one Facebook app? Anyone know the answer to this, or do you need to create anew app and get permission for every page?

Solution 2

I have recently worked with the new chat bot API and there's a lot that can go wrong. So, here are some Ideas.

  • Make sure you've verified your webhook under the product settings tab.
  • subscribe your app to the page using your page access token. It returns {"success" : "true"} if everything goes right.

Important

  • Make sure the Facebook user from which you're sending the message is listed as the Admin or Developer or Tester in your app roles (https://developers.facebook.com/apps/YOUR_APP_ID/roles/). Messages from other users won't work unless your app is approved and publicly released.

  • Have you received any call back from the facebook api ? or is it just the messages? Take a look at the logs of your web server and check if you're getting any hits on the webhook. Also check the error logs.

  • Try hitting your webhook manually and see if it responds. You can use curl to generate a manual request. This is what the request from Facebook looks like:

Command:

curl -i -X POST -H 'Content-Type: application/json' -d '{"object":"page","entry":[{"id":43674671559,"time":1460620433256,"messaging":[{"sender":{"id":123456789},"recipient":{"id":987654321},"timestamp":1460620433123,"message":{"mid":"mid.1460620432888:f8e3412003d2d1cd93","seq":12604,"text":"Testing Chat Bot .."}}]}]}' https://www.YOUR_WEBHOOK_URL_HERE

Solution 3

Another thing which can prevent some responses from being sent to your webhook is when a message type gets blocked in a queue.

If a particular message type is delivered to your webhook but doesn't receive it's 200 response within 20 seconds it will keep trying to send you that message again for hours.

What's more facebook messenger will stop sending you any more of that message type until the first one has been acknowledged. It essentially puts them into a queue.

In the meantime, other message types will continue to send fine.

This happened to me when I accidentally introduced an undeclared variable inside my code which handled standard messages. It meant that postback messages all worked fine, but quick replies and normal messages would never get sent to my webhook. As soon as you fix the error, they all come piling through at once.

As mentioned by others, using a service such as POSTMAN to send messages to your webhook is a great way to find this kind of errors, otherwise, messenger just fails silently.

Solution 4

Exluding of your bot rout from CSRF verification can help if you use framework. This helps for me (Laravel 5.4, app/Http/Middleware/VerifyCsrfToken.php):

protected $except = [
        '/your_bot_route'
    ];

Solution 5

I too had the same issue when I was working on a bot couple of days ago. Followed this gist and modified the code as below, and everything is working fine.

public function index()
    {

        $challenge = $_REQUEST['hub_challenge'];
        $verify_token = $_REQUEST['hub_verify_token'];
        // Set this Verify Token Value on your Facebook App
        if ($verify_token === 'MyVerifyToken!') {
            echo $challenge;
        }
        $input = json_decode(file_get_contents('php://input'), true);
        // Get the Senders Graph ID
        $sender = $input['entry'][0]['messaging'][0]['sender']['id'];
        // Get the returned message
        $message = $input['entry'][0]['messaging'][0]['message']['text'];
        //$senderName = $input['entry'][0]['messaging'][0]['sender']['name'];

        $reply="Sorry, I don't understand you";

        switch($message)
        {
            case 'hello':
                $reply = "Hello, Greetings from MyApp.";
                break;
            case 'pricing':
                $reply = "Sample reply for pricing";
                break;
            case 'contact':
                $reply = "Sample reply for contact query";
                break;
            case 'webinar':
                $reply = "Sample reply for webinar";
                break;
            case 'support':
                $reply = "sample reply for support";
                break;
            default:
                $reply="Sorry, I don't understand you";
        }
        //API Url and Access Token, generate this token value on your Facebook App Page
        $url = 'https://graph.facebook.com/v2.6/me/messages?access_token=MYACCESSTOKEN';
        //Initiate cURL.
        $ch = curl_init($url);
        //The JSON data.
        $jsonData = '{
        "recipient":{
        "id":"' . $sender . '"
        },
        "message":{
            "text":"'.$reply.'"
            }
        }';
//Tell cURL that we want to send a POST request.
        curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
//Set the content type to application/json
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request but first check if the message is not empty.
        if (!empty($input['entry'][0]['messaging'][0]['message'])) {
            $result = curl_exec($ch);
        }

    }

Note : Ensure the user roles within the application page to get the responses from the web hook. I have set Administrator, and Tester user. Only there were able to get the responses. Other users will get once this is published. Also, change verify token, and page token accordingly.

There is an option that is asked while publishing the app about the number of business this bot going to be used by. But I have no idea how to use it. Still searching that though.

Share:
32,731
James
Author by

James

President of Paphus Solutions - Your experts in intelligence automation. Paphus Solutions Inc. is a Canadian corporation that specializes in intelligence automation products and services. Paphus Solutions - www.paphussolutions.com Bot Libre for Business - Commercial bot hosting and services - www.paphuslivechat.com Bot Libre! - Free bot hosting - www.botlibre.com Llive Chat Libre! - Free live chat, and chatroom hosting - www.livechatlibre.com Forums Libre! - Free embeddable forums - www.forumslibre.com BotLibre.org - Open source bot platform - github.com/BotLibre I am a former architect of Oracle TopLink and committer on the open source EclipseLink product from the Eclipse Foundation. I have over 20 years of experience in object persistence and enterprise software development. For more information see my blog Java Persistence Performance, on follow me on Twitter, or Google+.

Updated on July 18, 2022

Comments

  • James
    James almost 2 years

    So I'm trying to setup a bot for the new Facebook Messenger API.

    I'm following the quickstart.

    I setup the webhook ok, and see it in my webhooks,

    I called this:

    https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=%3Ctoken%3E
    

    and it did not throw any errors,

    But when I go to the Page that I generated the access token on, and send a message, it does not call my webhook. I check the httpaccess, and it does not call it.

    Any way to debug this or any ideas?

    Also, one thing I'm still puzzled over is how to support managing multiple pages from one Facebook app? Anyone know the answer to this, or do you need to create anew app and get permission for every page?

  • gar
    gar about 8 years
    Just to remind you that you can accept your own answer (blog.stackoverflow.com/2009/01/accept-your-own-answers). This removes it from 'unanswered' categories.
  • Rick Love
    Rick Love almost 8 years
    Another problem: The PageId must be the numeric page id, not the friendly url id. The only way I could find this was by viewing page source and searching for page_id in the javascript.
  • Mukarram Khalid
    Mukarram Khalid almost 8 years
    @Rick ... or you can simply click 'About' tab of your page and your 'Facebook Page ID' is listed at the bottom of the 'Page Info' section.
  • 尤川豪
    尤川豪 almost 6 years
    Hey! Thank you very much! You save my day! Spent 10+ hours on a messenger API issue, saw your answer and realized my message was blocked by FB continuously because I didn't respond with status code 200.
  • kkica
    kkica about 5 years
    my app is live, not in development. I can trigger the webhook when i write from an admin role but not when i write from another fb account. WHat could be the problem?
  • Marchy
    Marchy almost 5 years
    How do you get Messenger to resume firing the queue? It seems that the queue is stuck and the webhook doesn't fire any other events. Is there any way to get Messenger to 'retry' once the code is fixed?
  • elMarquis
    elMarquis almost 5 years
    @Marchy It should already be continuing to fire those requests at your app. There's nothing you need to do to tell it to retry. Most likely it's not getting a satisfactory 200 response. I suspect it'll eventually give up, but at that point there would no longer be a queue and it wouldn't be blocked. See if you can replicate what facebook is sending to your webhook and send it yourself using CURL or postman and check the response. I suspect there's still an error.
  • Jason Logsdon
    Jason Logsdon over 4 years
    "if your webhook throws a error, Facebook will stop sending you messages for a while" was a lifesaver for me
  • shanti
    shanti over 3 years
    My app is live and most probably some messages are stuck in the queue. Occasionally, one or two messages are coming. How to kill those messages so that at least new ones get sent?