Automating Linkedin oAuth usin Curl and PHP - php

I am trying to automate the process of authenticating LinkedIn login in order to perform a public search for people on LinkedIn.
First i will try to explain what i was doing.
I am using four files:
oAuth.php (required)
linkedin.php (php LinkedIn library)
auth.php (which gets oAuth token from the LinkedIn lib file)
callback url demo.php?params (which, after successful authenticaton, prints the current user's profile and the search results using params)
The authentication url is https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken.
I did two things, neither seems to work; they are:
I am using curl to automate the process of going to the authentication url, posting fields (username, password, oauth token, csrfToken, duration, sourceAlias, etc., which I came to know from Firebug).
The only two things which change here are oauth token and csrfToken (by parsing the content in the authentication url). I was able to get both, each time the page loads, and finally trying to print the GET response from curl_exec.
Trying to post just the email and password, and trying to print a GET response.
For reference here is my auth.php:
function extract_unit($string, $start, $end)
{
$pos = stripos($string, $start);
$str = substr($string, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, $end);
$str_three = substr($str_two, 0, $second_pos);
$unit = trim($str_three); // remove whitespaces
return $unit;
}
session_start();
$config['base_url'] = 'http://linkedin.tweetrank.tk/auth.php';
$config['callback_url'] = 'http://linkedin.tweetrank.tk/demo.php';
$config['linkedin_access'] = 'my key';
$config['linkedin_secret'] = 'my secret';
include_once "linkedin.php";
# First step is to initialize with the 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";
echo $url = $linkedin->generateAuthorizeUrl();
$token = $linkedin->generateAuthorizeToken();
//echo '<br><br>';
$data = file_get_contents($url);
$csrfToken = extract_unit($data,'name="csrfToken" value="','"');
//echo $csrfToken;
//echo $token;
//echo 'https://www.linkedin.com/uas/oauth/authenticate?oauth_token='.$token.'&trk=uas-continue';
// INIT CURL
$postParams = 'email=myemail&password=mypassword&duration=720&authorize=Ok%2C+I%27ll+Allow+It&extra=&access=-3&agree=true&oauth_token='.$token.'&appId=&csrfToken='.$csrfToken.'&sourceAlias=0_8L1usXMS_e_-SfuxXa1idxJ207ESR8hAXKfus4aDeAk';
Now I used the authentication URL and the postParams with curl.

In order to get login process through, one has to use linkedIn web page authorization step; No way we can have third party app accepting credentials and making linkedIn authorization with the link https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken

I think I understand what you are asking and the answer is no you cannot do that with LinkedIn. I have been facing similar problem recently and wasn't able to solve it. I guess the LinkedIn guys have a good point about data protecting and stuff.
Check this out:
http://developer.linkedin.com/message/6460
http://getsatisfaction.com/linkedin/topics/cant_use_linkedin_api_to_view_public_profiles_without_oauth_login

Related

Always getting response as Invalid Session Token in soap client php

I have php version 7.1 in my localhost. I have made changes in my php.ini file to run SOAP from my localhost.
I need to generate primary and secondary session token by passing login id and password to SOAP client API.
Once session token is authenticated it will return some rate chart. My code is generating session tokens. But when I am passing that token key to the next method in SOAP Client api its always giving me an error like "Invalid Session Token" or "Invalid Authentication". However the same tokens are working well in SOAP UI exe. I mean I have installed SOAP UI exe and by using wsdl "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl" and using method "Login" and "LookupRate" its working everything fine. The way i need that.
But whenever i am using that tokens in php localhost its always giving me an authentication error by SOAP Client.
I am sharing my code below.
$wsdl = "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
$params = array('loginOperation'=>array('loginId'=>'ryder_cnx1','password'=>'ryder1','thirdPartyId'=>'dl'));
$client->Login($params);
$data = $client->__getLastResponse();
$p = xml_parser_create();
xml_parse_into_struct($p, $data, $vals, $index);
xml_parser_free($p);
$token = [];
foreach ($vals as $key => $value) {
foreach ($value as $key1 => $value1) {
if($key1 == "value")
$token[] = $value1;
}
}
echo "Primary Token = ".$token[0];
echo "<br> Secondary Token = ".$token[1];
//echo "<br> Expiry Date = ".$token[2];
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
$namespace = 'http://www.tcore.com/TcoreTypes.xsd'; // I am not sure about this namespace. Whether its correct or not.
$header = new SoapHeader($namespace,'sessionHeader',$params_session,true);
$client->__setSoapHeaders($header);
$params_data = array('lookupRateOperations'=> array(
'equipment'=>'Vans',
'origin'=>array('postalCode'=>array('country'=>'US','code'=>'30004')),
'destination'=>array('postalCode'=>array('country'=>'US','code'=>'10001'))
));
try{
$result = $client->LookupRate($params_data);
print_r($result);
}catch (SoapFault $exception){
//or any other handling you like
print_r(get_class($exception));
enter code hereprint_r($exception);
}
if anybody have any idea, please share it with me.
Awaiting any response.
Thanks a lot in advance :)
I know this is very old, and most likely the OP figured it out. But in case anyone else comes along, I was able to get it working with two slight changes.
First,
$namespace = 'http://www.tcore.com/TcoreTypes.xsd';
Should be
$namespace = 'http://www.tcore.com/TcoreHeaders.xsd';
Second,
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
should be
$params_session = array(
"sessionToken"=> array(
"primary"=>base64_decode($token[0]),
"secondary"=>base64_decode($token[1])
)
);
The rest of my code is similar enough that if the above changes are made, it should work. I would also refrain from posting real usernames and passwords, btw.

