Facebook Real Time Subscriptions Throws Exception Even when challenge is answered - facebook

I'm trying to subscribe from my app to Real Time Subscription of Facebook using v2.4 Graph API (after creating a callback function in fbcallback.php) using the code below from my index.php page (the appid and IP address obviously fake in this post):
try {
$response=$fb->sendRequest('POST','/1111/subscriptions',
array(
'object' => 'user',
'callback_url' => 'http://111.111.111.111/fbcallback.php',
'fields' => 'first_name',
'verify_token' => 'thisisaverifystringtestuser',
)
);
$graphNode = $response->getGraphNode();
}catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "exception:" . $e->getMessage(); }
While i'm sure from callback log that Facebook reaches my callback function and i use in it the code below:
<?php
define('VERIFY_TOKEN', 'thisisaverifystringtestuser');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
}
?>
i get the Message from my index page code looking like this:
exception:(#2201) response does not match challenge, expected value = '866531638', received='866531638'
Anyone encountered it?
P.S I created a test user from the app dashboard roles and configured him to subscribe to app on creation and also got (but not used) an access token for this user from dashboard also.....since i can't denote a specific user during the subscription proccess from my php code i expect (or wish) this user to be subscribed by my php code...am i wrong?

Looks like your script outputs more than just the hub_challenge value.
When I copy&paste the error message from your posting, and insert it in NotePad++, I get that part shown as
received='?866531638'
^
– so there seems to be some invisible/not display-able character before the actual value.
Make sure your script is saved as UTF-8 without BOM, and that it does not make any other output besides the hub_challenge value either. (That could include stuff outside of <?php … ?> tags as well.)

Related

Ask facebook to re-scrape URL automatically

how can I make a php code for facebook to automatically update the cache of a single url
I saw something similar in other threads, but did not manage to make it work:
Is there an API to force Facebook to scrape a page again?
Ask facebook to re-scrape URL
For example use this php code, adding the url of my web www.tolchx.net, but it still appears the same GIF when I go to debugging:
<?php
try {
$params = [
'id' => 'https://www.tolchx.net',
'scrape' => 'true',
];
$response = $fb->post('/', $params);
print_r($response);
} catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
?>
With that enough to automatically update the link cache www.tolchx.net?
thanks for the reply

Facebook Marketing API and Ads Insight Access

I'm building a small program that works with various APIs to automate reporting services we offer some clients.
One of the things we report on is Facebook Ads performance.
I've been building out this program using the Facebook Marketing API & Ads Insight APi https://developers.facebook.com/docs/marketing-apis
I've gone through the whole process of setting up a Facebook 'App' and getting the relevant app tokens.
However, I've hit a wall since development access only allows for 5 Ad Accounts.
To apply for basic access, the marketing API is asking for the development platform and a whole bunch of other things that aren't relevant to my program. I'm not building an 'app' intended for public release in the traditional sense; rather, I just want to integrate with these APIs on a basic level to automate some internal tasks.
It seems mind-boggling to me that I wouldn't be able to do something like this, but this is what the Facebook documentation seems to be suggesting.
If anyone else has familiarity with this kind of issue, I'd love to know if there is a workaround.
Submit your app for review to get more than 10 ad accounts. Use the "Platform" of Website. Select Native or desktop app; app secret NOT embedded in the client. The rest of it can be mostly ignored, but you will need to include some screen shots of your app and a description of how it works and what it does. A real human will review it, and you can get help in the Facebook Developers group here:
https://www.facebook.com/groups/fbdevelopers
Youwill get a pass/fail only...no comments. Don't be surprised if they reject it first time around. Do not resubmit and hope for a better response the second time around -- they'll eventually lock you out for a few days. Post a help question to the group.
Derks, I currently am building dashboard with over 40 clients and I am able to display everyone of them and their insights data etc. with basic development level. I have code if you want to take a look only thing I am trying to accomplish now is making a date range picker but, you are more than welcome enough to take a look at what I have just to get a general idea.
Here are the Use objects from Facebook
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Fields;
use FacebookAds\Object\Fields\AdImageFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\Fields\AdCreativePhotoDataFields;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Page;
use FacebookAds\Object\Fields\AdPreviewFields;
use FacebookAds\Object\Values\AdPreviewAdFormatValues;
use FacebookAds\Object\AdVideo;
?>
Here is the general code I am trying
<?php
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => 'xxxxxxxxx',
'app_secret' => 'xxxxxxxxxxx',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['enter api key here'])) {
$_SESSION['enter api key here'] = null;
}
if (!$_SESSION['enter api key here']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['enter api key here'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['enter api key here']) {
//echo "You are logged in!";
// Initialize a new Session and instantiate an API object
Api::init(
'xxxxxxxxx', // App ID
'xxxxxxxxx', //app_secret
$_SESSION['enter api key here'] // Your user access token
);
?>
<div id="fbdata"></div> <?php
$account = new AdAccount('act_xxxxxxxxxx');
$params = array(
'date_preset'=> 'last_28d',
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'campaign',
'limit' => '15'
);
$fields = array(
AdsInsightsFields::CAMPAIGN_NAME,
AdsInsightsFields::CAMPAIGN_ID,
AdsInsightsFields::IMPRESSIONS,
AdsInsightsFields::CLICKS,
AdsInsightsFields::REACH,
AdsInsightsFields::SPEND,
AdsInsightsFields::CPM,
AdsInsightsFields::CPC,
AdsInsightsFields::ACTIONS,
);
$field = array(
AdCreativeFields::TITLE,
AdCreativeFields::THUMBNAIL_URL,
AdCreativeFields::BODY,
);
$params1 = array(
'time_range' => array(
'since' => (new \DateTime($beginDate))->format('Y-m-d'),
'until' => (new \DateTime($lastDate))->format('Y-m-d'),
),
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'ad',
'limit' => '5'
);
$adcreatives = $account->getAdCreatives($field, $params1);
?>
<table class="fbtable">
<tr>
<th>Title</th>
<th>Ad Image</th>
<th>Ad Body</th>
</tr>
<?php
foreach($adcreatives as $t2){
echo"<tr>
<td>$t2->title</td>
<td><img src='$t2->thumbnail_url'/></td>
<td>$t2->body</td>
</tr>";
}
$insights = $account->getInsights($fields, $params);?>
<table class="fbtable">
<tr>
<th>Campaign ID</th>
<th>Campaign Name</th>
<th>Impressions</th>
<th>Clicks</th>
<th>Reach</th>
<th>Spend</th>
<th>Total Actions</th>
<th>CPM</th>
<th>CPC</th>
</tr>
<?php
foreach($insights as $i) {
$impress = number_format((float)$i->impressions);
$reach = number_format((float)$i->reach);
$totalAction = number_format((float)$i->actions);
$cpc = number_format($i->cpc, 2, '.', '');
$cpm = number_format($i->cpm, 2, '.', '');
echo"<tr class='fbtable'>
<td>$i->campaign_id</td>
<td>$i->campaign_name</td>
<td>$impress</td>
<td>$i->clicks</td>
<td>$reach</td>
<td>$$i->spend</td>
<td>$totalAction</td>
<td>$$cpm</td>
<td>$$cpc</td>
</tr>";
}
}else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://where you want login to be.com', $permissions);
echo 'Log in with Facebook';
}
?>
I will help much as I can #Derks and I believe the only thing you may need to do is figure out way for the program or whatever your building know who is who.

