Facebook Graph Api error "An unexpected error has occurred. Please retry your request later" - facebook

I'm trying to retrieve all members in a Facebook group getting this error:
array(5) {
["message"]=>
string(66) "An unexpected error has occurred. Please retry your request later."
["type"]=>
string(14) "OAuthException"
["is_transient"]=>
bool(true)
["code"]=>
int(2)
["fbtrace_id"]=>
string(11) "AnfsXcdgM"
}
Here is my code:
$this->_facebook = new Facebook\Facebook(array('app_id' => "$app_id",'app_secret' => "$secret",'default_graph_version' => 'v2.10'));
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name";
try{
$response = $this->_facebook->get($query);
while($pagesEdge)
{
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
$id = $member->id;
}
}
}catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); }
It works for groups with few hundreads of people (even once for a group with 10.000 members) but randomly I'm occurring to this.

This might be caused by a server side timeout. I get this error every now and then when I request a huge amount of data. Maybe you should try to limit your request by using the limit parameter (default should be 25).

I solved this by doing a cron that takes 100 data at the time and putting into a file text the value of the token for the next call.
I add this string on the query and when the fields inside $url are empty I quit my execution
<?php
public function updateGroupMembers($groupID)
{
$tempNext = file_get_contents($this->dirM); //check if the next string token is in the file
if (!empty($tempNext))
{
$queryUntil = $tempNext;
}
// Sets the default fallback access token so we don't have to pass it to each request
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
// Create table name
$tableName = $groupID . "_Members";
// Query the Graph API to get all current member's ID and name
try
{
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name".$queryUntil; //add the next string to my query
$response = $this->_facebook->get($query);
$pagesEdge = $response->getGraphEdge();
// Index for the elements fetched from the API below
$i = 0;
// Get current time
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
/* ...get data and process them... */
}
$temp = $pagesEdge->getMetaData();
$next = parse_url($temp['paging']['next']);
parse_str($next['query'], $url);
$access_token = '&access_token='.$url['access_token'];
$fields = '&fields='.$url['fields'];
$limit = '&limit=100';
$after = '&after='.$url['after'];
$res['until'] = $access_token.$fields.$limit.$after;
file_put_contents($this->dirM, $res['until'], LOCK_EX);
if ( empty($url['access_token']) || empty($url['fields']) || empty($url['limit']) || empty($url['after']) )
{
file_put_contents($this->dirM, '', LOCK_EX); //clean my txt file that contains my next string
die('FINE');
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'm2Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'm2Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}

Related

UnityWebRequest: Null response

So I have a website(it is unsecured/it doesn't have an SSL certificate) where I have a php script that echo's some info of my database. Here is it:
$query = "SELECT id, password FROM users WHERE username = ".$_GET['uname'];
$result = mysqli_query($connect, $query);
while( $record = mysqli_fetch_assoc($result) )
{
echo json_encode($record);
}
Now, in Unity(version 2022.1.0b10.2818), I have a script that does a get request to my website and gets the info the php script displayed. Here is the script:
IEnumerator GetText()
{
string url = "http://example.com/getUser.php?uname=" + "'" +
usernameInputField.text + "'";
using(UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.SendWebRequest();
if(www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
response = www.downloadHandler.text;
}
}
}
Why does it always give me this error:
Curl error 52: Empty reply from server
and I also get this log in the console from the Debug.log(ww.error):
Received no data in response
How can I fix this?

Facebook messenger bot - receives single and very first message

Facebook messenger bot - receives single and very first message continuously at every 2 minutes.
I have created bot in PHP and set webhook. But I am receiving webhook trigger at every two minutes no matter I have added/received new message or not.
One more thing is that we are receiving only very first messages. There are so many new messages after that message but we are receiving single message only.
Where am I incorrect? I have followed this article :
http://blog.adnansiddiqi.me/develop-your-first-facebook-messenger-bot-in-php/
We got the solution:
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text'] : '';
if (!empty($input['entry'][0]['messaging'])) {
foreach ($input['entry'][0]['messaging'] as $message) {
$command = "";
// When bot receive message from user
if (!empty($message['message'])) {
$command = $message['message']['text'];
}
// When bot receive button click from user
else if (!empty($message['postback'])) {
$command = $message['postback']['payload'];
}
}
}
$pagetoken = "PAGE TOKEN"; // Facebook TOKEN
if ($command) {
if ($command == "hii") {
$message_to_reply = "test_response";
} else if ($command == "need more info") {
$message_to_reply = "Please fill form at link ";
} else if ($command == "\ud83d\ude00") {
$message_to_reply = "smiley";
}
if ($message_to_reply != "") {
$url = "https://graph.facebook.com/v2.6/me/messages?access_token=$pagetoken";
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"' . $sender . '"
},
"message":{
"text":"' . $message_to_reply . '"
}
}';
$jsonDataEncoded = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
$result = curl_exec($ch);
}
curl_close($ch);
}
}
header('HTTP/1.1 200 OK'); // This line needs to be added
die;