Signing errors from Withings Rest API

all
I have an app that is successfully getting authorized using Withing's api and OAuth.
I get the auth page from whitings, and I get the resulting token and verifier, however I can not make requests with those - I keep getting a 342 error: The signature (using Oauth) is invalid.
Code:
<?
require("include.php");
require_once("OAuth.php");
$domain = "oauth.withings.com";
$base = "/account/";
$base_url = "https://$domain$base";
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$consumer = new OAuthConsumer("my key goes here :-)", "my key goes here :-)", "http://oauth.corp.withings.com/test.php");
$sig_method = $hmac_method;
$username="mydbusername";
$mySQL=" select * from `healthtokens` where service='WITHINGS' and userid='".$username."'";
$data=mysql_query($mySQL) or die("Died at 2<BR>".mysql_error());
$tokenrow = mysql_fetch_array( $data );
$serviceuserid=$tokenrow['serviceuserid'];
$otoken=$tokenrow['otoken'];
$overifier=$tokenrow['overifier'];
$acc_tok = new OAuthToken($otoken,$overifier);
$req = OAuthRequest::from_consumer_and_token($consumer, $acc_tok, "GET", "http://wbsapi.withings.net/user?action=getbyuserid&userid=".$serviceuserid);
$req->sign_request($sig_method, $consumer, $acc_tok);
$response = file_get_contents($req);
echo $response;
?>
Withings API docs: http://www.withings.com/en/api
An example of my call:
http://wbsapi.withings.net/user?action=getbyuserid&oauth_consumer_key=mybigconsumerkeyishere&oauth_nonce=f57a956d52c7412326fb0577e87addc4&oauth_signature=jiBNvql5r06HysjjVyxCh7C7ZUk%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1381758029&oauth_token=4088d6173b78b71cfd6ddd4245496de4b1f7b3c45bfb49f8e59b1202ccfc&oauth_version=1.0&userid=1234567
I know it sounds silly and it gave me some headaches too, but the "funny" thing with oauth 1 (or at least withings) is, that the order of the parameters is important.
Try using the EXACT order as in the withings oauth sample (http://www.withings.com/en/api/oauthguide):
http://wbsapi.withings.net/measure?
action=getmeas
&oauth_consumer_key=c331c571585e7c518c78656f41582e96fc1c2b926cf77648223dd76424b52b
&oauth_nonce=accbac1b7ee2b86b828e6dc4a5a539b2
&oauth_signature=XfobZMboIg2cRyNKAvyzONHHnKM%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1311842514
&oauth_token=887557411788d5120537c6550fbf2df68921f8dd6f8c7e7f9b441941eb10
&oauth_version=1.0
&userid=831

facebook graph api picture - get full url with .jpg

I am able to access my user image from FB with graph api by accessing the user id like so: https://graph.facebook.com/<USER_ID>/picture
However for my code to work, i need the real path to the image like http://profile.ak.fbcdn.net/hprofile-ak-snc6/******_**************_********_q.jpg
FBs doc shows that by adding ?callback=foo i can get an output, but in practice it doesnt seem to work.
any suggestions for getting the full path to my image with that .jpg extension from graph api or with the user id, thank you.
Callback is for javascript requests,
For php,try appending a redirect=false in url.
Do a curl request to,
https://graph.facebook.com/shaverm/picture?redirect=false
If you want to use callback in js,
$.getJSON('https://graph.facebook.com/zuck/picture?callback=?',function (resp) {
$('body').html(resp.data.url);
});​
Demo
Reference
*USE FOLLOWING YOU NEVER GET WRONG RESULT *
$URL='FB GRAPH API URL';
$headers = get_headers($URL, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$URL = $headers['Location']; // this gets the new url
}
$url_arr = explode ('/',$URL);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$pos = strrpos($img_type, "&");//many time you got in url
if($pos)
{
$pieces = explode("&", $img_type);
$img_type = $pieces[0];
}
$imagename = imgnameyouwant'.'.$img_type;
$content = file_get_contents($URL);
file_put_contents("fbscrapedimages/$imagename", $content);

I can't get contacts from yahoo after jumping through all the OAuth loops

I have go throught all the oauth loops, and When I make the call to get the contacts information I only get a 401 error.
this is my code:
<?php
//define yahoo consumer key
$yahoo_consumer_key = variable_get('_contact_grabber_yahoo_consumer_key',NULL);
define('YAHOO_CONSUMER_KEY', $yahoo_consumer_key);
//define yahoo consumer_secret
$yahoo_consumer_secret = variable_get('_contact_grabber_yahoo_consumer_secret',NULL);
define('YAHOO_CONSUMER_SECRET', $yahoo_consumer_secret);
//define yahoo callback
$yahoo_callback = variable_get('_contact_grabber_yahoo_callback',NULL);
define('YAHOO_CALLBACK', $yahoo_callback);
//define app id constant
$yahoo_app_id = variable_get('_contact_grabber_yahoo_app_id',NULL);
define('YAHOO_APP_ID', $yahoo_app_id);
$url =
'http://social.yahooapis.com/v1/user/'.$_SESSION['yahoo']['token']['xoauth_yahoo_guid'].'/contacts?';
$url .= 'oauth_consumer_key='.YAHOO_CONSUMER_KEY;
$url .= '&oauth_nonce='.sha1(time() + rand(0,10));
$url .= '&oauth_signature_method=plaintext';
$url .= '&oauth_timestamp='.time();
$url .= '&oauth_token='.$_SESSION['yahoo']['token']['oauth_token'];
$url .= '&oauth_version=1.0';
$url .= '&oauth_signature='.YAHOO_CONSUMER_SECRET;
$result = drupal_http_request($url);
dpm($result);
?>
This is the error:
<yahoo:error xml:lang="en-US">
<yahoo:description>
Please provide valid credentials. OAuth oauth_problem="signature_invalid", realm="yahooapis.com"
</yahoo:description>
</yahoo:error>
I don't find nowhere how to fix this.
thanks
Oskar
Incase anyone else ever stumbles on this, you cannot use plaintext for the api's, your signature has to be signed using HMAC-SHA1
Few good posts on here regarding how to do this, I would start here: Oauth HMAC-SHA1 authentication to get contacts from Yahoo! Contacts API

login with curl and get session

hello i need somehow to get top Regional interest and interest over time from
http://www.google.com/trends?q=lingerie+&ctab=0&geo=id&date=all&sort=0
or better
http://www.google.com/insights/search/#q=lingerie&geo=ID&cmpt=q
so i found out that we have to login to export data can anybody give me an example doing this with our google username and password? maybe using curl to export the data? or something else
Thanks for looking in
Adam Ramadhan
Just to be quick about it, I used my xhttp class which is a curl wrapper, and I think the code is easy enough to follow.
<?php
header('content-type: text/plain');
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'trendspro', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
);
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Test if unsuccessful
if(!$response['successful']) {
echo 'response: '; print_r($response);
die();
}
// Extract SID
preg_match('/SID=(.+)/', $response['body'], $matches);
$sid = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the SID in cookies
$data['cookies'] = array(
'SID' => $sid
);
$response = xhttp::fetch('http://www.google.com/insights/search/overviewReport?q=lingerie&geo=ID&cmpt=q&content=1&export=1', $data);
// CSV data in the response body
echo $response['body'];
?>
The result is at: http://codecri.me/apps/test/test.google.trends.php
But I'm not sure if the result is what you are looking for.
Since April 2012 Google changed it's auth policy, edit the Arvin's code as follows:
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the Authorization header
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth='.$auth
);
The curl man page describes how to provide username and password. Have you tried the -u flag?
-u/--user
Specify the user name and password to use for server authentication. Overrides -n/--netrc and --netrc-optional.
If you just give the user name (without entering a colon) curl will prompt for a password.
If you use an SSPI-enabled curl binary and do NTLM authentication, you can force curl to pick up the user name and password from your environment by simply specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.

Categories