Facebook API Real Time updates for Page/Feed no response - php

I have a problem with Facebook Real-time subscription from my facebook page.
When I POST a subscription, i get the message from facebook about it to my call back url.
Code:
$session = new FacebookSession('<APP ACCESS TOKEN>');
$request = new FacebookRequest(
$session,
'POST',
'/<APP ID>/subscriptions',
array(
'object' => 'page',
'callback_url' => 'http://*************/facebook/callback.php',
'fields' => 'conversation', // a try 'feed' to
'verify_token' => '<VERIFY TOKEN>',
)
);
$response = $request->execute();
BUT when someone add a post/conversation to my fb page, facebook don't send me any data.
callback.php code:
<?php
// Insert the path where you unpacked log4php
include('log4php/Logger.php');
// Tell log4php to use our configuration file.
Logger::configure('config.xml');
// Fetch a logger, it will inherit settings from the root logger
$log = Logger::getLogger('myLogger');
// Start logging
$log->warn($_REQUEST); // Logged because WARN >= WARN
require_once __DIR__ . '/facebook-php-sdk-v4-5.0-dev/src/Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\Authentication\AccessToken;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
//define('VERIFY_TOKEN', '*******');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == '<VERIFY TOKEN>') {
echo $_GET['hub_challenge'];
$log->warn($_GET);
$log->warn($_POST);
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Here you can do whatever you want with the JSON object that you receive from FaceBook.
// Before you decide what to do with the notification object you might aswell just check if
// you are actually getting one. You can do this by choosing to output the object to a textfile.
// It can be done by simply adding the following line:
// file_put_contents('/filepath/updates.txt',$updates, FILE_APPEND);
$log->warn($updates);
$log->warn($_GET);
$log->warn($_POST);
error_log('updates = ' . print_r($obj, true));
}
Thank you for your help !

There is currently an open bug with Facebook support:
https://developers.facebook.com/bugs/709097499224897/
So it's possible that this is a temporary issue...

What's the output of /{your-app-id}/subscriptions?
According to your code you subscribed to /conversations which requires read_page_mailboxes permissions. You probably want to try a simple page feed subscription first to see if this works.
RTU updates seem to be back to normal since yesterday, but deleting your subscriptions and re-subscribing might be worth a try, too, since you probably subscribed to a black hole when RTU had issues yesterday.

I find answer with a big help from facebook developers forum friends :)
My code to make subscription and callback code is good. But to get conversations or feed it is not enough. I have to add my app to my page as a subscribed_app using request in graph api:
POST
{page-id}/subscribed_apps
the docs for this operation is on:
https://developers.facebook.com/docs/graph-api/reference/page/subscribed_apps/

Related

How to a users Google+ cover programticly

I had a problem with updating user cover pic using php(zend framework) and Oauth.
I have added to my composer.json the following lines:
"require" : {
"google/auth": "0.7",
"google/apiclient" : "^2.0.0#RC"
}
After that I made composer-install + composer-update using and oppp I get the library inside my vendor.
I have configured my application inside google developing console, following the official tutorial by google :D
Now inside my controller I could easily request google web service using this method :
public function googleplusAction()
{
Zend_Loader::loadFile("HttpPost.class.php");
$client_id = "id_here";
$client_secret = "secret_here";
$application_name = "application_name_here";
$redirect_uri = "redirection_uri_here";
$oauth2_server_url = 'https://accounts.google.com/o/oauth2/auth';
$query_params = array(
'response_type' => 'code',
// The app needs to use Google API in the background
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'scope' => 'https://www.googleapis.com/auth/userinfo.profile'
);
$forward_url = $oauth2_server_url . '?' . http_build_query($query_params);
header('Location: ' . $forward_url);
}
After that I get redirected to my redirection URI , and in the bar address I get a new variable 'code'.
Until now, I hope everything is fine , coming to the most important part , the controller of the redirection URI page , using the 'code' variable that I have talked about it before I tried to get an access token, but I was failed.
This is the method that should set a new cover picture on google plus :
$client_id = "client-id";
$client_secret = "g+-secret";
$application_name = "my-app-name";
$redirect_uri = "my-uri-on-g+";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$client->authenticate($_GET['code']); // I have the right code, and I am being authenticated
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
var_dump($person);
$pic = $this->session->image['generatedAbs'];
$gimg = new Google_Service_Plus_PersonCover();
$source = new Google_Service_Plus_PersonCoverCoverPhoto();
$source ->setUrl("$photo-that-i-wanted-to-put-on-g+");
$gimg->setCoverPhoto($source);
$person->setCover($gimg);}
So my questions are :
How can I change my google plus cover picture to a new png or JPEG picture that I have already in my project ?
inside the G+ library I found this method :
Google_Service_Plus_PersonCoverCoverPhoto();
inside a class called
Google_Service_Plus_PersonCover();
But how can I use it ?
I think that methods Google_Service_Plus_PersonCoverCoverPhoto() and Google_Service_Plus_PersonCover() are used by the client library to set it when the information is retrieved. It is not meant for you to be able to update the users cover on Google+, if that does work it will only update the class object which really there is no point in doing (IMO).
var_dump($person->Cover);
If you check the Plus.People documentation you will notice there are no update or patch methods. This is because its not possible to update a users information programmatically at this time.
Answer: Your inability to update the users cover picture has nothing to do with Oauth it has to do with the fact that this is not allowed by the API. Unfortunately it looks like you have done a lot of work for nothing this is why it is good to always consult the documentation before you begin you would have seen that it was not possible, and could have avoided a lot of unnecessary stress on yourself.

