Facebook messenger platform webhook Verify Token not validated - facebook

I've created a facebook app on facebook developers
I've setup a local rails server and exposed it to public internet using ngrok. I'm receiving facebook's webhook validation GET request and I'm returning the hub_challenge code in response. The response status code is also 200. I've provided a secret Verify Token which is required to set up a messenger webhook. But after all this I'm getting error
The Callback URL or Verify Token couldn't be validated. Please verify
the provided information or try again later.
I've checked that the request is received and the response being sent back to the facebook server, but don't know why it fails and says Verify Token couldn't be validated. Is it some special token that I have to get from somewhere from facebook messenger platform? Currently I've provided it my own secret token. Any help will be appreciated. Thanks

when I verify Facebook Webhook with my website i got that kind error
The URL couldn't be validated. Response does not match challenge, expected value="1421256154", received="1421256154\u003Clink rel=..."
My code
public function verify_token(Request $request)
{
$mode = $request->get('hub_mode');
$token = $request->get('hub_verify_token');
$challenge = $request->get('hub_challenge');
if ($mode === "subscribe" && $this->token and $token === $this->token) {
return response($challenge,200);
}
return response("Invalid token!", 400);
}
my code everything is ok .I am using laravel thats why APP_DEBUG=true defalt when I change it APP_DEBUG=false its working and my problem solved.

Related

Request parameters not coming in facebook webhook callback url

I want to integrate Facebook leads into my WordPress website.
I went through all instructions given on Facebook url https://developers.facebook.com/docs/marketing-api/guides/lead-ads/quickstart/webhooks-integration
But I'm not getting request parameters when webhook trying to verify webhook on page subscription.
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token']
Also request body is blank.
file_get_contents('php://input');
Thanks to help in advance.

Facebook Messenger webhook setup, but not triggered

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?
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
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,
the examples use https://graph.facebook.com/v2.6/me/.. but I seemed to need to use, https://graph.facebook.com/v2.6/:pageid
the access token is the messenger access token, not your API access token
if your webhook throws a error, Facebook will stop sending you messages for a while
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?
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.
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'
];
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.
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...
You can link multiple pages to your app, under Add or Remove Pages tab in your Messenger Settings

HWIOAuthBundle, how to manually authenticate User with a Facebook access token?

