Facebook API php - Post a news item to a facebook group - php

*strong text*I have a website that publishes articles every day.
I want to have a corresponding Facebook group that I can publish the articles to at the same time as on my site.
I have set up a similar arrangement in twitter using the api. When I publish an article to my site I it automatiaclly posts the headline and link back to twitter via the twitter API. I would like to have a similar arrangement for my facebook group.
Is it possible to have my stories forwarded to my facebook group wall?
EDIT
Ok, I have gotten this far, and no further:
Step 1: Get authorisation to publish to the stream
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?client_id=XXXXXXXXXX&client_secret=XXXXXXXXXXXXtype=client_cred&scope=publish_stream', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
$tokens = explode("access_token=",$content);
// do something with the content here
$auth_token = $tokens[1];
fclose($fp);
} else {
// echo" an error occured when trying to open the specified url";
}
Step 2: send my message to the stream using my authorisation code (I have chosen to use cURL):
$message="This will be a post on my groups wall.";
$url = "https://graph.facebook.com/my_app_id/feed";
$data = array('message' => $message, 'auth_token' => $auth_token);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl_handle,CURLOPT_URL,$url);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer))
{
print "Nothing seems to have happened";
}
else
{
print $buffer;
}
The code runs with no errors, but nothing gets returned and nothing gets posted to the wall
any ideas?

Facebook treats pages similar to the way they treat people, you specify a UID which is associated with the Page ID of your group. Then just use Facebook's Graph API to post to the stream, just as you would a person.
To authorize, you get Facebook API permission from an admin and request the manage_pages permission.
All of the information you need is contained here: https://developers.facebook.com/docs/reference/api/#impersonation.
(Ctrl+F Page Login for more information on authorizing to update to pages).

Related

PHP Fetch image from DM Twitter using REST API?

I have problem when I want to fetch image that was sent to my DM.
So when I fetch the DM data from API, I got the media id for the image but how to fetch it?
I want to fetch the image and tweet it to my account.
So basically:
Someone send DM to me with media
I read my account DM from API
Tweet DM content to my account
Here is my code
$AMConnection = new \Twitter\OAuth(AM_CONSUMER_KEY, AM_CONSUMER_SECRET);
$AMConnection->setAccessToken($amService->token, $amService->secret);
$jsonData = json_decode(file_get_contents("./fetchDM.json"));
foreach ($jsonData as $json) {
if (!isset($json->entities->media)) continue;
$medias = $json->entities->media;
$postParam['status'] = $json->text;
foreach ($medias as $image) {
$postParam['status'] = str_replace($image->url, "", $postParam['status']);
$postParam['media_ids'][] = $image->id_str;
}
echo "SEND TWEET".PHP_EOL;
$return = $AMConnection->post('statuses/update', $postParam);
var_dump($return);
if (isset($return->errors) and count($return->errors) > 0) {
foreach ($return->errors as $error) {
if ($error->code == 89) {
$amService->token = null;
$amService->secret = null;
$amService->save();
break;
}
}
}
}
On my code, I was tried to tweet media using media_id but it doesn't work.
Sorry for bad english
Finally it's solved.
So I've been look for this one on some forums but only 2 forum has answer, 1 on twitter forum (sorry I don't have link) and another 1 StackOverflow
I'm using library and try messing out with it but deadend. The library that I've used to request REST API, use OAuth request from URL and POST data. Yeah, it's totally work (only for REST API) but this one is totally different.
To fetch image from DM, YOU MUST REQUEST USING HEADER AUTHORIZATION and no other way.
On my sample, I want to try to fetch https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg (This one is image url from DM, so only me and someone who've sent me that image only can see it).
I'm using CURL PHP to fetch the image so the request will be like this
<?php
$this->http_info = array();
$ci = curl_init();
$url = 'https://ton.twitter.com/1.1/ton/data/dm/863758539021365258/863758532109246464/VSSysEvy.jpg';
$headerAuth = 'Authorization: OAuth oauth_version="1.0",
oauth_nonce="{autoGeneratedNonce}",
oauth_timestamp="{time()}",
oauth_consumer_key="{yourAppToken}",
oauth_token="{userToken}",
oauth_signature_method="HMAC-SHA1",
oauth_signature="{autoGeneratedSignature}"';
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, 'LShaf User Agent');
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, [$headerAuth]);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_HEADER, FALSE);
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
curl_close ($ci);
Note: You MUST use method GET and put Authorization on HEADER.
And for the last thing, I'm sorry for my bad english.

Retrieving Facebook / Google+ / Linkedin profile picture having email address only