Facebook TokenResponseException with Laravel 4.1 and oauth-4-laravel

I'm getting a TokenResponseException from Laravel when I try to login to my web site with Facebook using oauth-4-laravel.
OAuth \ Common \ Http \ Exception \ TokenResponseException
Failed to request resource.
Using Facebook's JavaScript API works like its supposed to, so I'm pretty sure my application is configured correctly.
Are there any known issues that might cause this problem? Am I doing something wrong, or is this a bug in the library?
With the exception of a redirect line that works around another bug, my code is identical to the example code at the GitHub page. I think the exception is thrown when I try to get the token from the Facebook Service object.
Here's the code:
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from google, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
// ref: https://github.com/artdarek/oauth-4-laravel/issues/27
//return Response::make()->header( 'Location', (string)$url );
return Redirect::to((string)$url);
}
}
And a screenshot:
I had this exact same problem. It turns out that my issue was that my return_uri was missing a trailing slash, which through off the entire process. Make sure that when you're calling it you've added it.
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to/');
NOT
$fb = OAuth::consumer('Facebook','http://url.to.redirect.to');
first try to load file_get_contents("https://www.facebook.com");
if allow_url_fopen=0 was set in the php.ini it will not work so you need to change it to allow_url_fopen=1
The weirdest thing i have your problem with google not with facebook, so here is my code maby it helps you fix your fb problem
public function loginWithFacebook() {
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode( $fb->request( '/me' ), true );
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name'];
echo $message. "<br/>";
//Var_dump
//display whole array().
dd($result);
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
}
Since my previous answer was deleted.. Let's try again..
--
After some debugging I think I got it. Commenting out the error_reporting part visible in your code snippet will already tell you a lot. The file_get_contents call got a 401 Unauthorized because the tokens were no longer valid.
After changing code, start your auth process from the beginning and don't refresh your url half-way, that wil cause the error.
The problem should be here $token = $fb->requestAccessToken( $code );
When I tried var_dump it, I get this.
object(OAuth\OAuth2\Token\StdOAuth2Token)[279]
protected 'accessToken' => string 'your-accessToken' (length=180)
protected 'refreshToken' => null
protected 'endOfLife' => int 1404625939
protected 'extraParams' =>
array (size=0)
empty
Try this and check what you've get as accessToken. Anyway, your function loginWithFacebook working fine with me.
I had the same problem. I was trying to access facebook graph. It wasn't that it could not access the URL, it was that Facebook was returning a 400 error because I wasn't passing parameters through. Try connecting to HTTPS on a site that will have a working HTTPS connection. E.g. Try this:
file_get_contents("https://www.namhost.com");
If that works, you must see why the HTTPs connection you are connecting to is failing, because the problem isn't that you can't connect to HTTPs, but rather that what you are connecting to isn't liking the request.

How to post feeds to twitter?

