How can I get Facebook Profile image from email? - facebook

There's an outlook plugin called Xobni that has a really cool feature, if a contact has an email address, it will fetch that contact's profile picture and display it. Their FAQ states the following:
Xobni sends an encrypted email address to Facebook to retrieve the Facebook profile for the person who is currently being viewed in the Xobni sidebar. Your own Facebook profile is never altered by Xobni, and all Facebook privacy settings are strictly followed when viewing other profiles.
I'd like to duplicate this functionality. However, I can't figure out which API call they're using. I'm assuming when they say "encrypted email address" that's laymen's terms for the email hash. Once a username is derived, the graph api looks ideal for actually fetching the image, but I'm having trouble going from email hash to profile ID.

You can query the following URL to get user id (if one exists on Facebook):
https://graph.facebook.com/search?access_token=YOUR_ACCESS_TOKEN&q=EMAIL_ADDRESS_URL_ENCODED&type=user
Then <img src="https://graph.facebook.com/USER_ID/picture"> gives you the picture.
More info: article at codinglogs.com

I am searching for a way to do this exact thing... No attempts have worked yet.
Has anyone been able to find a solution?
Update: I've put together this snippet in PHP. It's just about the only way I've been able to accomplish my goal. I'm not sure how Xobni is doing it (I'm sure they are less intrusive about it)
<?php
/* Email to Search By */
$eml = 'user#domain.com';
/* This is where we are going to search.. */
$url = 'http://www.facebook.com/search.php?q=' . urlencode($eml);
/* Fetch using cURL */
$ch = curl_init();
/* Set cURL Options */
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* Tell Facebook that we are using a valid browser */
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
/* Execute cURL, get Response */
$response = curl_exec($ch);
/* Check HTTP Code */
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/* Close cURL */
curl_close($ch);
/* 200 Response! */
if ($response_code == 200) {
/* Parse HTML Response */
$dom = new DOMDocument();
#$dom->loadHTML($response);
/* What we are looking for */
$match = 'http://www.facebook.com/profile.php?id=';
/* Facebook UIDs */
$uids = array();
/* Find all Anchors */
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$href = $anchor->getAttribute('href');
if (stristr($href, $match) !== false) {
$uids[] = str_replace($match, '', $href);
}
}
/* Found Facebook Users */
if (!empty($uids)) {
/* Return Unique UIDs */
$uids = array_unique($uids);
/* Show Results */
foreach ($uids as $uid) {
/* Profile Picture */
echo '<img src="http://graph.facebook.com/' . $uid. '/picture" alt="' . $uid . '" />';
}
}
}
?

It is no longer possible to search user info with email address via Facebook Graph API. While it still works if you have the Facebook user ID, but if you can't get the Facebook ID with the search API, you can no longer do this.
https://developers.facebook.com/x/bugs/453298034751100/
The API will return the following response:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}

Many thanks #McHerbie, you gave me the clue to FINALLY get my code working. The key is the urlencode() function to encode email!!! thanks, this is my working code using PHP Simple HTML Dom Parser:
public function getFacebookPictureByScrapping($email="your#email.com", $file="fbPicture.jpg") {
require_once('protected/extensions/simplehtmldom/simple_html_dom.php');
$userEmail = urlencode($email);
ini_set('user_agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13');
$url = "http://www.facebook.com/search.php?q=$userEmail&type=all&init=srp";
$html = new simple_html_dom();
$html = file_get_html($url);
if (is_object($picture = $html->find(".uiList .img",0))) {
$image = file_get_contents($picture->src, false);
file_put_contents($file);
return $file;
} else {
return null;
}
}