What I need
I need to automatically find & download profile picture for user knowing his email address only. Originally, I focused on Facebook considering the amount of people actively using it. However, there seem to be no direct support from their API anymore.
There was similar question here:
How to get a facebook user id from the login email address which is quite outdated and current answers there are "it's deprecated" / "it's not possible"...
EDIT: I've found even better question: Find Facebook user (url to profile page) by known email address (where it is actually explained why and since when this feature isn't supported)
There must be a way...
What makes me think that this should be possible is that Spokeo is somehow doing it:
http://www.spokeo.com/email-search/search?e=beb090303%40hotmail.com
There are some services / APIs offering this kind of feature:
Clearbit
Pipl
...but I haven't found anything free.
Alternatives
If there is some workaround or different approach than using Facebook's API to achieve this, I would like to know. If Facebook is really completely hopeless here, then combination of these: Google+, Linkedin and/or Gravatar could do.
My first (original) attempt:
Once you have Facebook's username or user ID, it's easy to build URL to download the picture. So I was trying to look for Facebook's user IDs using emails with the /search Graph API:
https://graph.facebook.com/search?q=beb090303#hotmail.com&type=user&access_token=TOKEN
which unfortunatelly always ends with "A user access token is required to request this resource."
Using FB PHP API + FB App ID & Secret
I've also tried this: at first I retrieve access_token using app ID and secret and then I'm trying to use it as a part of /search request with curl:
function post_query_url($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
function get_query_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
function get_retrieve_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token?client_id='.$app_id.'&client_secret='.$secret.'&grant_type=client_credentials';
$res = get_query_url($url);
if (!empty($res)) {
$tokens = explode('=', $res);
if (count($tokens) == 2)
return $tokens[1];
}
return null;
}
function post_retrieve_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token';
$data = 'client_id='.$app_id.'&client_secret='.$secret.'&grant_type=client_credentials';
$res = post_query_url($url, $data);
if (!empty($res)) {
$tokens = explode('=', $res);
if (count($tokens) == 2)
return $tokens[1];
}
return null;
}
function get_id_from_email($email, $accessToken) {
$url = 'https://graph.facebook.com/search?q='.urlencode($email).'&type=user&access_token='.$accessToken;
$res = get_query_url($url);
if (!empty($res)) {
return $res;
}
return null;
}
echo 'Retrieving token...<br>';
$token = post_retrieve_app_access_token('MY_APP_ID', 'SECRET');
echo 'Retrieved token: ' . $token . '<br>';
echo 'Retrieving user ID...<br>';
$id = get_id_from_email('beb090303#hotmail.com', $token);
echo 'Retrieved ID: ' . $id . '<br>';
outputs something like:
Retrieving token...
Retrieved token: 367458621954635|DHfdjCnvO243Hbe1AFE3fhyhrtg
Retrieving user ID...
Retrieved ID: {"error":{"message":"A user access token is required to request this resource.","type":"OAuthException","code":102}}
Other info
Since it's asking for "user access token", I've also tried to go to Facebook's Graph Explorer: https://developers.facebook.com/tools/explorer/
let it generate access token for me and queried:
search?q=beb090303#hotmail.com&type=user&debug=all
That one ends with:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
...so Facebook seems kinda hopeless here.
That's exactly why Gravatar exists and why people use Gravatar, users know which public profile image they bind to which e-mail address and they know where to change it.
Your app can have the possibility for users to upload their own profile image and fallback to Gravatar.
If you just try to extract an image from Facebook or Google+, it might freak your users out and it will also be harder for them to know where your service got the profile image from.
Using Gravatar in PHP it is as simple as this:
<?php
$email = "email#server.com";
$default = ""; // absolute url to default image goes here or leave empty for default gravatar image
$size = 200;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . urlencode($default) . "&s=" . $size;
header("content-type: image/jpeg");
echo file_get_contents($grav_url);
?>
Apart from that, you can also use Facebook and/or Google+ as external login providers where users can grant your application access to their profile information.
There was a bug: Can't search for user by email after July 2013 Breaking Changes that has been closed as "By Design" with official response:
"The ability to pass in an e-mail address into the "user" search type was removed on July 10, 2013. This search type only returns results that match a user's name (including alternate name)" ~ Joseph Tuấn Anh Phan (Facebook Team)
so probably no direct support from Graph API.
I've tried Graph API Explorer where you can try to play with some FQL too (just need to select version 2.0 as newer versions are not supported anymore), unfortunately query like:
SELECT uid, name FROM user where email = 'some.email#gmail.com'
gives:
"error": {
"message": "(#604) Your statement is not indexable. The WHERE clause must contain
an indexable column. Such columns are marked with * in the tables linked from
http://developers.facebook.com/docs/reference/fql ",
"type": "OAuthException",
"code": 604
}
and reference for table user shows that only uid and third_party_id can be used in WHERE.
You should need access token as well as Facebook id of the user. without knowing them cannot get their profile pic
I think Spokeo might have an agreement with Facebook to access the data? I would not be surprised.
Anyway, if you are on a profile you can maybe search for profile_id in the HTML. It's a hack, not sure if it works.
You could always allow people to comment by logging in with their g+/facebook/whatever account (requires you to do something OpenID-like, though); if they've logged in, you should be able to get the facebook uid.
Also, there's something called libravatar, which allows people to associate pictures with their OpenID or email address (and which falls back to gravatar if they haven't configured anything specifically for libravatar); using that should give you more photos than if you stick to "just" gravatar.

