Facebook realtime updates, no post update from facebook - facebook-graph-api

I followed the guide realtime updates on facebook.
My application is a tab page.
I'm using the sandbox environment.
Initially set up by the signing of the dashboard.
The callback URL endpoint verify works fine.
I did an post on the page for only test.
But so far (after 24hrs), i received no update post from facebook.
On log apache server, there is no post from facebook too.
My callback script:
<?php
define('UPD_FILE', 'updates.log');
$method = $_SERVER['REQUEST_METHOD'];
global $log_file;
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == 'jogabonito') {
echo $_GET['hub_challenge'];
exit;
}
else if ($method == 'POST')
{
$log_file=UPD_FILE;
$updates = json_decode(file_get_contents("php://input"), true);
logToFile("updates =".print_r($updates));
}
function logToFile($message){
global $log_file;
$hdl = fopen($log_file, 'a') or die ("couldn't open log file");
fwrite($hdl,$message."\n");
fclose($hdl);
}
?>
Grateful for the attention

Your code works (somewhat) fine after some requirements have been met.
You have subscribed successfully for at least one field change.
The user you are testing with has granted your app some or all of the required permissions for the fields you are subscribed for.
If one of the above isn't properly handled you won't be notified about related changes.
On another note I wrote "somewhat" because you are dumping the array content using print_r without specifying that the function should return the data rather than print it. The way you have it right now will result in a "1" result.
What you need should look more like this:
logToFile("updates =".print_r($updates, true));

I was facing the same problem, below solution fixed my problem,
just make an POST request to the following URL
https://graph.facebook.com/PAGE_ID/tabs?app_id=APP_ID&access_token=PAGE_ACCESS_TOKEN
Please replace the values before making a request

Related

Facebook Webhooks. How to create an event that will work on like and unlike?

