Facebook API - Subscriptions Timeout in callback - php

I have a really strange problem in PHP with the Facebook API. All this code is working in my testing server (shared hosting). But when I run it in the production server (Heroku) I get an error.
What I am trying to do is to receive realtime updates from Facebook when my app users likes (or unlikes) a new page.
This is the documentation that Facebook provides: https://developers.facebook.com/docs/graph-api/real-time-updates
My code to subscribe:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$facebook->api(
"/" . $app_id . "/subscriptions", "POST", array(
'object' => 'user',
'callback_url' => 'http://' . $url . '/rtu/callback',
'fields' => 'likes',
'verify_token' => $rtu_verify_token,
'access_token' => $app_id . "|" . $app_secret
)
);
My code in the callback:
if (isset($_GET['hub_verify_token']) && isset($_GET['hub_challenge'])) {
$rtu_verify_token = Config::get('variables.rtu_verify_token');
if (($_GET['hub_verify_token'] == $rtu_verify_token)) {
echo $_GET['hub_challenge'];
die();
}
}
$data = file_get_contents("php://input");
$json = json_decode($data);
The error:
FacebookApiException (#2200) callback verification failed: Operation
timed out after 6001 milliseconds with 0 bytes received
I have already verify the app_id, url and the app_secret variables.
Again, this works in my testing server, but not in Heroku.
I even tried not to use the Facebook API and make a cURL call, but I got the same error.
I'm thinking that maybe has something to do with Heroku, but i couldn't find any evidence.
Thanks

Your server must be reachable from the internet, and be able to process concurrent requests, because facebook sends verification requests simultaneously.

Related

Curl GET Request to the spotify Authorization API

I need some help with my Curl GET Request to the Spotify API.
The API has three different ways/endpoints to get an authorization.
I read some articles, to find the correct syntax to send the request. But i always get an error. If i post the url into my brwoser it works perfectly, also with the redirect uri.
But it doesnt work with the Curl GET Request.
It sounds stupid, but i spend the last three days with this Problem.
My code:
<?php
$client_id = 'myClientID';
$redirect_url = 'http://mywebsite/first/page.php';
$scope = 'user-read-private%20user-read-email';
$data = array(
'client_id' => $client_id,
'response_type' => 'code',
'redirect_uri' => $redirect_url,
'state' => stateHash(), // Create a random hash
'scope' => $scope,
'show_dialog' => 'true'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/authorize' . http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
$result=curl_exec($ch);
echo $result;
The error from the API Shows me this:
or i got an "1" as response.
I hope that i get some nice tips :)
There is a package for Spotify web API try using that
composer require jwilsson/spotify-web-api-php
Before using the Spotify Web API, you'll need to create an app at Spotify’s developer site.
Simple example displaying a user's profile:
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
}
For more instructions and examples, check out the documentation.

Is Facebook long-lived access token usable on multiple users?

I'm experimenting with Facebook's long-live access token and I found that the long-lived access token is usable in different users. Is this normal?
I'm using the Facebook PHP SDK v3.2.2 and Yii. Here's my code to generate the long-lived access token from App_User_1
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch', 'scope' => 'publish_actions'));
$fbUser = $facebook->getUser();
if(!empty($fbUser))
{
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$access_token = $facebook->getAccessToken();
exit(print_r($access_token));
}
Here's my code to test posting to App_User_1's Facebook wall.
$message = "A message";
$link = "http://www.alink.com";
$picture = "http://www.alink/image.png";
$sendTo = "`**App_User_1**`";
$access_token = "xxxxxxxxxx";
Yii::import('application.vendors.facebook.Facebook');
$facebook = new Facebook(
array(
'appId' => Yii::app()->params['facebookApi'],
'secret' => Yii::app()->params['facebookSecretCode'],
'cookie' => true,
)
);
$attachment = array('message' => $message, 'link' => $link, 'picture' => $picture );
$api = "/$sendTo/feed/?access_token='.$access_token,";
$result = $facebook->api($api,'post', $attachment);
I have 2 test app user. If I substitute the App_User_1's access token, I can also post into App_User_2's Facebook Wall. Is this normal?
I think I may have been doing this the wrong way. Using the PHP SDK, the api method does not recognize the access_token as part of its path parameter. (e.g. /me/feed/?access_token=blah)
Instead, the access token should be specified under optional parameters in an array format.
Here's how I got mine to work.
$facebook_uid = '1234567890';
//Initialize array for the params parameter
$fb_data = array();
$fb_data['access_token'] = 'xxxxxxxxxx';
$fb_data['message'] = 'A test message';
$facebook->api('/'.$facebook_uid.'/feed/', 'post', $fb_data);
Tried swapping the access token with other app user's access token and not specifying access_token at all. Both will result in error (#200) The user hasn't authorized the application to perform this action.
I would also recommend using this tool by Facebook to verify that the access_token is generated correctly by your app. https://developers.facebook.com/tools/debug