curl not working for linkedin profile of my connections

I want email id of my friends from linkedin. Till now I got url of my site request url of friends. Which is like https://www.linkedin.com/profile/view?id=xxx&authType=name&authToken=xxx&trk=api*a4152951*s4217191*
(Linkedin API IN.API.Connections("me").result( function(me) { } )
From this url I have to get email address.So I am using curl.
Here is my code:
$ch = curl_init("https://www.linkedin.com/profile/view?id=259116153&authType=name&authToken=S9sN&trk=api*a4152951*s4217191*");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$rr = curl_exec($ch);
//curl_close($ch);
echo $rr;
I also tried this but not working (blank page):
$url = $_POST['links'];
$contents = file_get_contents($url);
$dom = new DOMDocument();
#$dom->loadHTML($contents);
$dom->preserveWhiteSpace = false;
$xpath = new DOMXPath($dom);
$hrefs = $xpath->query("//li[#id='contact-field']");
for ($i = 0; $i < $hrefs->length; $i++)
echo $hrefs->item($i)->nodeValue;
if(!$hrefs) echo 'Not found';
echo $hrefs->nodeValue;
And one more thing if put that url in browser I can see email by click the conatct info button which make display:block (CSS).
Scraping data from LinkedIn is explicitly prohibited by our Terms of Use. The proper way to retrieve data would be via a REST API call.
Requesting a LinkedIn member's email address requires your application to be requesting a special OAuth permission called: r_emailaddress
Make sure your application is configured to request that permission, and then use the following REST API call to retrieve a member's email address:
https://api.linkedin.com/v1/people/id={targetMemberID}:(email-address)
Additional information about making REST API calls can be found here: https://developer.linkedin.com/documents/profile-api

Check if the user is a fan of my facebook page?

I used to use the flowing code to check if the user is a fan of my page or not while he is on my facebook page. Now I want to check if the user is a fan of my facebook page while he is on my WEBSITE.
<?php
$signed_request = $_REQUEST["signed_request"];
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);
if (empty($data["page"]["liked"])) {
echo "You are not a fan!";
} else {
echo "Welcome back fan!";
}
?>
I read through the facebook documentation, but I was not able to find suitable answer.
Help ?
I do not want to deal with any application permissions with facebook. How can I approach this through only php ?
You will not get page details if visiting application not in Page Tab.
You may achieve that with simple FQL query to page_fan table (knowing the id of the Facebook Page of course):
SELECT uid, page_id FROM page_fan WHERE uid=me() AND page_id=PAGE_ID
Or by querying Graph API for likes connection of user object:
https://graph.facebook.com/me/likes/PAGE_ID
Both of those ways require user_likes permission granted by user.
To get the same details for user's friends ask for friends_likes permission and substitute me/me() with friend id.
Update: (just to describe what you asked in comments)
There are cases that requiring user_likes may be unnecessary due to nature of flow, if you only need to know that user will/need to like some URL and/or Facebook Page.
You may do so by subscribing (FB.subscribe) to edge.create event which will be triggered once user will like the page (for un-like there is edge.remove event).
Beware that this is only reliable in cases user didn't liked that content before since edge.create only fired on time of user's action.
A better approach to the problem is:
// to generate user access token after the user is logged in
$USER_ACCESS_TOKEN = $facebook->getExtendedAccessToken();
$isFan = curl("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . $USER_ACCESS_TOKEN . "&page_id=" . $FACEBOOK_PAGE_ID);
function curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

echo html tags in status

I am updating facebook status with my feed update from my site,
and facebook status followed by link of feed.
I'm using
echo $_POST['msg']." #"."<a href='http://xxx.ch/comment.php?id=".$result."'>link</a>";
but the status updates in facebook is like that,
msg #<a href='http://xxx.ch/comment.php?id=2>link</a>
I want only
msg # link
Facebook doesn't support html tags in messages. Just specify url and it will be shown as url.
Links should be posted in link parameter, you can also select custom name for that one. Don't use message for this purpose
i got it using tinyurl:
function get_tiny_url($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$new_url = get_tiny_url('http://xxx.ch/comment.php?id='.$result);
echo $_POST['msg']." # ".$new_url;

Categories