facebook open graph count shares using PHP SDK - php

As from Facebook documentation I can get the count of shares for a web page calling the following url https://graph.facebook.com/?id=http://www.google.it, the returned data are the following:
{
"share": {
"comment_count": 0,
"share_count": 636734
},
"og_object": {
"id": "389545309239",
"title": "Google",
"type": "website",
"updated_time": "2017-06-08T10:05:50+0000"
},
"id": "http://www.google.it"
}
I want to get the same data using the PHP SDK using the following code:
//require the Facebook PHP SDK
$client_id="my app id";
$client_secret="my secret key";
$default_access_token = file_get_contents( "https://graph.facebook.com/oauth/access_token?client_id=$client_id&client_secret=$client_secret&grant_type=client_credentials");
$OGResponse = new Facebook\Authentication\AccessToken($default_access_token);
$access_token = json_decode($OGResponse)->access_token;
$fb = new Facebook\Facebook([
'app_id' => $client_id, // Replace {app-id} with your app id
'app_secret' => $client_secret,
'default_access_token' => $access_token,
]);
$helper = $fb->getRedirectLoginHelper();
$request = new \Facebook\FacebookRequest(
$fb->getApp(),
$access_token,
'GET',
'/',
array(
'id' => 'http://www.google.it',
)
);
$response = $fb->getClient()->sendRequest($request);
//$response = $request->execute();
$graphObject = $response->getGraphObject();
Accessing the $graphObject I can retrieve the same data except the ones in "share" key, that are what I'm interested.
If I use the GRAPH API Explorer, I get the same info using the PHP SDK:
{
"og_object": {
"id": "389545309239",
"title": "Google",
"type": "website",
"updated_time": "2017-06-08T10:05:50+0000"
},
"id": "http://www.google.it"
}
Is there any way to get the "shares" using the PHP SDK?

try this
graph api explorer v2.8
but you cannot get share field with graph api v2.9 because share field is deprecated for versions v2.9 and higher,or you can use engagement field like this graph api explorer v2.9
for PHP SDK:
$request = new \Facebook\FacebookRequest(
$fb->getApp(),
$access_token,
'GET',
'/',
array(
'id' => 'http://www.google.it',
'fields' => 'engagement,og_object',
)
);
then you will get something like this
{
"engagement": {
"reaction_count": 207037,
"comment_count": 125335,
"share_count": 304362,
"comment_plugin_count": 0
},
"og_object": {
"id": "389545309239",
"title": "Google",
"type": "website",
"updated_time": "2017-06-08T15:58:56+0000"
},
"id": "http://www.google.it"
}

Related

How to authorize API endpoint through header using wp_remote_get()?

I am testing API Football on my WP site and facing a difficulty in authentication. I have tested endpoint on postman and everything works fine but as soon as I test it on WP it gives me following response with error:
{ "get": "status", "parameters": [], "errors": { "token": "Error/Missing application key. Go to https://www.api-football.com/documentation-v3 to learn how to get your API application key." }, "results": 0, "paging": { "current": 1, "total": 1 }, "response": [] }
My WP code is:
$response = wp_remote_get( 'https://v3.football.api-sports.io/status', array(
'headers' => array(
'x-apisports-key' => $this->api_key
)
) );
$response_body = wp_remote_retrieve_body( $response );
return json_decode( $response_body );
I have tried php curl too but still getting same problem. For some reason I don't want to try it on rapidapi.
I have tried php cURL too but still getting same error. For some reasons I don't want to use rapidapi.

Google Logging API v2 Authentification troubles