I want to post some text automatically to my application twitter account. I create an account for that and take all the needed information and write a php code for it. it is simple code:
I made it just to test the post ability :
<?php
require_once 'oauth/twitteroauth.php';
$message = "hiiiiiii"; #actual message to twitter
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
print_r($connection);
$content = $connection->get('account/verify_credentials');
//print_r($content);
$connection->post('statuses/update', array('status' => $message));
?>
I get the information from the account so i think the connection is working but why i can not post any thing? i tried to post this message but after executing this code nothing happened on my twitter no new tweet is shown????
$connection->post is a method :
/**
* POST wrapper for oAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->oAuthRequest($url, 'POST', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
My first port of call if you are able to receive information from the account using those credentials, would be that your app has read AND write (posting) permissions:
Go to dev.twitter.com/apps. Select your app, then under 'settings' -->
'application type' you will find what you need.
Although that didn't work, no matter what you changed in your code posting to your account through this app wouldn't work as that functionality was outside the permissions you set yourself. So now we know that you're able to post:
Change
$connection->post('statuses/update', array('status' => $message));
To
$result = $connection->post('statuses/update', array('status' => $message));
Then see what the value of $result is. This might provide some clues
Ok so the response is telling you, you still don't have permissions, you need to regenerate your token and access credentials then update your code with them:
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Those credentials still have the previous permissions attached to them, when you request new token, it will reference the new permissions and allow you to post.

Facebook PHP SDK get access token using php

I am using the following code to post to Facebook:
require('facebook.php');
$fb = new Facebook(array('appId' => 'MY APP ID','secret' => 'MY APP SECRET','cookie' => true));
$result = false;
$feed_dir = '/401868882779/feed/'; //to the UID you want to send to
$acToken = "MY ACCESS TOKEN";
$url = 'URL';
$link = $url . 'event.php?id=' . $id;
if (isset($picture))
{
$picture = $url . 'uploads/' . $picture;
}
else
{
$picture = $url . 'images/blank100x70.png';
}
$msg_body = array('access_token' => $acToken,'name' => $noe_unsecured,'message' => $link,'link' => $link,'description' => $description_unsecured,'picture' => $picture);
try
{
$result = $fb->api($feed_dir, 'post', $msg_body);
}
catch (Exception $e)
{
$err_str = $e->getMessage();
}
but I need to update the access token manually every time it changes. I am sure there's solution but I cant find it.. I tried lots of scripts and nothing worked.
It is possible.
Check: http://developers.facebook.com/docs/reference/php/facebook-setAccessToken/
Depending on when you perform the wall post, you might need to request the offline_access permission. This will convert your access_token into a format that does not expire so there would be no need to refresh the token.
A simple solution...remove the access_token!
You simply don't need it as long as you got the publish_stream permission!
I believe there are multiple methods to do this:
- you can use the method already provided in the PHP SDK getAccessToken which returns the current access token being used by the sdk instance, more info at this url.
- However you need not use an access token to call the api() method, once you ask the user for the publish_stream permission, as already mentioned by #ifaour. Hence you can do something like this example, scroll to the subheading Post a link to a User's wall using the Graph API.
- Then, you have another three options
i) either get a new access token using the method here, if you are posting when the user is currently using your app, otherwise you can try the next 2 options
ii) get offline access
iii) i'm not sure of this, but you might want to try with an app access token which can be obtained this way.

Auth problems with OAuth (Facebook App), session is not available?

I want to read all birthdays of the friends from current user. I use the new Graph API of facebook. I request the authorization of the permissions (read_friendslist and friends_birthday) based on Facebooks insights example and php-sdk example. For reading the friendslist and the user details I used the Graph API with Facebook PHP SDK.
The upcoming code snippets are a short self contained correct example of my approach. If I try to use my app it requests login, then asks for permissions and then fails in printing all my friends due to the fact that no session is available. What's wrong here?
First is the birthday.php which is used by the following index.php, I removed some boilerplate code or code I think it's not causing this problem (identified by [...]). You can find the complete code on the end of this question.
<?php
function get_birthday_of_friends() {
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
try{
include_once "facebook/src/facebook.php";
}
catch(Exception $o){
// [...] log error
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
// [...] return birthdays
} else {
echo "No session found";
}
}
?>
The required lib.php is identically with the insights example.
<?php
// [...] Include and define app-id etc.
function get_access_token($base_url) {
if (isset($_REQUEST['access_token'])) {
return $_REQUEST['access_token'];
}
$params = array();
$params['client_id'] = APP_ID;
$params['redirect_uri'] = $base_url;
if (!isset($_REQUEST['code'])) {
$params['scope'] = 'read_friendlists, friends_birthday';
$url = FacebookMethods::getGraphApiUrl('oauth/authorize', $params);
throw new RedirectionException($url);
} else {
$params['client_secret'] = APP_SECRET;
$params['code'] = $_REQUEST['code'];
$url = FacebookMethods::getGraphApiUrl('oauth/access_token');
$response = FacebookMethods::fetchUrl($url, $params);
$response = strstr($response, 'access_token=');
$result = substr($response, 13);
$pos = strpos($result, '&');
if ($pos !== false) {
$result = substr($result, 0, $pos);
}
return $result;
}
}
// [...] Call get_access_token() and get_birthday_of_friends()!
?>
Can you help me with that? I added the whole source code on pastebin.com if this helps you to identify my problem. Source code on pastebin.com for "index.php" and "birthday.php".
Thank you in advance!
I am not sure if the method that you are using is deprecated or not, but I know it's the old way and you should try with the new one in order to get the auth token.
Take a look at this link:
http://developers.facebook.com/docs/authentication/signed_request/
In a glance, you have to:
Get the signed_request parameter from $_REQUEST.
Use the sample function provided in
the link to decode it Once you decode
it, you will have an array in which
there is a parameter called
oauth_token.
With this parameter, you can start
making calls to the Graph by
appending it to the URL e.g.
*https://graph.facebook.com/PROFILE_ID/pictures/?access_token=OAUTH_TOKEN*
Make sure that you have Oauth 2.0 for Canvas enabled into the Configuration settings of your app (Advanced tab).
I think in some browsers there's a prblem with third party cookies. Are you testing in Safari? And also, try to add permissions to the loginUrl - it's a bit more simple than adding and requesting the permissions with oauth.
If no session is available, I had to redirect to the login page and require the extended permissions with the parameters. This did the trick to me, thanks to manuelpedrera for helping me out.
$facebook->getLoginUrl(array('req_perms' => 'read_friendlists, [...]'));

Categories