facebook php sdk 4 version, unable to fetch user albums

I am developing a facebook application via php sdk 4 version.
My code is as follows:
try {
$session = $helper->getSession();
} catch (FacebookRequestException $ex) {
echo $ex->getMessage();
} catch (\Exception $ex) {
echo $ex->getMessage();
}
if ($session) {
try {
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$me = $response->getGraphObject();
$user_id = $me->getProperty('id');
echo $user_id;
$accessToken = $session->getAccessToken();
echo $accessToken;
echo "<br>".$user_id;
$request = new FacebookRequest($session, 'GET', '/me/albums');
$response = $request->execute();
$userAlbums = $response->getGraphObject();
echo $userAlbums['data'][0]['id'];
} catch(FacebookRequestException $e) {
echo $e->getMessage();
}
} else {
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/lykebook/');
$auth_url = $helper->getLoginUrl(array('user_friends', 'publish_actions', 'user_photos', 'user_status', 'friends_photos','friends_status','publish_stream'));
echo "<script>window.top.location.href='".$auth_url."'</script>";
}
But the problem is I am not getting any album data. I don't know what the problem is? The earlier request i.e: /me is working fine. I checked that by printing $user_id. But the next request for getting albums is not working i.e /me/albums. Help me in correcting this.
Try using the getGraphObjectList() method since you are expecting more than one object. Then the result will be an array of GraphObject objects, see here.
From here, you need to access these as objects and not arrays with the helper methods available (e.g. getProperty()).
Otherwise, you can retrieve the array backing this object with asArray().
You could use getGraphEdge, here below the code:
$fb->setDefaultAccessToken($accessToken);
try {
$response = $fb->get('/me/albums');
$albums = $response->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
foreach ($albums as &$value) {
echo $value;
}

Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. thrown in

with my app's administrator acount on facebook my app work normally, but with other app I get error: Fatal error: Uncaught OAuthException: An active access token must be used to query information about the current user. What's wrong here? I tried many ways using different guides but does not return true results .Help me, please if you can, Thank you very much.
My code here :
//$return_url = loginFacebook;
$this->load->library('facebook', $this->app_config);
parse_str($_SERVER['QUERY_STRING'], $_GET);
if (isset($_GET['code'])) {
if (isset($_GET['code']) && !isset($_GET['error'])) {
$user = $this->facebook->getUser();
if($user){
try{
$fb_user = $this->facebook->api('/me?fields=email,username,name,picture');
//print_r('<pre>');print_r($fb_user);die;
if (!$fb_user) {
show_error('invalid access_token');
}
if(!isset($fb_user['email'])) {
show_error('invalid facebook account');
}
// do somthing here
$this->load->view('login_success',$array);
}
}catch (FacebookApiException $e) {
echo $e->getMessage();
}
} else {
echo "Could not log in with Facebook";
}
} else if ($_GET['error']) {
show_error('user denied!!!');
}
} else {
$log = array(
'scope' => $this->scope,
'redirect_uri' => $return_url
);
if(strlen(store()) > 1) $log['display'] = 'popup';
else $log['display'] = 'wap';
$loginUrl = $this->facebook->getLoginUrl($log);
header("Location: $loginUrl");
}

open_basedir restriction in effect. File() is not within the allowed path(s) and Uncaught CurlException: 3: No URL set! thrown in base_facebook.php

protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
I have built a facebook app, but something went wrong in this piece of code of base_facebook.php.
Whole code is here. All i get everytime are this 2 errors -
1.Warning: curl_setopt_array() [function.curl-setopt-array]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in /home/a2424901/public_html/base_facebook.php on line 802
2.Uncaught CurlException: 3: No URL set! thrown in /home/a2424901/public_html/base_facebook.php on line 814
Here is the code of my facebook app i.e.(index.php)
Yeap, non-obvious error message.
But it means, that realpath() returns empty value:
File() is not within the allowed path(s)...
Make sure, that the file passed to realpath() function really exists in the specified path.
Other exceptions in your example were caused by this problem.
By the way, it's good practice to wrap all weak spots (in your example - Facebook API calls) in try-catch blocks.