I'm trying to authentificate by OAuth token but i didn't find the way to get it without Google prompt and url redirection.
I'm using php and google/apiclient:"^2.7" library
I try to get token with it but I didn't find the way to get it.
If it's not possible to perform it without a google prompt, how I can authenticate my request to the https://logging.googleapis.com/v2/entries:list?
Thanks in advance for your help.
I tried with the following method
public function init()
{
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $this->container->getParameter('service-account-authentification-file'));
$scopes = [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-platform.read-only',
'https://www.googleapis.com/auth/logging.admin',
'https://www.googleapis.com/auth/logging.read',
'https://www.googleapis.com/auth/logging.write'
];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://logging.googleapis.com/',
'auth' => 'google_auth'
]);
$httpClient = $client->authorize();
$data = [
"resourceNames" => ["xxxx"],
"filter" => "xxxxxx",
];
$response = $httpClient->post('https://logging.googleapis.com/v2/entries:list', [
'body' => json_encode($data)
]);
}
I also tried with this other method provided by the https://github.com/googleapis/google-cloud-php & https://github.com/googleapis/google-cloud-php-logging
$logging = new LoggingClient([
'keyFilePath' => $this->container->getParameter('service-account-authentification-file')
]
);
$entries = $logging->entries([
'filter' => 'logName = projects/****logs/stdout'
]);
foreach ($entries as $entry) {
echo $entry->info()['textPayload'] . "\n";
}
Response is always the same
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
I tried to use Curl
curl --request POST \
'https://logging.googleapis.com/v2/entries:list?key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{}' \
--compressed
but i have such error too
{
"error": {
"code": 400,
"message": "The API Key and the authentication credential are from different projects.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developer console API key",
"url": "https://console.developers.google.com/project/******/apiui/credential"
}
]
},
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CONSUMER_INVALID",
"domain": "googleapis.com",
"metadata": {
"consumer": "projects/******",
"service": "logging.googleapis.com"
}
}
]
}
}

Facebook PHP Graph API not returning complete data