I know this post is a bit old, but only just now found it - you might try the FullContact Person API (full disclosure - I'm biased, I work for them):
http://www.fullcontact.com/developer/
On the one hand, it will pull the associated social media profiles when you query based on email so that you can find and pull the associated profile...but on the other hand, you can also save some time & use it to pull the profile images directly.
The response schema includes:
"photos":
[
{
"typeId": [photo type],
"typeName": [photo type name],
"url": [photo url],
"isPrimary": [boolean]
}
]
More info: http://www.fullcontact.com/developer/docs/person/#lookup-by-email-3

Related

Get Email state using codeigniter & sendgrid Webhook

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

get likers of Facebook page and get count of those who like more than 200 pages

I'm trying to get a "list" of random likers who follow a Facebook Page. I'm using this code to get some fans (not random fans, but this is something else).
<?php
function fetch_fb_fans($fanpage_name, $no_of_retries = 10, $pause = 500000){
$ret = array();
/* get page info from graph */
$fanpage_data = json_decode(file_get_contents('http://graph.facebook.com/' . $fanpage_name), true);
if(empty($fanpage_data['id'])){
/* invalid fanpage name */
return $ret;
}
$matches = array();
$url = 'http://www.facebook.com/plugins/fan.php?connections=100&id=' . $fanpage_data['id'];
$context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0')));
for($a = 0; $a < $no_of_retries; $a++){
$like_html = file_get_contents($url, false, $context);
preg_match_all('{href="https?://www\.facebook\.com/([a-zA-Z0-9._-]+)" data-jsid="anchor" target="_blank"}', $like_html, $matches);
if(empty($matches[1])){
/* failed to fetch any fans - convert returning array, cause it might be not empty */
return array_keys($ret);
}else{
// merge profiles as array keys so they will stay unique
$ret = array_merge($ret, array_flip($matches[1]));
}
// don't get banned as flooder
usleep($pause);
}
return array_keys($ret);
}
/*
print_r(fetch_fb_fans('cocacola', 2, 400000));
prints 73 unique fan names as array
*/
$contador = 0;
foreach (fetch_fb_fans('cocacola', 2, 400000) as $fan) {
$pageContent = file_get_contents('http://graph.facebook.com/'.$fan.'');
$parsedJson = json_decode($pageContent);
echo $parsedJson->username ."<br/>";
}
?>
Code from: Facebook API: Get fans of / people who like a page
This code give me some usernames. Now, my question, after searching Google... Is, can I get the number of pages that follow every user?
I know that Graph API let me know my likes but when I try to see other user likes it throws me an OAuthException error. I supose that I'm not doing right.
So I will apreciate some explanation about how to do this. I searched Google but I don't understand how it works.
Thanks.
The Facebook documentation is unfortunately not very clear: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
However, getting the likes from a user requires:
User access token for the user
"User likes permission" granted on the access token, which is a special permission that Facebook approves on your app
Without an access token for the user you cannot see what pages they like.
While not supported, you could perhaps use a page scraper to find this information if they have it public.
Based on your question, it's not clear whether users log in to your app or if you're just trying to get information from one of your own pages, or another page. If you don't have users logging into your app, I'm afraid there's no way at all to get this information apart from a page scraper.

How to use dodirect payment paypal on form submission?

I have to use dodirect payment method after the form submission. The form will be displayed on the site for all the card detail such as card type (visa or master), card card no, security number, expiration date, name on card, address, state, postal, country, phone, email etc.
I searched how to use the dodirect method and found as below
<?php
/** DoDirectPayment NVP example; last modified 08MAY23.
*
* Process a credit card payment.
*/
$environment = 'sandbox'; // or 'beta-sandbox' or 'live'
/**
* Send HTTP POST Request
*
* #param string The API method name
* #param string The POST Message fields in &name=value pair format
* #return array Parsed HTTP Response body
*/
function PPHttpPost($methodName_, $nvpStr_) {
global $environment;
// Set up your API credentials, PayPal end point, and API version.
$API_UserName = urlencode('my_api_username');
$API_Password = urlencode('my_api_password');
$API_Signature = urlencode('my_api_signature');
$API_Endpoint = "https://api-3t.paypal.com/nvp";
if("sandbox" === $environment || "beta-sandbox" === $environment) {
$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
}
$version = urlencode('51.0');
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the API operation, version, and API signature in the request.
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
if(!$httpResponse) {
exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
$tmpAr = explode("=", $value);
if(sizeof($tmpAr) > 1) {
$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
}
}
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
return $httpParsedResponseAr;
}
// Set request-specific fields.
$paymentType = urlencode('Authorization'); // or 'Sale'
$firstName = urlencode('customer_first_name');
$lastName = urlencode('customer_last_name');
$creditCardType = urlencode('customer_credit_card_type');
$creditCardNumber = urlencode('customer_credit_card_number');
$expDateMonth = 'cc_expiration_month';
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
$expDateYear = urlencode('cc_expiration_year');
$cvv2Number = urlencode('cc_cvv2_number');
$address1 = urlencode('customer_address1');
$address2 = urlencode('customer_address2');
$city = urlencode('customer_city');
$state = urlencode('customer_state');
$zip = urlencode('customer_zip');
$country = urlencode('customer_country'); // US or other valid country code
$amount = urlencode('example_payment_amuont');
$currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// Add request-specific fields to the request string.
$nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
"&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
"&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else {
exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
?>
I didn't get an idea how to use this code on submission of the form that I have on my site. Can anyone help me out how to use this after submitting form.
Thanks in advance :)
That's really not a very well built function. It's basically wanting you to just fill in the values within the function rather than pass them in. It's a pretty rough example and you can see it was last updated in 2008 according to the comments.
If you want to use it, though, you can simply fill in all those placeholders where they show things like "my_api_username" with the data that you want to actually include.
If you want something a lot easier to work with, I would recommend using this PHP library for PayPal that I developed and have maintained for years. It's current and contains straight forward samples for running DoDirectPayment. You could have it up-and-running within minutes.
I offer 30 min of free training via screen share, too, if you're interested in that.
Actually there are samples available for DoDirectPayment as part of the official SDKs available at https://www.x.com/developers/paypal/documentation-tools/paypal-sdk-index#expresscheckoutnew
Suggest using the official SDK and check the samples inside them. In case of any issues please post back here or open an issue at https://github.com/paypal/merchant-sdk-php/issues

