Get page access token with Facebook API 5.0 PHP - facebook

I need to post messages on a Facebook page. Specifically I want to post via cron.
Here's what the API docs say:
Page Access Token – These access tokens are similar to user access tokens, except that they provide permission to APIs that read, write or modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token and asking for the manage_pages permission. Once you have the user access token you then get the page access token via the Graph API.
How I can obtain a user access and page access token without a page callback? Is this possible?

What you need it an Extended Page Token, it is valid forever. You get one like this:
Authorize with the manage_pages permission (and publish_pages if you want to post as Page later), to get a User Token
Extend the User Token
Use /me/accounts?fields=access_token with the Extended User Token to get a list of all your Pages with Extended Page Tokens - or use /page-id?fields=access_token to get an Extended Page Token for a specific Page
Information about all Tokens and how to extend the User Token:
https://developers.facebook.com/docs/facebook-login/access-tokens#extending
http://www.devils-heaven.com/facebook-access-tokens/

PHP API V5
The below code worked for me after 24 hours of head scratching .... hope this helps by the way if you need this code to work you should have completed the first two steps
Should have login to facebook I used getRedirectLoginHelper
Set session variable with the received user access token on the call back file $_SESSION['fb_access_token'] = (string) $accessToken;
$fbApp = new Facebook\FacebookApp( 'xxx', 'xxx', 'v2.7' );
$fb = new Facebook\Facebook( array(
'app_id' => 'xxx',
'app_secret' => 'xxx',
'default_graph_version' => 'v2.7'
) );
$requestxx = new FacebookRequest(
$fbApp,
$_SESSION['fb_access_token'],//my user access token
'GET',
'/{page-id}?fields=access_token',
array( 'ADMINISTER' )
);
$responset = $fb->getClient()->sendRequest( $requestxx );
$json = json_decode( $responset->getBody() );
$page_access = $json->access_token;
//posting to page
$requesty = new FacebookRequest(
$fbApp,
$page_access ,
'POST',
'/{page-id}/feed?message=Hello fans YYYYYYYYYYYYYYY'
);
$response = $fb->getClient()->sendRequest( $requesty );
var_dump( $response );

You can get the page token this way:
$response = $fb->get('/'.$pageId.'?fields=access_token', (string)$accessToken);
$json = json_decode($response->getBody());
$page_token = $json->access_token;
$response = $fb->post('/'.$pageId.'/feed', $fbData, $page_token);

I've only JavaScript code, but once you have an access token, you may get the pages which can be adminstered by the given user. This will contain a page access token for each of them:
jQuery.ajax({type: "GET",
url: "https://graph.facebook.com/v2.2/me/accounts?access_token=" + userToken,
async: false,
data: jsonRequest,
dataType: "json",
cache: false,
success: function(data)
{
The data given back is like:
{
"data": [
{
"access_token": "CAACni8TcBB0B...cZBJfwZDZD",
"category": "Computers/Technology",
"name": "abc",
"id": "...",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
]
},
{
"access_token": "CAA...ZDZD",
"category": "App Page",
"name": "xyz",
"id": "....",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
]
}
],
access_token is your page token. You may transform the above request into PHP easily.

Related

Retrieving google photos with IONIC 3 with google photos API

I am working on an IONIC application.
In this app the user will be able to get photos from his google photos account and do some design manipulations on the image he selected.
So for that I want to use the google photos API
I did not find any example on how to accomplish this in IONIC.
So I am looking for some sample code or guid on how to get this done.
=======================================================
UPDATE
I tried to do it like this:
Login to google with: cordova-plugin-googleplus
And request the https://www.googleapis.com/auth/photoslibrary
scope
Here is the code:
//Here we do a login.
this.gplus.login({
'webClientId': '***********',
'offline': true,
'scopes': 'profile email https://www.googleapis.com/auth/photoslibrary'
}).then((res) => {
//after login we try to get the google photos albums
this.http.get('https://photoslibrary.googleapis.com/v1/albums', {
responseType: ResponseContentType.Json,
params:{
accessToken: res.accessToken,
pageSize: 50,
}
}).subscribe(res=>{
console.log('<--- google images res: ', res);
},err=>{
console.log('<--- google images err: ', err);
});
});
Now I get an error 'Expected OAuth 2 access token'
Here is the full error description:
Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.
==========================================================
UPDATE 2
So after some research I am trying to get the OAuth 2 access token like this:
//Here we do a login.
this.gplus.login({
'webClientId': '***********',
'offline': true,
'scopes': 'profile email https://www.googleapis.com/auth/photoslibrary'
}).then((res) => {
//after login we need to get the OAuth 2 access
//I think like this:
this.http.post('https://www.googleapis.com/oauth2/v4/token', {
code: res.serverAuthCode,
client_id: '*****************',
client_secret: '*************',
redirect_url: '***************',
grant_type: 'authorization_code'
},{
responseType: ResponseContentType.Json
}).subscribe(res=>{
//after we got the OAuth 2 access, we try to get the google photos albums
let myHeaders= new Headers();
myHeaders.append('Content-Type', 'application/json');
this.http.get('https://photoslibrary.googleapis.com/v1/albums', {
responseType: ResponseContentType.Json,
params:{
pageSize: 50,
accessToken: {'bearer': res['_body'].access_token},
},
headers: myHeaders
}).subscribe(res=>{
console.log('<--- google images res: ', res);
},err=>{
console.log('<--- google images err: ', err);
})
},err=>{
......
})
}
}), err => {
.....
});
But still getting the same error:
Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.
So now the question is how do is get an OAuth 2 access token ?