I'm having an issue with Facebook's PHP SDK version 4.0.
I'm simply trying to retrieve the insights/page_fans_city metric via the Graph API:
$request = new FacebookRequest($session, 'GET',
'/{my object}/insights/page_fans_city',
array('period' => 'lifetime'));
$response = $request->execute();
$client_graph_object = $response->getGraphObject();
print_r($client_graph_object);
However, no data is returned:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[data] => Array
(
)
[paging] => stdClass Object
(
[previous] => https://graph.facebook.com/v2.0/...
[next] => https://graph.facebook.com/v2.0/...
)
)
)
I know that I have the Insights data that I'm requesting. I can make the exact same request via the Graph Explorer:
→ /v.2.0/{my object}/insights/page_fans_city?period=lifetime
{
"data": [
{
"id": "{my object}/insights/page_fans_city/lifetime",
"name": "page_fans_city",
"period": "lifetime",
"values": [
{
"value": {
...
},
"end_time": "2014-08-01T07:00:00+0000"
},
{
"value": {
...
},
"end_time": "2014-08-02T07:00:00+0000"
}
],
"title": "Lifetime Likes by City",
"description": "Lifetime: Aggregated Facebook location data, sorted by city, about the people who like your Page. (Unique Users)"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.0/...,
"next": "https://graph.facebook.com/v2.0/...
}
}
I should note that I am receiving data if I omit the page_fans_city segment. When it's omitted- I can view data for page_fans_country only. Therefore
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights/page_fans_country',
array('period' => 'lifetime'));
and
$request = new FacebookRequest($session, 'GET',
'/{myobject}/insights',
array('period' => 'lifetime'));
will work for me ...
I suspect it's my Access token- but I'm not sure why that would be the case. The app that I created only requires the read_insights permission.
Any thoughts or suggestions?
Thanks in advance,Mike
It was a permissions issue. If you ever see:
{
"data": [
],
...
}
It's likely your access token does not have sufficient privileges to access the data you're requesting (that or there's simply no data).
My problem was that even though I was the Developer of the app and it was approved by Facebook (with the manage_pages and read_insights permissions)- I could not use an app access token to retrieve the insights data.
I needed a user access token!
I easily generated the user access token by manually creating a login flow per Facebook's documentation. This stackoverflow thread was useful, too.
More info on Facebook tokens here.
Hope this helps anyone who stumbles across this thread!
-Mike

Posting a link to a page not showing up?

<?php
$appId = 'XXXXX';
$pageId = 'XXXXX';
$secret = 'XXXXX';
$token = 'XXXXX';
$data = array(
'access_token' => $token,
'description' => 'test_description',
'link' => 'http://www.google.co.uk',
'message' => 'test_message',
'name' => 'test_name'
);
try
{
require_once 'facebook/facebook.php';
$sdk = new Facebook(
array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
)
);
$post = $sdk->api('/'.$pageId.'/feed', 'POST', $data);
print_r($post);
}
catch (FacebookApiException $e)
{
echo $e;
}
?>
Using the code above I am trying to post a link to Google on my page wall. When I run the code, I get an ID response which is what I would expect. However nothing shows up on the page, despite having a valid ID.
If I remove the "link" and try again, I get another ID and the post is visible on my page.
Am I doing something wrong?
Why should the "link" value cause an ID to be returned but no post to be displayed?
This is what Facebook sees (queried via the Graph API explorer):
{
"id": "484729401573953",
"created_time": "2013-01-08T12:03:27+0000",
"caption": "www.readesresidential.com",
"description": "test_description",
"from": {
"name": "David Reade",
"id": "100003544363105"
},
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"link": "http://www.readesresidential.com/brookside-crescent-northop-hall-ch7-6hw-ps03009/",
"message": "test_message",
"name": "test_name",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQC7MpbP6aNe2CVP&w=90&h=90&url=http%3A%2F%2Fwww.readesresidential.com%2Fframework%2Fstatic-487d%2F2%2Fimg%2Fv3%2Ffacebook.png",
"privacy": {
"description": "Friends",
"value": "ALL_FRIENDS",
"allow": "",
"deny": "",
"networks": "",
"friends": ""
}
}
I can see it says "ALL_FRIENDS" - could this be what's causing the post to not be displayed? You can't be friends with a page can you?
I have now modified the "data" variable to the following:
$data = array(
'access_token' => $token,
'description' => 'test_description',
'link' => 'http://www.readesresidential.com/go/ps02618',
'message' => 'test_message',
'name' => 'test_name',
'privacy' => array(
'value' => 'EVERYONE'
)
);
The response from the Graph API explorer is:
{
"id": "454654274601000",
"created_time": "2013-01-08T12:14:52+0000",
"caption": "www.readesresidential.com",
"description": "test_description",
"from": {
"name": "David Reade",
"id": "100003544363105"
},
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif",
"link": "http://www.readesresidential.com/church-street-tarvin-ch3-8eb-ps02618/",
"message": "test_message",
"name": "test_name",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQC7MpbP6aNe2CVP&w=90&h=90&url=http%3A%2F%2Fwww.readesresidential.com%2Fframework%2Fstatic-487d%2F2%2Fimg%2Fv3%2Ffacebook.png",
"privacy": {
"description": "Public",
"value": "EVERYONE",
"allow": "",
"deny": "",
"networks": "",
"friends": ""
}
}
Even though the post is now "public" and I have used a completely new URL, it's still not showing.
Could this be a Facebook bug?
Why should the "link" value cause an ID to be returned but no post to be displayed?
This usually happens if the same link is posted again by the same user (with only a certain amount of time between those two posts).
After some fiddling with the code, I found out how to fix this. Turns out the access token I was using was incorrect, even though the debugger tool said it was valid and had the appropriate permissions.
I had to query the Graph API, in particular the /me/accounts bit using the access token which returned the page info but and a completely different access token. This access token in question has no expiration time (I thought this feature was no more??) and after inserting it into my code, the posts now display properly for all users.
None of these steps were in the Facebook documentation anywhere, and if they are then they're extremely hard to find.

How to share a public photo in a group php sdk facebook

I'm trying to share a public photo to a group using php sdk (graph api)
$ret_obj = $facebook->api("/$group_id/feed", 'POST', array(
'link' => $link,
'message' => $message,
)
);
where $link is a link for the photo I want to share in this format : https://www.facebook.com/photo.php?fbid=10151273906386749&set=a.53081056748.66806.6815841748&type=1&theater
it didn't work so I also tried this in Graph Api Explorer,
in result i get :
{
"error": {
"message": "(#100) property values must be strings or objects with a 'text' and a 'href' attribute",
"type": "OAuthException",
"code": 100
}
}

Categories