How to create an event that will work on like and unlike?,
when I create a webhook
object = page callback_url = ”example.com" fields = feed verify_token =
hub_verify_token
verification callback_url passes and the answer is tapped
{ “success”: true }
But after like or unlike on callback_url nothing is sent.
The events that I have used before :
edge.create and edge.remove.
http://i.imgur.com/xK5C4IK.png
Help please!
There is a solution to the problem:
Details here: https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/
Code example in the JavaScript SDK:
/* make the API call */
FB.api(
"/{page-id}/subscribed_apps",
'POST',
{
"object":"page",
"callback_url":"https://example.com/callback",
"fields":"likes",
"verify_token":"my_token_code",
"access_token" : "you_access_token"
}
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
but unlike for the page does not work (((
what do you think about it?
There is a list of all webhook fields in the docs: https://developers.facebook.com/docs/graph-api/webhooks/reference/page/
There is no specific webhook about likes/unlikes. According to this article, it should be possible though: https://developers.facebook.com/blog/post/2017/11/07/changes-developer-offerings/
The feed hook may only deliver likes to posts:
Describes nearly all changes to a page's feed, such as posts, shares,
likes, etc. The values received depend on the types of changes made to
the page's feed.

Facebook Messenger Platform -> Subscribed Apps with graph-api not working for me

I am trying to develop one-click-integration support for my bot, which will include FB messenger.
For the FB messenger I did the following:
Followed the "quick-start" guide and created a Facebook App.
Followed the "facebook-login" tutorial and deployed a facebook login process which works with permissions for:
- public_profile
- email
- manage_pages
- pages_show_list
- pages_messaging_subscriptions
- pages_messaging
I then used the graph-api of '/me/accounts' to get list of pages name , page ids, and access_token under a "test user" I created in facebook.
Now, I picked a page under this "test user" (with all the permissions), and tried to run this JS code -
FB.api(
`/${page.id}/subscribed_apps?access_token=${page.access_token}`,
function (response) {
console.log(`response = {$JSON.stringify(response)}`);
if (response && !response.error) {
/* handle the result */
}
}
);
The problem: I get response = {"data":[]} , which might be OK, but when I look at the page->settings->Messenger Platform->Subscribed Apps , I don't see any app subscribed there.
By the way, When I run this without the proper access_token , I do get an error #210 ("needs access_token") which is as expected...
Any idea how to subscribe the app properly to the page?
Must say I also tried it with the graph api explorer tool and got the same result...
Thanks in advance :-).
#CBroe got it correct and there were 2 issues:
1. I should have used the POST() instead of GET() method.
2. When you use the graph-api-explorer tool, you will see it works, then role down and get the JS code... problem is the code is a bit confusing since what you get is this:
FB.api(
`/${my_page_id}/subscribed_apps`,
'POST',
{},
function(response) {
// Insert your code here
}
);
but, it should actually be like this:
FB.api(
`/${my_page_id}/subscribed_apps`,
'POST',
{"access_token": `${page_access_token}`},
function(response) {
// Insert your code here
}
);
remeber to take the access_token from the /me/accounts api as I described in my question.
Thanks again to #CBroe for showing me how to solve this :-)

Joomla 3.6 Authentication and Login

I' m having a difficulty in getting a clear view on Joomla (I'm using version 3.6.x) authentication and login.
I've seen many approaches and snippets on how to "Login" in a Joomla site from an external source (which is what i m interesting in).
But what i see after testing and testing (and more testing), is that at the end of the day, you re simply not logged in.
You may have the ability to verify that the user who's attempting to login is a valid registered user and also to be able to retrieve his name, email, phone and blah blah blah but in Joomla backend, this user is still not logged in.
I created a brand new user in Administrator Panel (it shows the user NEVER visited the site), I wrote the login script in external PHP, I "authenticated" the new user a dozen times and when i go back to the Backend, the user still NEVER been there. Not even once.
Which, i guess, it also means that i can't retrieve a list of "active" users, since Joomla can't see them as logged in users.
So what i want to achieve is users to be able to login from outside the Joomla site and to have the ability to know IF they're logged in or not. So I can get a list of them and assign tasks to them.
I guess it has something to do with tokens and cookies. But no matter how much i searched to that direction, i can't find any examples to enlighten me.
Any help (and specially "scripting" help) is much appreciated.
Thank you.
<?php
if (version_compare(PHP_VERSION, '5.3.1', '<')) {
die('Your host needs to use PHP 5.3.1 or higher to run this version of Joomla!');
}
define('_JEXEC', 1);
if (file_exists(__DIR__ . '/defines.php')) {
include_once __DIR__ . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', __DIR__);
require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_BASE . '/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
require_once (JPATH_BASE .'/libraries/joomla/factory.php');
$credentials['username'] = $_GET["usrname"];
$credentials['password'] = $_GET["passwd"];
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select('id, password')
->from('#__users')
->where('username=' . $db->quote($credentials['username']));
$db->setQuery($query);
$result = $db->loadObject();
if ($result) {
$match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);
if ($match === true) {
$user = JUser::getInstance($result->id);
$session =& JFactory::getSession();
echo "<p>Your name is {$user->name}, your email is {$user->email}, and your username is {$user->username}</p>";
$session->set('userid', $user->id);
if ($user->guest) {
echo 'SORRY, NO LOGIN YET...';
} else {
echo 'user is LOGGED IN !';
}
} else {
die('Invalid password');
}
} else {
die('Cound not find user in the database');
}
?>
Joomla log in is handled in authentication plugins, by writing and enabling your own you can bypass the token verification and allow logging in by a simple get request.
Keep in mind that Joomla! keeps administrator and frontend sessions separate (you can be logged into the administrator, and browse the site as a guest). Additionally, a user needs a Manager, Administrator or Super User group membership to login to the backend.
Administrator
The common use case for admin login is to run a background script.
In order to bypass the Joomla Authentication in the backend, check out the /cli folder as it contains some examples.
Frontend
The use case for frontend login is much wider: server-to-server communication, app authentication, single sign on etc.
The best practice to perform frontend authentication is to build your own authentication plugin. The authentication will be implemented by the onUserAuthenticate() function. Check out the /plugins/authentication/joomla/ plugin for an example.
If you need extra data for the authentication plugin to perform its magic (e.g. the remote token/api key to authenticate using a remote service) you might want to check out the user plugin group, for example the /plugins/user/profile plugin.
Verify last login date/time
The frontend approach should automatically work, showing users as logged in in the administrator control panel.
However, if you use the CLI approach to login to the administrator, this may not work depending on how you perform login.
To be able to check if a user is logged in only authentication is not enough but you need a forced login. Only then you will be able to view them at the backend.
This is the code you can use to check if a user is logged in or not
<?php
if (version_compare(PHP_VERSION, '5.3.1', '<')) {
die('Your host needs to use PHP 5.3.1 or higher to run this version of Joomla!');
}
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
echo ini_get('display_errors');
define('_JEXEC', 1);
define('JPATH_BASE', "C:\Vertrigo\www\joomla" );//Define the Base path as per your installation directory
if (!defined('_JDEFINES'))
{
require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_BASE . '/includes/framework.php';
// Instantiate the application.
$app = JFactory::getApplication('site');
$app->initialise();
require_once (JPATH_BASE .'/libraries/joomla/factory.php');
//Check if a user exists else create one with forced login
$user = JFactory::getUser();
jimport('joomla.plugin.helper');
$credentials = array();
$credentials['username'] = JRequest::getVar('username', '');
$credentials['password'] = JRequest::getVar('passwd', '');
if (!$user->get('gid')){
$forcevars = array();
$forcevars['silent'] = true;
$forcevars['forecelogon'] = true;
$response = $app->login($credentials, $forcevars);
if($response){
echo "Login Successful";
}else{
echo "Login Unsuccessful. Check Username and Password. Give just Plain password.";
}
}
?>
I have modified the code as you neeeded to call username and password in url. better to use getVar in joomla rather than GET method. You url will be in the format http://www.yoursite.com/thisscript.php?username=yourusername&passwd=yourpassword

Do all 404 pages share something in common?/Are 404 page distinguishable from regular pages?

Say I am running stumbleupon.com and users can submit sites to be added into the db of sites. Is there a way that I can write a program to see whether or not the site that was added by the user is actually a real website? Or if it bring me to a 404 that I can say "welp, that was some bugus" or maybe that the user made an error when submitting the url? Or do i need to put people on my payroll to see if the user submitted website bring me to a 404?
The response code from the request is a 404 not found, instead of a 200 success message that you get on a good response from the server. You can easily automate the check.
Since I don't know much about python, I offer a client side solution.
You could check if the URL is legit as soon as the user submits the page. Maybe throw up a 'verifying url' message or something.
Using this method you could make a cross domain call to see if that site is really there. Then you could pop up a message that asks them to fix their mistake or allow the URL to be submitted. This solution uses Yahoo as a proxy, but as you can see by my super simple function below it does work.
function doAjaxCheck(url){
// if the URL starts with http
if(url.match('^http')){
//add a 'loading message here, or something'
// assemble the YQL call
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function(data){
if(data.results[0]){
alert('it is OK');
} else {
alert('not OK');
}
}
);
} else {
$.ajax({
url: url,
timeout:5000,
success: function(data){
alert('it is OK');
},
error: function(req,error){
if(error === 'error'){error = req.statusText;}
alert('not OK : ' + error );
}
});
}
}
However, all this being said, I would go with a server-side check for reliability-sake.

Deleting each notification as a user accepts

How can I make the app delete the notifications as a user accepts them? For example the user sends a request to friends, the users are then notified of this before giving the option to accept or reject. On acceptance I need to enter some info into a database, which isn't the problem I'm having.
I'm using the code below, and the problem i'm finding is when the user has multiple requests from different people. It's either deleting all of the requests or none at all, ideally I need it to delete each request the user has accepted. Any ideas?
$request = $facebook->api("/me/apprequests");
foreach ($request as $data) {
echo "<form method='post'>";
foreach ($data as $full_request_id) {
echo "<input type='submit' name='yes' id='yes' value='Yes'>";
if ((isset($_POST['yes']))) {
try {
$delete_success = $facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;}
else {
echo "Delete failed".$full_request_id;}
}
catch (FacebookApiException $e) {
echo $e;}
}
echo "</form>";
}
}
There's sample code on the page for the Requests dialog: https://developers.facebook.com/docs/reference/dialogs/requests/
I believe the recommended workflow is to delete all pending requests for that user (from Facebook's side); if you still need the user to manually accept them one by one after they click the first one, you can render your own interface for the remaining requests
This is what apps like Cityville do - when you click through from a Facebook requests they clear all your Facebook requests and render their own dialog for you to accept the remaining (now hidden from Facebook's onterface) gifts.