How to subscribe to real-time updates for a Facebook page's wall - facebook

Facebook's real-time updates docs now say that you can get the feed for a page:
You can subscribe to the page's feed in the same way you subscribe to
a user's feed - the subscription topic should be 'user' and the
subscription field should be 'feed'
My understanding of this is that I need to post to the graph API to subscribe as such:
curl -d \
"object=user&fields=feed&callback_url=$CALLBACKURL&verify_token=$SECRET" \
"https://graph.facebook.com/$PAGEID/subscriptions?access_token=$OAUTHTOKEN"
(This is a bash script.) Here $CALLBACKURL is set up correctly following their example code. (At least I think it's correct -- I can successfully add subscriptions with it.)
The $OAUTHTOKEN is the one for my Facebook App.
And the $PAGEID is the facebook object id of the page I'd like to get realtime updates for.
When I do this, the call appears to work -- no error message. My callback gets called. But I certainly don't get notified when something happens on the page's feed.
So what's missing? Does the page need to install the app whose oauth token I'm using? Or do I somehow need to get an oauth token for the page itself by logging in as the page?

I do not know if this can help you but I'll tell you where I am for real-time update page feed:
(permissions : manage_page,offline_access,read_stream)
your application must be linked to the page (then install the application but not required to have a tab ex. create tab https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&method=POST&access_token=PAGE_ACCESS_TOKEN and delete tab
TAB_ID=PAGE_ID.'/tabs/app_'.APP_ID;
https://graph.facebook.com/TAB_ID?method=DELETE&access_token=PAGE_ACCESS_TOKEN)
function page_access_token($page_id,$access_token){
$page_token_url="https://graph.facebook.com/" .
$page_id . "?fields=access_token&" . $access_token;
$response = file_get_contents($page_token_url);
$resp_obj = json_decode($response,true);
$page_access_token = $resp_obj['access_token'];
return $page_access_token;
}
function page_tabs_create($page_id,$app_id,$page_access_token){
$page_settings_url = "https://graph.facebook.com/" .
$page_id . "/tabs?app_id=".$app_id."&method=POST&access_token=" . $page_access_token;
$response = file_get_contents($page_settings_url);
$resp_obj = json_decode($response,true);
return $resp_obj;
}
function page_tabs_delete($tab_id,$page_access_token){
$page_settings_url = "https://graph.facebook.com/".$tab_id."?method=DELETE&access_token=" . $page_access_token;
$response = file_get_contents($page_settings_url);
$resp_obj = json_decode($response,true);
return $resp_obj;
}
Subscription: to subscribe must be like a "user" and therefore object = user fields = feed but you have to add new fields because otherwise it receives the comments and likes the wall so you must add "status" in order to receive the articles posted (my problem is to get other content such as links I have managed to add "link" as fields but I am not receiving notifications when a link is posted)
$param = array ('access_token' => $ access_token,
'object' => 'user',
'fields' => 'feed, status, link'
'callback_url' => 'http:// ******** fbcallback.php'
'verify_token' =>'***********',
'include_values' => 'true');
POST
https://graph.facebook.com/APP_ID/subscriptions
my English is not very good but I hope it will help you, on my side I'm still looking for really all updates to the wall (links, video ...)

I have been researching on this and i am getting the pushes for pages too.
while subscribing make sure that object = user and fields = feed, status is present.
Make sure that application is added to your page, then only you will receive the update.
Response received from facebook is as below :-
{"entry":[{"id":"*******","uid":"*****","time":1332940650,"changed_fields":["status"]}],"object":"user"}
where **** is my pageId.
The above push is received on adding a new post , as you can see the changed_feild is status , but when we post on wall the changed_fields comes as feed. Below link helped me in receiving pushes for the page.
http://bugs.developers.facebook.net/show_bug.cgi?id=18048

Firstly, subscription to real-time update for page/feed doesn't work.
See: http://bugs.developers.facebook.net/show_bug.cgi?id=18048
Does the page need to install the app whose oauth token I'm using?
Yes
Or do I somehow need to get an oauth token for the page itself by logging in as the page?
If i correctly understand you, you need only app access_token
https://graph.facebook.com/oauth/access_token?client_id=your_app_id&client_secret=your_secret&grant_type=client_credentials

I first started reading the docs about real-time updates thinking that it could delivery the actual data. But, as I realized, that's not the purpose.
Real-time updates are just to tell you that something has changed, and once it happens, you can call the api with the conventional method.
Also, seems like there's an error on this part the subscription topic should be 'user' and the subscription field should be 'feed'. The subscription topic, actually, should be 'page'. (Have you thought the same?)
And by subscribe on page feed as the same as user feed, means that you can get update notifications, not the data itself.
Not sure if this is a common mistake, but I'm posting it just in case.
--
Currently I'm working on a data mining tool that will need real-time updates. But first, I'm focused on the data itself, so I can't post any examples yet. (I'll edit this answer when implementing this part)
What I can say about your issue is:
1) Look that your $PAGEID isn't correct. Actually it's your APPID instead.
2) After subscribing, have your subscription appeared on the list when calling https://graph.facebook.com/<app-id>/subscriptions?access_token=... ?
3) With user subscription, does it work? Or is it just with pages?