I have a website (Symfony2) with HWIOauthBundle used to connect with Facebook and everything works fine.
Now, I'm trying to build an iOS app with Cordova and Ionic framework (AngularJS) and I want to authenticate my user with Facebook :
With $cordovaFacebook, I authenticate my user and get a valid Facebook access token, that's ok
I try to use this access token to authenticate my user on the server-side with HWIOauthBundle :
GET http://..../login/facebook?code=MY_FACEBOOK_ACCESS_TOKEN
Symfony rejects my request with this log :
INFO - Matched route "facebook_login" (parameters: "_route": "facebook_login")
INFO - Authentication request failed: OAuth error: "Invalid verification code format."
So my question is : how can I authenticate my user on both front and back end with Facebook connect?
Thanks :)
I've also been wondering how to implement a server side login with the HWIOAuthBundle.
I didn't find any solution on the web, so I coded the functionnality based on hints I've read on the net.
Basically, you have to :
authenticate the user on your app
make an http request to your server with the Facebook token.
ont the server side, check if the token is for your Facebook app, and retrieve the user's Facebook ID.
Get your user from the DB based on the fetched ID.
Here's my Symfony controller:
public function getSecurityFbAction($token)
{
// Get the token's FB app info.
#$tokenAppResp = file_get_contents('https://graph.facebook.com/app/?access_token='.$token);
if (!$tokenAppResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Make sure it's the correct app.
$tokenApp = json_decode($tokenAppResp, true);
if (!$tokenApp || !isset($tokenApp['id']) || $tokenApp['id'] != $this->container->getParameter('oauth.facebook.id')) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Get the token's FB user info.
#$tokenUserResp = file_get_contents('https://graph.facebook.com/me/?access_token='.$token);
if (!$tokenUserResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Try to fetch user by it's token ID, create it otherwise.
$tokenUser = json_decode($tokenUserResp, true);
if (!$tokenUser || !isset($tokenUser['id'])) {
throw new AccessDeniedHttpException('Bad credentials.');
}
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('facebookId' => $tokenUser['id']));
if (!$user) {
// Create user and store its facebookID.
}
// Return the user's JSON web token for future app<->server communications.
}
I throw the Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException exceptions to handle login errors on my app.
Of course, you really should use https because you will be exchanging sensible information.
I don't know if it's the best way to do it but it works well.
Hope it helps !
Well, I think that Symfony doesn't actually reject your request. Facebook is. I'm not sure if this might help, but I know that a bunch a problems can happen when dealing with the Facebook Auth :
Do you know if the tool sends, along with the code parameter, a redirect_uri parameter ? If so :
Did you check that your redirect_uri HAS a trailing slash at the end ? See this
Silly question, but did you check that your app_id is the same when you got authorized via Cordova ?
Check that your redirect_uri DOES NOT have any query parameter.
Check that the redirect_uri that you use during the whole process is the same all the time.
Overall, it seems that your issue is almost all the time related to the redirect_uri URI format.

Facebook api - invalid token

tried to send post to facebook api to scrape my page at load.
http://i.stack.imgur.com/3Jd0y.png
what is wrong with my code?
This is how you use FB.api:
FB.api('/', 'post', {
id: 'url-to-scrape',
scrape: true
}, function (response) {
console.log(response);
});
Not sure where you got that code example from, but you should always take a look at the Facebook docs.
I you are getting invalid token means your token is not correct let me tell you how to generate token it is simply by combining your app id and app secret gotten on Facebook developers app dashboard after you have signed up check here and read url and to check errors faster on your code api, download post man here www.getpostman.com, put in your api call code in the url bar and hit send it will tell you your error. Then to get token for facebook fancount,pageid,likescount, you can do a search for more info on graph.facebook.com on google. contact me if there is problem.
$appid = "xxxxxxxxxxxxxxx";
$appsecret = "yyyyyyyyyyyyyyyyyyyyyyyyy";
//get it from your dashboard
$token = $appid .|. $appsecret key

Soundcloud API error 401 when i use a token later than just after i get it

I would like to understand why i get "The requested URL responded with HTTP code 401." when i try to put a description whith an access token.
The weird think is it works fine when i do that just after getting the access_token (session) from the user, but when i store the token, and try to launch the same code later, it fail !
Apparantly, there is a problem with the token, because i can access the soundcloud description without token, but if i use this method: $soundcloud->setAccessToken($token); before getting the tracks datas, i can't access them anymore...
Here is the code:
require_once 'soundcloud/Soundcloud.php';
$soundcloud = new Services_Soundcloud(SOUNDCLOUD_CLIENT_ID, SOUNDCLOUD_CLIENT_SECRET, SOUNDCLOUD_REDIRECT_URI);
$soundcloud->setAccessToken($session_token);
try
{
$track = json_decode($soundcloud->get('tracks/'.$media_id), true);
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e)
{
exit($e->getMessage());
}
try
{
$response = json_decode($soundcloud->put(
'tracks/'.$media_id,
'test',
array(CURLOPT_HTTPHEADER => array('Content-Type: application/xml'))), true);
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e)
{
exit($e->getMessage());
}
This code works when i just get the token but fail if i launch it a few days later...
Thanks for help !
Where is $session_token coming from in this example? Depending on how you generated the access token, one of two things are happening:
You are not sending the correct access token.
The access token you are sending has expired.
If it's 2, you should have gotten a refresh token when the user authorizes your app. The PHP SoundCloud SDK has a accessTokenRefresh() method that you can use in this scenario.
You need a non-expiring token.
When authorizing, the param scope defaults to "*".
Specify the scope and retrieve the token like this:
$soundcloud->getAuthorizeUrl(array('scope'=>'non-expiring'))
See: http://developers.soundcloud.com/docs/api/reference#connect
(Quite old question, but just ran into this myself. When the token is expired you don't get feedback from the API other then the 401 error, leaving you in the dark.)