Facebook Messenger webhook setup, but not triggered
Asked Answered
A

7

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?

Alarmist answered 22/4, 2016 at 21:26 Comment(0)
A
17

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?

Alarmist answered 25/4, 2016 at 16:15 Comment(2)
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.Cristen
"if your webhook throws a error, Facebook will stop sending you messages for a while" was a lifesaver for meBobcat
J
68

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 have 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
Jakie answered 25/4, 2016 at 5:40 Comment(4)
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.Dullish
@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.Jakie
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?Leger
Make sure the Facebook user did the trick! I was stuck for 3 hours in there!Multiple
A
17

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?

Alarmist answered 25/4, 2016 at 16:15 Comment(2)
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.Cristen
"if your webhook throws a error, Facebook will stop sending you messages for a while" was a lifesaver for meBobcat
O
9

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.

Olympe answered 23/5, 2017 at 4:56 Comment(5)
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.Pattiepattin
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?Sharice
@Sharice 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.Olympe
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?Quietly
@Quietly 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.Anaesthetize
H
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'
    ];
Hapless answered 6/4, 2017 at 8:48 Comment(1)
man you saved me im trying to find solution since long long time and your answer slove it thanks a lotBeeline
B
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.

Bridge answered 30/4, 2016 at 6:51 Comment(0)
M
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...

Militarize answered 28/3, 2019 at 8:13 Comment(0)
E
-1

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

Erythroblast answered 10/6, 2020 at 7:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.