FaceBook PHP API SDK: suddenly the argument 'link' is not published and /me/feed is not working

I completed this script, that was working fine till this morning, when launching it, suddenly I noticed that the argument "link" of the array $linkData, is not published any longer, (no error returned) while "message" is published.
I also noticed that if I put /me/feed into the object $fb->post, it doesn't work (see the commented line). No errors returned.
While, if I put the code of a group (the code you see is a test group I created to test the script), the argument "message" is published (not the "link")
The scopes are:
user_managed_groups,
user_events,
user_friends,
user_posts,
publish_actions,
user_actions.music,
user_actions.video,
public_profile
The link is referred to the link for which the application is written. the www.example.com URL, is written here for this example. In the real code, I use the URL of the site of the App (that till yesterday was working fine).
Please here the code:
<?php
session_start();
define(__APP_ID__, XXXXXXXXXXXXXXX);
define(__APP_SECRET__, 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY');
define(__APP_TOKEN__, 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ');
define(__APP_ACCESS_TOKEN__, 'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW');
require_once '../include/setup.php';
require_once $root_dir.'/include/Facebook/autoload.php';
// Creates the object
$fb = new Facebook\Facebook([
'app_id' => __APP_ID__,
'app_secret' => __APP_SECRET__,
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'The link above, is not any longer published',
];
$group_id = "1041863359178529";
try {
//$response = $fb->post("/me/feed", $linkData, __APP_ACCESS_TOKEN__); // SUDDENLY it doesn't work any longer
$response = $fb->post("/{$group_id}/feed", $linkData, __APP_ACCESS_TOKEN__);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
echo 'Posted with id: ' . $graphNode['id']."\r\n";
?>
EDIT:
Is there anything I can do? Is id depending from the App settings? I changed many parameters to find a solution but I still have the issue.
I did verified that the block, is due FB.
In other words: probably of security reasons (mainly Anti-Spam), FB block repetitive use of the function in short time.
I did try also to wait more than 15 seconds among the iterations, but if I employ it for more than 20-25 time in one day, FB suspends all the required authorizations.
At the time I did post the thread, FB was enabling only the post of the text, and deactivated OpenGraph.
Now, instead, it blocks any kind of sending, including text.

Facebook PHP SDK - OAuthException - OAuth2

How are you supposed to deal with people who signed into Facebook a while ago. Come to your site you should them a continue link (because you detect that they are already logged into Facebook) and then on the page you direct them to you get this error.
Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in /var/www/html/lib/base_facebook.php on line 1039
I don't understand how you are supposed to prevent this? Does this have something to do with the signed info that you give back to Facebook to get an access_token? Seems like this signed info can expire (it has an issued_at date). What is the correct way to handle this in your website's flow?
Are you expected to write code like this:
<?php
$user = $facebook->getUser();
try {
// attempt to do a call just to see if you are going to have this issue
$profile = $facebook->api('/me');
} catch (Exception $e) {
$user = false;
}
if ($user) { ?>
Begin
<?php } else { ?>
<fb:login-button scope="email" size="large">Connect</fb:login-button>
<?php } ?>
Instead of this:
<?php
$user = $facebook->getUser();
if ($user) { ?>
Begin
<?php } else { ?>
<fb:login-button scope="email" size="large">Connect</fb:login-button>
<?php } ?>
Getting the $user back from the Facebook SDK only seems to tell you there is a cookie. And not if that will actually work when you go to do the API calls.
UPDATE:
So my only problem with this method is ... when the user does have a cookie on my site, but the API call fails - I show them the connect button. User clicks the connect button, it quickly appears and disappears. Because it wasn't a true 'auth.login' that just occured, the user will not get sent to my start.php page via JavaScript redirect. How do others handle this? I'm stumped. Please tell me if there are other flaws with how I'm attempting to do this.
Try passing the access token to the API call that verifies that the user has authorized your application. Below is what I do, and it should help to alleviate the OAuthException you're getting.
$user = $facebook->getUser();
if($user) {
$access_token = $facebook->getAccessToken();
$params = array('access_token' => $access_token);
try {
$me = $facebook->api("/me", $params);
} catch(FacebookApiException $e) {
$user = null;
}
}
if($me) {
// proceed with authenticated user with an active access token.
}
Are you expected to write code like this:
Yes, you will have to handle the OAuthException.
But rather than using FBML login button, you can redirect the user to facebook login url for your application. You can get the url by using function getLoginUrl provided by Facebook PHP SDK. See getLoginUrl for more information.
For your email permissions you can use following array:
$params = array( 'scope' => 'email' );
Once successfully logged in, the user will be redirected back to the application page which redirected him to facebook login.

codeigniter facebook

SORRY FOR THE LONG POST. I JUST WANT TO BE CLEAR!! :cheese:
I am using the stated template library in my ci setup and everything works great except for when i use Mr. Haughin's facebook_connect!
facebook_connect works beautifully if I call anything in a separate view file in my controller like so:
function facebookconnect()
{
$this->load->library('facebook_connect');
$data = array(
'user' => $this->facebook_connect->user,
'user_id' => $this->facebook_connect->user_id
);
$this->template->write_view('content','fbtest',$data);
$this->template->render();
}
this works no problem calling it from it's own page and everyone is happy. But when I try to put my facebook interactivity into a div on my homepage with this code:
function index()
{
$this->load->library('facebook_connect');
$data = array(
'user' => $this->facebook_connect->user,
'user_id' => $this->facebook_connect->user_id
);
$this->template->write_view('content','indexpage',$data);
$this->template->render();
}
My homepage loads fine but I have this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: user_id
Filename: views/indexpage.php
Line Number: 32
This i think is strange as it works with code above. My variables are passed so I don't get it.
What I want to achieve is that on the homepage a list of facebook friends should appear when page loads. Is there anything i should know about this library? I went through the userguide looking for to see if i could write a separate view to the div that should carry the facebook connect results. Here is my view code just incase it will help:
php if ( !$user_id ):
php else:
" />
Hi php$user['first_name']!
(Logout)
php endif;
Here's some comments!
[removed]
FB.init("$this->config->item('facebook_api_key')", "/xd_receiver.htm");
[removed]
The problem seems to be in this line:
user_id' => $this->facebook_connect->user_id
because facebook's PHP client doesn't have any user_id property. The user id is available from:
user_id' => $this->facebook_connect->user
So try removing the line:
'user_id' => $this->facebook_connect->user_id