45

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?

dmulter
  • 2,608
  • 3
  • 15
  • 24
James
  • 17,965
  • 11
  • 91
  • 146

7 Answers7

65

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
Mukarram Khalid
  • 2,115
  • 1
  • 16
  • 20
  • 1
    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. – Rick Love Jul 24 '16 at 03:14
  • 3
    @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. – Mukarram Khalid Jul 25 '16 at 04:31
  • 1
    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? – kkica Mar 28 '19 at 13:11
  • 1
    `Make sure the Facebook user` did the trick! I was stuck for 3 hours in there! – Tamil Vendhan Kanagarasu Aug 16 '23 at 06:26
16

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?

James
  • 17,965
  • 11
  • 91
  • 146
  • Just to remind you that you can accept your own answer (http://blog.stackoverflow.com/2009/01/accept-your-own-answers/). This removes it from 'unanswered' categories. – gar Apr 29 '16 at 15:20
  • "if your webhook throws a error, Facebook will stop sending you messages for a while" was a lifesaver for me – Jason Logsdon Nov 16 '19 at 14:09
8

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.

Kunal Pal
  • 545
  • 8
  • 21
elMarquis
  • 7,450
  • 4
  • 38
  • 42
  • 1
    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. – 尤川豪 Jun 23 '18 at 06:22
  • 1
    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? – Marchy Aug 07 '19 at 18:30
  • @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. – elMarquis Aug 09 '19 at 01:39
  • 1
    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? – shanti Jan 14 '21 at 09:19
  • @shanti How did you fix your error? I'm using ngrok to expose my local port. It connects to the Facebook webhook. But if I send any message to Facebook, it doesn't sent a http request to my server. I assume I'm facing the same problem as you. – Maharun Afroz Mar 12 '23 at 14:25
5

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'
    ];
SlowSuperman
  • 488
  • 1
  • 8
  • 14
  • man you saved me im trying to find solution since long long time and your answer slove it thanks a lot – softya Jul 06 '22 at 19:55
1

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.

Rajesh
  • 934
  • 12
  • 23
0

If you still can not solve your problem, try to check and update your Privacy policy link.

I updated worry link to Privacy policy, and Facebook show 404 error even the webhoob is verified...

Kin Cheng
  • 1
  • 1
-1

You can link multiple pages to your app, under Add or Remove Pages tab in your Messenger Settings

QuickSilver
  • 3,915
  • 2
  • 13
  • 29