I have set up a Microsoft Outlook account for testing purposes. I have entered a couple of contacts and sent emails to/from that account, so it is clearly active. I have written php code to access that data, but nothing is returned. Everything else seems to be working in that the access tokens and verification all seems OK.
The php code is as follows (the 'xxxx' is obviously replaced with an actual code) with echos for diagnostic purposes, and some lines have been broken for clarity here.
<?php
//***************************************MSN
START********************************
$client_id = 'xxxxxx';
$client_secret = 'xxxxx';
$redirect_uri =
'http://localhost:8000/testcontacts/oauth_hotmail.php';
$urls_ = 'https://login.live.com/oauth20_authorize.srf?
client_id='.$client_id.
'&scope=wl.signin%20wl.basic%20wl.emails%20wl.contacts_emails&
response_type=code&redirect_uri='.$redirect_uri;
$msn_link = '<a href="'.$urls_.'" >MSN Contacts</a>';
echo $msn_link;
//***************************************MSN
ENDS********************************
?>
<?php
//function for parsing the curl request
function curl_file_get_contents($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$client_id = 'xxxxx';
$client_secret = 'xxxxx';
$redirect_uri = http://localhost:8000/testcontacts/oauth_hotmail.php';
$auth_code = $_GET["code"];
echo '<br>' . $auth_code;
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,
'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
echo '<br>' . $accesstoken;
$url = 'https://apis.live.net/v5.0/me/contacts?
access_token='.$accesstoken.'&limit=100';
$xmlresponse = curl_file_get_contents($url);
$xml = json_decode($xmlresponse, true);
echo '<br>' . $url;
echo '<br>' . $xmlresponse;
echo '<br>' . $xml;
$msn_email = "";
foreach($xml['data'] as $emails)
{
// echo $emails['name'];
$email_ids = implode(",",array_unique($emails['emails'])); //will get
more email primary,sec etc with comma separate
$msn_email .= "<div><span>".$emails['name']."</span>
<span>". rtrim($email_ids,",")."</span></div>";
}
echo $msn_email;
?>
I get the following response (... represents long character string):-
MSN Contacts
Md9a1ad3b-d405-5f3f-1b08-10ae540b5669
EwAgA61DBAAUcSSzoTJJs.....
https://apis.live.net/v5.0/me/contacts?access_token=EwAgA61DBAAUcSSzo.....=&limit=100
{ "data": [], "paging": { } }
Array
Please can anyone tell me why nothing is returned. Thank you.
If anyone else comes this way, I have now got this to work. All the code that I have seen on the internet has been much more complicated than I wanted or refused to work at all, so not much use to me. Here I have managed to pare the code down to a minimum in a stand-alone working piece of code. I hope it works for you.
One question still remains. I cannot see how to get the contacts which are in a specific contact list, and not get all the contacts. Any ideas?
Here is the code...
<?php
//***************************************MSN START********************************
$client_id = 'xxxxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxx';
$redirect_uri = 'https://.........php';
$login_uri = 'https://login.live.com/oauth20_authorize.srf';
$scope = '&scope=wl.signin%20wl.basic%20wl.emails%20wl.contacts_emails';
$urls_ = $login_uri;
$urls_ .= '?client_id='.$client_id;
$urls_ .= $scope.'&response_type=code';
$urls_ .= '&redirect_uri='.$redirect_uri;
$msn_link = '<a href="'.$urls_.'" >Get Contacts</a>';
echo $msn_link;
//***************************************MSN ENDS********************************
if(isset($_GET["code"])){
$auth_code = $_GET["code"];
// get contacts
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$apiurl = "https://outlook.office.com/api/v2.0";
$headers = array(
"User-Agent: php-tutorial/1.0",
"Authorization: Bearer ".$accesstoken,
"Accept: application/json",
"return-client-request-id: true"
);
$search = array (
// Only return selected fields
"\$select" => "EmailAddresses,GivenName,Surname",
// Sort by GivenName
"\$orderby" => "GivenName ASC"
);
$outlookApiUrl = $apiurl . "/me/contacts?" . http_build_query($search);
$response = runCurl($outlookApiUrl, null, $headers);
$response = explode("\n", trim($response));
$response = $response[count($response) - 1];
$response = json_decode($response, true);
foreach ($response["value"] as $contacts) {
$email = $contacts["EmailAddresses"][0]["Address"];
echo '<br>' . $contacts["GivenName"] . ' ' . $contacts["Surname"] . ' ' . $email;
}
}
function runCurl($url, $post = null, $headers = null) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, $post == null ? 0 : 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($http_code >= 400) {
echo "Error executing request to Office365 api with error code=$http_code<br/><br/>\n\n";
echo "<pre>"; print_r($response); echo "</pre>";
die();
}
return $response;
}
?>
I'm trying to develop a Telegram Bot in PHP, but I failed to make my bot answer the user when he press an inline button.
Can someone help me sending a message (sendMessage method) after calling the answerCallback method?
Here's my last trial code:
if ($call_back_query != null) {
$response = $call_back_query;
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $call_back_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
$response = "help me if you can, i'm feeling down";
header("Content-Type: application/json");
$parameters = array('chat_id' => $chatId, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
Ok, I've understood the problem:
In sendText I have to use $call_back_from instead of $chatId, because he's answering to the callback query and not a simple message (I think so...)
While
$chatId = isset($message['chat']['id']) ? $message['chat']['id'] : "";
$call_back_from = isset ($update['callback_query']['from']['id']) ? $update['callback_query']['from']['id'] : "";
The code will be
if ($call_back_query != null) {
$response = $call_back_query;
$botUrl = "https://api.telegram.org/bot" . BOT_TOKEN . "/answerCallbackQuery";
$postFields = array('callback_query_id' => $call_back_id, 'text' => $response);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $botUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$output = curl_exec($ch);
//send Text
$response = "help me if you can, i'm feeling down";
header("Content-Type: application/json");
$parameters = array('chat_id' => $call_back_from, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
}
Hope this could be helpful!
Have a nice try!
I have looked over the code many times but whenever I send request to API it returns "message":"invalid signature"
I am thinking it has to do with hashing the body, possibly. I'm new to PHP and its my first project. :)
Anyone see an error? Thanks.
<?php
$arr = array('size' => ".01", 'price' => '240', 'side' => 'sell',
'product_id' => 'BTC-USD');
$output = json_encode($arr);
echo json_encode($arr)."<br/>";
$key = "f23612b06cb4d020cda7e04b1ae6ef9a";
$secret = "RENqodtuTCn4v7g7Pn/FFdQAIKReVXGayNPrNN/Zb7AjATI0hP4R0MCDD5RqnDu60qTZ5Qry329fFu7kcObGBw==";
$passphrase = "tradebot";
$time = time();
$url = "https://api.gdax.com/orders";
$data = $time."POST"."/orders";
echo $data . "<br/>";
$hashinput = "$output"."$data";
$sign = base64_encode(hash_hmac("sha256", $hashinput, base64_decode($secret), true));
echo $sign . "<br/>";
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
var_dump($headers);
echo $url;
static $ch = null;
if (is_null($ch)) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'local server');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, $output);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$res = curl_exec($ch);
echo $res;
}
replace
$hashinput = "$output"."$data";
with
$hashinput = "$data"."$output";
and replace
curl_setopt($ch, CURLOPT_POST, $output);
with
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
(from Coinbase Community forum)
I want to grab json string, set objects and httpheaders in 1.php (for example). Get these values in JSON format and display in next page (2.php).
I tried to use CURL method. I m very new to PHP. Not sure whether CURL method is the best to POST data.. Session or cookie method no need. Is there any other method other than this to POST data?
1.PHP:
<?php
$data = array($item_type = "SubscriptionConfirmation";
$message = "165545c9-2a5c-472c-8df2-7ff2be2b3b1b";
$Token = "2336412f37fb687f5d51e6e241d09c805a5a57b30d712f794cc5f6a988666d92768dd60a747ba6f3beb71854e285d6ad02428b09ceece29417f1f02d6";
$TopicArn = "arn:aws:sns:us-east-1:123456789012:MyTopic";
$Message = "You have chosen to subscribe to the topic arn:aws:sns:us-east-1:123456789012:MyTopic.\nTo confirm ";
$SubscribeURL = "https://sns.us-east-1.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-east-1:123456789012:MyTopic&Token=2336412f37fb6";
$Timestamp = "2012-04-26T20:45:04.751Z";
$SignatureVersion = "1";
$Signature = "EXAMPLEpH+DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=";
$SigningCertURL = "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem";);
$json_data = json_encode($data);
$ch = curl_init('http://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CAINFO, "/path/to/CA.crt");
curl_setopt($ch, CURLOPT_HTTPHEADER,array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
$result = json_decode($output);
echo $result;
?>
2.PHP:
How to post 1.php json value to 2.php.. either through CURL or other posting method.. Tried my best.. cant able to figure out the solution.
Thanks
1.php
$data = array(
'test' => 'data',
'new' => 'array');
$json_data = json_encode($data);
// Only work with your example, curl need full url
$request_url = 'http://teshdigitalgroup.com/2.php';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
$output = curl_exec($ch);
print_r($output);
AND 2.php
print_r(file_get_contents('php://input'));
// Response 1.php's request HTTP Header
function parseRequestHeaders() {
$headers = array();
foreach($_SERVER as $key => $value) {
if (substr($key, 0, 5) <> 'HTTP_') {
continue;
}
$header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
$headers[$header] = $value;
}
return $headers;
}
print_r(parseRequestHeaders());
I got this code from some tutorial about linked signup, but the tutorial provide just the basic information. I need to get the user email also... How can I do that?
Here is the code:
auth.php
This is the link where I get access form on likedin.
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup.
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# First step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is LinkedIn library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The email address is only available to the authenticated user and not his/her connections.
Make sure you've requested the r_emailaddress member permissions from the user when authorizing your application. Authentication covers authentication and grant member permissions in detail.
Make the following GET call to fetch the email address for the authenticated user:
GET http://api.linkedin.com/v1/people/~:(email-address)
For people searching for v2 urls
please follow the below urls
payload = {
'grant_type': 'authorization_code',
'code': token,
'redirect_uri': s.SOCIAL_AUTH_CALLBACK_URL,
'client_id': s.LINKED_IN_CLIENT_ID,
'client_secret': s.LINKED_IN_CLIENT_SECRET
}
POST "https://www.linkedin.com/oauth/v2/accessToken"
to get access token
GET "https://api.linkedin.com/v2/me"
to get the user data send auth token in header
GET "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))"
to get user email address.
You can get email address via api
$this->userProfileUrl = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url,public-profile-url,email-address)?oauth2_access_token=";
But you have to set scope like $oauth->scope = 'r_basicprofile,r_emailaddress';
use Oauth
https://developer-programs.linkedin.com/documents/profile-api
Or try
https://developer.linkedin.com/docs/oauth2
You can access the linkedin user email address with below EP:
`https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))`
Make sure that you have defined the scope 'r_emailaddress' in your library.
You can use below curl request to fetch the data:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. $token,
'X-Restli-Protocol-Version: 2.0.0',
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $headerSize);
$response_body = json_decode($body,true);
$response_body will return the following response:
Array (
[elements] => Array
(
[0] => Array
(
[handle] => urn:li:emailAddress:123456
[handle~] => Array
(
[emailAddress] => your#email.in
)
)
)
)
You should pass '&scope=r_basicprofile+r_emailaddress' this at time of AccessToken Request
Step 1: AccessToken Request will be like
https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={Your code}&redirect_uri={Yourredirect_uri}&client_id={Your client_id}&client_secret={Your client_secret }&scope=r_liteprofile+r_emailaddress
This will return you the AccessToken using which You do have to make 2 more requests 1 is for Email and Profile Details
Step 2: for Email request will be like
https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token={AccessToken You get from step 1}'
Step 3: for basic profile request will be like
https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token={AccessToken You get from step 1}'
The LinkedIn API does not offer the email address as part of the profile object. See the docs here to read what data is available.
EDIT:
See Kamyar's answer. Apparently as of August 2012 LinkedIn now allows pulling the email addresses.
You can try :
->elements[0]->{"handle~"}->emailAddress
goodluck
Step 1: AccessToken Request
$postData = array(
'grant_type' => 'authorization_code',
'code' => urldecode(trim($_GET['code'])),
'redirect_uri' => url_for('social_login/linkedin'),
'client_id' => CFG_LINKEDIN_APP_ID,
'client_secret' => CFG_LINKEDIN_SECRET_KEY
);
$ch = curl_init("https://www.linkedin.com/oauth/v2/accessToken");
curl_setopt($ch, CURLOPT_HEADER, array('Content-Type' => 'application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $header_size);
curl_close($ch);
if(!$response)
{
die('Curl error: ' . curl_error($ch));
}
$response = json_decode($body,true);
In $response you will find the AccessToken using which You do have to make 2 more requests 1 is for Email and Profile Details
Step 2: profile request
$access_token = $response['access_token'];
$ch = curl_init('https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,emailAddress,profilePicture(displayImage~:playableStreams))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
curl_close($ch);
Step 3: for Email request
$ch = curl_init('https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))&oauth2_access_token=' . $access_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response2 = curl_exec($ch);
curl_close($ch);
Result: user data
$user = [
'first_name' => current($response['firstName']['localized']),
'last_name' => current($response['lastName']['localized']),
'photo' => $response['profilePicture']['displayImage~']['elements'][0]['identifiers'][0]['identifier'],
'email' => $response2['elements'][0]['handle~']['emailAddress']
];