How to count likes on FB page?

I have to do a very simple operation but my programming skills are not enough. I have to count likes in Facebook page and print that number on my web-site. I have two scripts that do the job well for ordinary web-sites, but they don't want to show the number of likes for the page.
<?php
$source_url = "http://www.facebook.com/"; //This could be anything URL source including stripslashes($_POST['url'])
$url = "http://api.facebook.com/restserver.php?method=links.getStats&urls=".urlencode($source_url);
$likes = $xml->link_stat->like_count;
$comments = $xml->link_stat->comment_count;
$total = $xml->link_stat->total_count;
$max = max($shares,$likes,$comments);
echo $likes;
?>
<?php
$fql = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
$fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
$fql .= "link_stat WHERE url = 'http://www.apple.com/'";
$apifql="https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
$json=file_get_contents($apifql);
print_r( json_decode($json));
?>
Both scripts work for ordinary web-sites but cant fetch fb page likes number. May be I should enter the link in another format or something?
I can get required data using graph like this http://graph.facebook.com/?ids=AutoSpecCenter , just by entering page name like that. But I don't know how to manipulate with this data.
As you already wrote in your question, you can query such information through Facebooks' Graph API. This short example will get the information of the Coca-Cola page, decode the JSON and outputs the number of people that like the page $data->likes.
<?php
$ch = curl_init("https://graph.facebook.com/CocaCola?access_token=<Access Token>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$raw = curl_exec($ch);
curl_close($ch);
$data = json_decode($raw);
echo $data->likes . " people like Coca-Cola";
?>
If you need to perform more tasks than just getting the likes of a page, consider using the Facebook SDK as cpilko suggested.
Here's the quick and dirty way:
<?php
$fb_id = 'AutoSpecCenter';
$url = 'https://graph.facebook.com/' . urlencode($fb_id);
$result = json_decode( file_get_contents($url) );
printf("<p>There are %s people who like %s</p>", $result->likes, $result->name);
You'd do much better off installing the Facebook PHP SDK or using cURL to get this.
You could set $fb_id equal to a url as well.
here is a easy way too....
<?php
$page_id = 'yourfbpageid'; // your facebook page id
$xml = #simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
?>
<li class="text white"><span></span><?php echo $fans.' Fans'; ?></li>
courtesy:ravi patel
This worked for me
<?php
function getData($username){
$access_token = 'YOUR ACCESS TOKEN'; //Replace it with your Access Token
$json = json_decode(file_get_contents("https://graph.facebook.com/".$username."?fields=fan_count&access_token=".$access_token),true);
return $json;
}
$data = getData("Mypage");//Replace it with your Username
$likes = $data['fan_count'];
echo "Facebook Likes: ".$likes;
?>
I was having same problem, just adding likes.summary(true),comments.summary(true) in parameter in against "fields" worked for me.
e.g. I used https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN&fields=story,from,story_tags,likes.summary(true),comments.summary(true)
instead of https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN
Also you can add other parameters if you want; separated by a ,
Also if you want count of single post you can use
https://graph.facebook.com/POST_ID/likes?summary=true&access_token=ACCESS_TOKEN
for likes count
Or
https://graph.facebook.com/POST_ID/comments?summary=true&access_token=ACCESS_TOKEN
for comment count
Try this code
<?php echo facebooklike('209414452444193');
function facebooklike($page_id){
$likes = 0; //Initialize the count
//Construct a Facebook URL
$json_url ='https://graph.facebook.com/'.$page_id.'';
$json = get_contents($json_url);
$json_output = json_decode($json);
//Extract the likes count from the JSON object
if($json_output->likes){
$likes = $json_output->likes;
}
return $likes;
}
function get_contents($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
?>

Graph API: How to grab current user's information?

I'm trying to get some basic information about a user in a PHP script (id and name).
I have tried the following methods:
$retrieve = curl_init("https://graph.facebook.com/me?access_token=$accesstoken");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($retrieve, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($retrieve);
curl_close($retrieve);
and
$user = json_decode(file_get_contents(
"https://graph.facebook.com/me?access_token=$accesstoken"))->me;
The cURL method (former) just times out. The file_get_contents (latter) method just doesn't return anything at all...
What could be causing this? Am I using cURL correctly?
for graph api you can use graph api methods rahter than curl
the following code grabs information of current user
define('FACEBOOK_APP_ID', 'Your API ID');
define('FACEBOOK_SECRET', 'YOUR SECRET');
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig')
{
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig'])
{
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));
its prettey easy
Facebook will not let you use curl. They have the api for that.
copy your link and paste it to browser. It will work. In Mozilla you will see the result in browser, IE will save the result as a file. So it is not about invalid access token etc. It is just because Facebook does not respond to your query when it does not come 1-from a web browser, 2-from Facebook APIs.
here is the relevant PHP call to Facebook.
$attachment = array('access_token' => $access_token);
$result=$facebook->api('/me', 'GET', $attachment);
$id = $result['id'];
$name=$result['name'];