can't exchange token manually v2.7

I'm using Loopback and
I'm trying to user auth for graph api without javascript sdk or passport
I got the code successfully however I can't exchange it with access token
I followed this guide https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/#confirm
my get request is https://graph.facebook.com/v2.7/dialog/oauth?code={xxxx}&client_secret={xxxx}&client_id={xxx}&redirect_uri={myURL}
myURL is the one used to get the code but not be used again if I understand
If I understand correctly I should it the access_token in the body of the response instead I get this error
{
"error": {
"message": "Unknown path components: /oauth",
"type": "OAuthException",
"code": 2500,
"fbtrace_id": "HXe+214tGpW"
}
}
It looks like a bug in the docs. The first call is to www.facebook.com in a browser.
See here for an example client https://github.com/yschimke/oksocial/blob/master/src/main/java/com/baulsupp/oksocial/services/facebook/FacebookAuthFlow.java
The second should be to something like https://graph.facebook.com/v2.7/oauth/access_token
$response = $fb->sendRequest(
'GET',
'/oauth/access_token',
[
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $short_token
],
$short_token,
null,
'v2.7');

Facebook Mutual Friends API

Using the Facebook Graph API (v2.4), I can't seem to access any information about mutual friends, not even the total count.
Here's my graph query (User ID changed for privacy purposes):
https://graph.facebook.com/v2.4/123456789?fields=context.fields(mutual_friends)
The result I get is:
{
"context": {
"id": "dXNlcl9jb250ZAXh0OgGQBqWf9ZAHMZA1yjZBJZABsMDkDORNsle8wkS8Acci9r4FsOdyRVl1TSGSXAsofmlaWYS05piSZCV9F1QwNNs0L9XpNuGLAaLyMk8Fnaiwyxpm5shUZD"
},
"id": "123456789"
}
I tried using FB's iOS SDK to make the same query as well, but got the same result.
Any suggestions?
The all_mutual_friends, mutual_friends, and three_degree_mutual_friends context edges of the Social Context API were deprecated on April 4, 2018 and immediately started returning empty data sets. They have now been fully removed.
The {user_id} must be another user of your app, and the user access token you MUST use is from another user of your app.
Then
GET /{user_id}?fields=context{mutual_friends}&access_token={other_users_access_token}
should work and give results, if both users gave your app the user_friends permission.
See
https://developers.facebook.com/docs/graph-api/reference/user-context#Reading
https://developers.facebook.com/docs/graph-api/reference/user-context/mutual_friends/
function aa_mutl_frnd(x, row)
{
FB.init({
appId : '<?php echo get_option('_fb_apps_id');?>', //Facebook apps id using theme option
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5' // use graph api version 2.5
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
console.log(':acc_tk:'+accessToken);
//////////////////////////////////////////////////////////
var data={
'action': 'wq_accss_tkn_gnrt',
'ddt' : accessToken
}
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function (response) {
console.log(':acc_tk2:'+response);
FB.api(
"/"+x+"",
{
"fields": "context.fields(all_mutual_friends)",
//"access_token": '',
"appsecret_proof": response,
},
function (response) {
console.log(response);
}
);
});
////////////////////////////////////
}
});
}
/// ajax part /////
add_action('wp_ajax_wq_accss_tkn_gnrt', 'wq_accss_tkn_gnrt');
add_action('wp_ajax_nopriv_wq_accss_tkn_gnrt', 'wq_accss_tkn_gnrt');
function wq_accss_tkn_gnrt() {
echo hash_hmac('sha256',$_POST['ddt'],'app_secret');;
die();
}