Programmatically post a facebook page status using Cron with the PHP API

So I have been tearing my hair out trying to make this work. I have been all over stack overflow looking at existing questions and found this: Facebook: Post on Page as Page issue (access token / php) but it still doesn't seem to solve my problem.
I'm trying to post to my facebook page every day using a cron job. I am having problems with the authentication. Here's my code:
//Post to Facebook
//Variables
$app_id = "...";
$app_secret = "...";
$page_id = "...";
$my_url = "http://.../";
$access_token = "taken from page access token (developers.facebook.com/tools/explorer/)";
//Create the facebook object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//Get the access token using Facebook Graph API
//This gives permission to post to the wall
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&code=" . $access_token
. "&redirect_uri=" . $my_url;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
//Get a list of pages and loop through
//If one matches one in the variables above, that's the one
//We're posting to
$attachment_1 = array(
'access_token' => $user_access_token
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//Write to the Page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> "Hello World"
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
//Send me an email
...
mail($to, $subject, $message, $headers);
}
This works if I access the script in a browser (I assume it is using my facebook session then), but not when it is triggered by the cron job.
I would really appreciate any help. Thanks.
//Get the access token using Facebook Graph API
//This gives permission to post to the wall
If you already have a page access token, then this step is wrong at this point – it’s for exchanging the code that the Auth dialog passes back to your app for a user access token.
But since you already have your page access token, you can skip that step (everything from the above comments up to //Write to the Page wall).
All you have to do, is to use your page access token in your API call, instead of the user access token you are giving there right now.

Facebook AppRequests not showing?

I'm using the Facebook php-sdk and the batch request API to send AppRequests with the following code:
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET,
'cookie' => true
));
// get app token before it's overwritten
$FB_APP_TOKEN = $facebook->getAccessToken();
$res = $facebook->api('<USER ID>/apprequests', 'POST', array(
'message' => 'Test message..'
), $FB_APP_TOKEN);
This appears to work and returns the ID of the request, which I can then see has been stored when looking back with the graph explorer. My problem is that nothing appears on my test user's facebook account, no notification and no number appears next to the app name in the sidebar as described here.
Does anyone have any idea why this might be?
getAccessToken() sometimes don't return user access token. It only returns facebook application key. Use the following code to get the access token.
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $app_id .
"&client_secret=" . $app_secret .
"&grant_type=client_credentials";
$app_access_token = file_get_contents($token_url);
Turns out I was looking at the App's page instead of the App itself, app requests are working fine!

index of $_POST seemingly empties at random

Ok so this is driving me insane! I've got a script written that takes user submitted product information from a previous page and sends it to the user's facebook business page via the facebook php sdk.
Here's the php code:
$app_id = "1234567890";
$app_secret = "1234567890";
$page_id = "1234567890";
$page_token = "1034921234567890";
$store_name = "MyStore.com";
$store_url = 'http://www.mystore.com';
$cur = '$';
$new_message = "New Product!";
$prod_image = $store_url . "/images/" . $_POST['products_image'];
$price = $products_price;
$prod_url = $store_url . '/index.php?main_page=product_info&cPath=' . $current_category_id . '&products_id=' . $products_id;
$prod_name = $_POST['products_name'][1];
$prod_description = $_POST['products_description'][1];
include_once 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true, ));
$attachment = array(
'access_token' => $page_token,
'message' => $new_message,
'name' => $prod_name,
'link' => $prod_url,
'caption' => 'Price: '.$cur . $price,
'description' => $prod_description,
'picture' => $prod_image
);
Everything sends to facebook fine except on some servers$prod_description aka $_POST['products_description'][1] ends up empty. When a var_dump($_POST['products_description']); is placed on the same line, it comes back with:
array(1) { [1] => string(35) "This is a
test product description." }
So I know the information is there and not being overwritten it's just for whatever reason when sent to facebook (with cURL from the include_once file) it doesn't post.
I should also say that this is a Zen Cart mod that is available for download and I while haven't been able to reproduce the error myself (test on 4 different servers) I have had miltiple users add the var_dump and send me the results.
I guess my question is; Is there something (like a ini setting, cURL option, etc) that may vary from server to server that would cause random indexes to empty when sent via cURL and is there something I can do to fix it?
Thanks in advance.
I think problem is in the way data is passed. You have spaces in the description, that can cause problems...
Try explicitly setting enctype for the form to "application/x-www-form-urlencoded"
<form enctype="application/x-www-form-urlencoded" .... >
You can also try to url_encode the product description before passing it to Facebook.
$prod_description = urlencode($_POST['products_description'][1]);

Categories