For this you need to set up an endpoint URL that receives both HTTP GET (for subscription verification) and POST (for actual change data) requests from Facebook.
Then you should make a POST to the graph API url https://graph.facebook.com/<app-id>/subscriptions?access_token=<access_token> to subscribe, and be ready to handle the verification request.
Then to list subscriptions, just perform a GET request on the same url, https://graph.facebook.com/<app-id>/subscriptions?access_token=<access_token>, which returns a JSON-encoded content that lists your subscriptions, up to one per object type.

Before you start waiting for the notifications you should check if the URL is actually being hit or not by FB
Check The Output of Following:
"https://graph.facebook.com/".FACEBOOK_APP_ID."/subscriptions?".$appToken."&client_secret=".FACEBOOK_SECRET;
This shall return the callback_url if set correctly !

Related

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

How to login user from inside Facebook Page Tab and get access_token on server side to post a carousel to the feed?

I have a Page Tab facebook app. I want to post to users timeline from it.
After login on client side with javascript sdk (I use angularjs module for that Ciul/angular-facebook (sorry, cannot post github link here)):
https://gist.github.com/Sevavietl/7e363fdfd0e714a12a43
I retrieve access_token on server side and trying to post a carousel to the users feed:
https://gist.github.com/Sevavietl/cec5fa434837312adfd3
I have two problems:
While first call I get
Graph returned an error: (#210) Param id must be a page.
After browsing, I found that this can be caused by wrong token usage. Not user_access_token. But I login the user on the client side.
And for next calls I get
Graph returned an error: This authorization code has been used.
Again, after browsing, I found that token can be used only once in order to be OAuth compliant.
Please, advise me how to do this right?
Thank you in advance.
Best regards,
Vsevolod
After spending some time on this, I am writing my solution, as it was not really obvious, at least for me. But, actually, all info is present in the documentation.
Starting with problem number 2: And for next calls I get Graph returned an error: This authorization code has been used.
As it was mentioned in the comments, I indeed was confusing access_token with authorization code. As I understand in really simplified form, the mechanism is:
When you login with facebook-javascript-sdk it writes authorization code to cookies.
Then on the server side you can retrieve access_token from javaScriptHelper available in facebook-php-sdk. This helper has getAccessToken() method, which retrieves access_token using authorization code from cookies. This is the place where I was confused. I was trying to use getAccessToken() on every request. As requests were made with AJAX the authorization code was not changed, and as you can use it only once I was getting an error. The solution to this was pointed in many places on the Internet, but somehow I was able to misunderstand this.
Here is the code excerpt that uses sessions to store access_token, and uses getAccessToken() method only if access_token is not set in the session.
$fb = new Facebook([
'app_id' => $widget->app_id,
'app_secret' => $widget->app_secret,
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getJavaScriptHelper();
if ($request->session()->has('facebook_access_token')) {
$accessToken = $request->session()->get('facebook_access_token');
} else {
$accessToken = $helper->getAccessToken();
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$request->session()->put('facebook_access_token', (string) $longLivedAccessToken);
$request->session()->save();
}
if ($accessToken) {
$fb->setDefaultAccessToken($accessToken);
} else {
die('No Access Token');
}
I use Laravel, so the session handling is not framework agnostic. This code is only for example, it is better to create service and move logic there.
Now. About the first problem: While first call I get Graph returned an error: (#210) Param id must be a page.
Again I was confusing two things '{user-id}/feed' and '{page-id}/feed'. My aim was to post a carousel with images and links. To create a carousel you have to provide child_attachments in the fields array. While you can send a Post like this to '{page-id}/feed', you cannot do so for '{user-id}/feed'. So at the moment you cannot post a carousel to users feed.
So when Graph Api was getting a Post data applicable for '{page-id}/feed', it was assuming that I have passed the {page-id}. And when getting the {user-id} instead, the Graph Api yelled back "(#210) Param id must be a page.".

How do I remove the Facebook login prompt when displaying images pulled with graph api on a page?

I recently started playing around with Facebook graph API and wanted to integrate images pulled from my Facebook page to display on my website. I have the images displaying properly but my problem is whenever anyone tries to view the page they are asked to log into Facebook first. Is there any way to display the images without prompting the user to log into Facebook?
Here is what I am using to make the session:
$app_id = 'id';
$app_secret = 'secret';
$redirect = 'my webpage';
// init app with app id and secret
FacebookSession::setDefaultApplication($app_id,$app_secret);
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper($redirect);
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
Any help would be appreciated.
Step one: familiarize yourself with the API. Read the docs, and play around with the Graph API Explorer
Step two: the code you provided has nothing to do with what you are trying to achieve (displaying page photos). That code is basically the getting started code used in the docs. If you need help, post the relevant code.
Step three: as mentioned by #CBroe, authenticating the visitor is not needed to display photos from a page. What you might want to explore:
The page admin authenticating your app with the right permissions (maybe manage_pages)
with the user access token you just got, you extend it to long-lived one
then you query the API to get a page access token that won't expire
you store this access token and query the API to get the relevant data and store it (GET /{PAGE-ID}/photos or GET /{PAGE-ID}/albums ... etc)
you show the stored data to your visitors
Notes:
Do not make these calls on client-side ... i.e. reveal your page access token, since you can do this in the backend.
Use the realtime updates to get notified when you should query the API and get new photos instead of periodically querying the API to pull new photos, or even worst, querying the API on each user visit.

Facebook Graph API - Events ticket_uri

I am trying to add a ticket_uri to the event that I am creating.
I enabled the "Events Timezone" migration in my app settings.
I am posting on behalf of a user that is manager of the page.
Currently it's not working when I create a new event. The new event has no ticket uri.
If I update the new event, just after it's created, the ticket uri works...
Is this a bug or am I doing something wrong?
$fbEvent = $facebook->publish('/events', $event);
if(isset($fbEvent['id']))
{
$facebook->publish('/' . $fbEvent['id'], array('ticket_uri' => 'http://lowiebenoot.be'));
}
Updating right after it's created is just stupid...
You must get a "Page access token" and then post to {page_id}/events. Here's a copy of the steps I've posted a couple of places:
Enable the "Events Timezone migration"
Log into FB as a user that has admin rights on the FB Page that we want events posted to
Use the APPLICATION's ID to build this link to authorize the
managing of pages
https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_SITE_URL&scope=manage_pages,create_event&response_type=token
Exchange token for perm (longer token)
https://graph.facebook.com/oauth/access_token?client_id=MY_APP_ID&client_secret=MY_CLIENT_SECRET&grant_type=fb_exchange_token&fb_exchange_token=(token from step 3)
Visit this page, find the PAGE you want to post and copy the new
access_token https://graph.facebook.com/me/accounts?access_token=
(token from step 4)
Use this last token (from step 5) and the PAGE's ID to post to post
the event per the instructions at
https://developers.facebook.com/docs/reference/api/page/#events
Note that if you create a lot of events, you will "spam" every user who Like'd the page. FB recently added the 'no_feed_story' option to prevent this.

how can I clear the app invite notification on Facebook?

When I use the API to send notification requests, they arrive as expected. However after the user follows the link and accepts the App permissions, the notification persists.
Is there some additional call I need to make to clear the notification? I know it auto expires after some time, but that doesn't seem entirely satisfying.
Am I missing something, or is this really not doable?
This is how you delete app request when users accept an app invitation.
When user accepts an invitation i.e. comes to your application canvas page by clicking on app request notification, Facebook sends comma separated ids in "request_ids" parameter. You can get this requests and delete it using graph api like this :
Here I am deleting the last request id :
$ids = $_GET['request_ids'];
$id_arr = explode(",",$ids);
$count = count($id_arr);
$delete_url="https://graph.facebook.com/".$id_arr[$count-1]. "?access_token=" . $token . "&method=delete";
$result = file_get_contents($delete_url);
echo("Requests deleted (true or false) ?" . $result);
Note request_ids field may contain multiple request id if he has been invited multiple times. I am not sure but you may need to delete all.