Facebook Extended access token server side with client side login

I am using client side sdk for Login and in server side php sdk for 'wall posting' on a triggered action using graph api ( I was using it with offline_access but now I know its deprecated ).
How to get Extended access token in Server-side using client side sdk so that I can use the extended token in server side,
I know some answers are there like here, but they use Server-side login and get extended token from $_REQUEST['code'] which they get in response,
I there any way that I can get the value of $_REQUEST['code'] using client side login?
Update:
My client login code supports oAuth:
FB.init({
appId : 'MYAPPID', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enable OAuth 2.0
});
FB.login(function() {
FB.api('/me', {'fields': "some coma seperated fields"},
function(response){
//Function that sends data to server
Pass_data_to_server( response );
});
}, scope:'some scope values');
Server side code:
<?php
$settings = array
(
'appId' => FB_APP_ID,
'secret' => FB_APP_SECRET,
'cookie' => true,
'oauth' => true
);
// Get facebook object from facebook sdk class
$facebook = new Facebook($settings);
if ($facebook)
{
$user_id = $facebook->getUser();
$facebook->setExtendedAccessToken(); //long-live access_token 60 days
$token = $facebook->getAccessToken();
try
{
$response = $facebook->api('me/og.like', 'POST',{ $MYCUSTOMDATA});
return $response;
}
catch (FacebookApiException $e)
{
print_r($e)
return false;
}
}
?>
You can extend your access token using the Facebook PHP SDK method
setExtendedAccessToken()
This will automatically extend your short term extended access token by calling the end point
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
You can then save this access token for authorizing the requests for next 60 days.

Facebook API How To Get All Pages I Like Without Pagination

If I like more than 100 pages/things, FB.API('me/likes') returns 99 items and a link to the next paging.
Is it possible to get ALL without the pagination?
Thanks
Have you tried /me/likes?limit=999 ?
You may still need to paginate, but you should be able to get more than 99 items in a single call
Use FQL:
$fql = "SELECT page_id from page_fan where uid = me())";
$pages_i_liked = $facebook->api(array(
'method'=> 'fql.query',
'access_token' => $access_token,
'query'=> $fql,
));
print_r($pages_i_liked);
Get All facebook pages of a user using facebook api
required permissions: manage pages
type: GET
url: https://graph.facebook.com/me/accounts
param: access_token
responce of the above request like this
{
"data": [
{
"category": "Book",
"name": "Mind blowing books",
"access_token": "CAACEdEose0cBAFRU2j0rGgNxBcJvU0pkZCpDbI7rZCJNmO2cZAfZBXoejoZCdTVdKi4gNCyBuu9fPRnWRAwCKrmkPePzKHoE5e46Jz7gRDYe3PM5ECm0ZC5OZB2iWLeEh3OZBgTGfWDmQbbFivwlp5v2umc0CcC9JlTvHsWDnTZCkKIbZAJeD2nOus1ZCCXMqSXHOAZD",
"perms": [
"ADMINISTER",
"EDIT_PROFILE",
"CREATE_CONTENT",
"MODERATE_CONTENT",
"CREATE_ADS",
"BASIC_ADMIN"
],
"id": "618353601555775"
}
],
"paging": {
"next": "https://graph.facebook.com/100000328561058/accounts?access_token=CAACEdEose0cBADKMTNRBl5pjNhw8xsKnQf57XKShV7UlhGyJy67bBZCUKkepl9rELlxqq0I474f8LEPGnt51Mdgs0MMtgTycuUgkOyRnLgVypWVpBd7oKy3LXrrbsQWSdIUZBU4qKHLxSb14TP8ySOaZChLseseYMr1YMLG3qrJiWLuwWJeVz2PeE8TmkkZD&limit=5000&offset=5000&__after_id=618353601555775"
}
}
Post at specific facebook page of a user using facebook api
required permissions: piblish action
type: Post
url: https://graph.facebook.com/{PAGE_ID}/feed
param: access_token, message
this http request will write your message on fb page
PAGE_ID: its page id which is in responce of first request
The maximum results limit is 100
"I just noticed this while counting the results and also next page query, if I insert limit 999 for example, the exact results will be shown as 100 and the next link generated by facebook will contain the limit value also 100"
With this class from Github: FacebookLikedPagesAPI you can get all ID liked pages on Facebook without pagination
$access_token = '';// your access token here
$likes=new Likes();
$result=$likes->getAllLikedPages($access_token);