Complete oAuth script for Twitter and LinkedIn using PECL oAuth Extension


After searching for help to connect with LinkedIn via their oAuth protocol using PECL oAuth extension, I’ve found that lots of people are posting in their forum for the code samples. And only very few obscure code examples are available. I’ve found phplinkedin script but that is just too bulky for a simple oAuth dance :)

So here are two files to perform 3 step oAuth Dance for both twitter and linkedin. Just set your consumer key and consumer secret key in these scripts (config.php) and in your LinkedIn and Twitter application, set the url of these scripts as authentication callback :) thats it :)

check out the source code below or just straight download them from the following url
http://www.box.net/shared/oc0u7ym5y7

config.php: source

<?
//config.php
$oauth['twitter']['consumersecret']="UtNkcJC5VqmHgSgxMIRl2UcHaJLWINzr1g2q*****";
$oauth['twitter']['consumerkey']="LveyUCUf9Ym96AU7*****";
$oauth['twitter']['requesttokenurl']="http://twitter.com/oauth/request_token";
$oauth['twitter']['accesstokenurl']="http://twitter.com/oauth/access_token";
$oauth['twitter']['authurl']="http://twitter.com/oauth/authorize";
$oauth['linkedin']['consumersecret']="SX9FS_Ptz7yNA3WtTW0e8z3_XSiROnVSpOEbAVCfKAn7fqFq4kjelVXiNMO*****";
$oauth['linkedin']['consumerkey']="qQkxCNYQbuALhWyBZO03V--6dtwUnQHz7KFE4PBpdIL6hy_87SHygEZAJj9*****";
$oauth['linkedin']['requesttokenurl']="https://api.linkedin.com/uas/oauth/requestToken";
$oauth['linkedin']['accesstokenurl']="https://api.linkedin.com/uas/oauth/accessToken";
$oauth['linkedin']['authurl']="https://api.linkedin.com/uas/oauth/authorize";
?>

twitter.php: source

<?
//twitter.php
/**
 * twitter authentication script based on
 * pecl oauth extension
 */
session_start();
include_once("config.php");
/*
unset($_SESSION['trequest_token_secret']);
unset($_SESSION['taccess_oauth_token']);
unset($_SESSION['taccess_oauth_token_secret']);
 */
$oauthc = new OAuth($oauth['twitter']['consumerkey'],
        $oauth['twitter']['consumersecret'],
        OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI); //initiate
if(empty($_SESSION['trequest_token_secret'])) {
    //get the request token and store it
    $request_token_info = $oauthc->getRequestToken($oauth['twitter']['requesttokenurl']); //get request token
    $_SESSION['trequest_token_secret'] = $request_token_info['oauth_token_secret'];
    header("Location: {$oauth['twitter']['authurl']}?oauth_token=".$request_token_info['oauth_token']);//forward user to authorize url
}
else if(empty($_SESSION['taccess_oauth_token'])) {
    //get the access token - dont forget to save it 
    $request_token_secret = $_SESSION['trequest_token_secret'];
    $oauthc->setToken($_REQUEST['oauth_token'],$request_token_secret);//user allowed the app, so u
    $access_token_info = $oauthc->getAccessToken($oauth['twitter']['accesstokenurl']);
    $_SESSION['taccess_oauth_token']= $access_token_info['oauth_token'];
    $_SESSION['taccess_oauth_token_secret']= $access_token_info['oauth_token_secret'];
}
if(isset($_SESSION['taccess_oauth_token'])) {
    //now fetch current users profile
    $access_token = $_SESSION['taccess_oauth_token'];
    $access_token_secret =$_SESSION['taccess_oauth_token_secret'];
    $oauthc->setToken($access_token,$access_token_secret);
    $data = $oauthc->fetch('http://twitter.com/account/verify_credentials.json');
    $response_info = $oauthc->getLastResponse();
    echo "<pre>";
    print_r(json_decode($response_info));
    echo "</pre>";
}
?>

linkedin.php: source

<?
//linkedin.php
/**
 * linkedin authentication script based on
 * pecl oauth extension
 */
session_start();
include_once("config.php");
/*
unset($_SESSION['lrequest_token_secret']);
unset($_SESSION['laccess_oauth_token']);
unset($_SESSION['laccess_oauth_token_secret']);
 */
$oauthc = new OAuth($oauth['linkedin']['consumerkey'],
        $oauth['linkedin']['consumersecret'],
        OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION); //initiate

$oauthc->setNonce(rand());

if(empty($_SESSION['lrequest_token_secret'])) {
    //get the request token and store it
    $request_token_info = $oauthc->getRequestToken($oauth['linkedin']['requesttokenurl']); //get request token
    $_SESSION['lrequest_token_secret'] = $request_token_info['oauth_token_secret'];
    header("Location: {$oauth['linkedin']['authurl']}?oauth_token=".$request_token_info['oauth_token']);//forward user to authorize url
}
else if(empty($_SESSION['laccess_oauth_token'])) {
    //get the access token  - dont forget to save it
    $request_token_secret = $_SESSION['lrequest_token_secret'];
    $oauthc->setToken($_REQUEST['oauth_token'],$request_token_secret);//user allowed the app, so u
    $access_token_info = $oauthc->getAccessToken($oauth['linkedin']['accesstokenurl']);
    $_SESSION['laccess_oauth_token']= $access_token_info['oauth_token'];
    $_SESSION['laccess_oauth_token_secret']= $access_token_info['oauth_token_secret'];
    $_SESSION['loauth_verifier'] = $_REQUEST['oauth_verifier'];
}
if(isset($_SESSION['laccess_oauth_token'])) {
    //now fetch current user's profile
    echo "<pre>";
    $access_token = $_SESSION['laccess_oauth_token'];
    $access_token_secret =$_SESSION['laccess_oauth_token_secret'];
    $oauth_verifier = $_SESSION['loauth_verifier'];
    $oauthc->setToken($access_token,$access_token_secret);
    $data = $oauthc->fetch('http://api.linkedin.com/v1/people/~');
    $response_info = $oauthc->getLastResponse();
    print_r(htmlspecialchars($response_info));
    echo "</pre>";
}
?>

Download these files from http://www.box.net/shared/oc0u7ym5y7 – Happy dancing time, in oAuth way ;)

About these ads

34 thoughts on “Complete oAuth script for Twitter and LinkedIn using PECL oAuth Extension

  1. Excellent :)

    You are indeed a lifesaver, now… all we need is one to work with facebook if applicable and we’re off!

    Thank you :)

  2. hey dude thnx for the nice tutorial .

    am really new to this.. .

    can u suggest me how i can get the pecl extension to working , so tha ti can use this code

  3. Fantastic work.
    Do you have one for youtube?
    I started one with PECL oAuth, but cannot get it working. I do get the key though…
    function get_r_token(){
    try {
    $o = new OAuth(GOOGLE_OAUTH_CONSUMER_KEY,GOOGLE_OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);

    /* Google scopes are in the following format: urlencoded(scope) urlencoded(scope) */
    $scopes = urlencode(“http://gdata.youtube.com/”);

    $arrayResp = $o->getRequestToken(“https://www.google.com/accounts/OAuthGetRequestToken?scope={$scopes}”);
    file_put_contents(OAUTH_TMP_DIR . “/request_token_resp”,serialize($arrayResp));
    $authorizeUrl = “https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token={$arrayResp["oauth_token"]}”;
    if(PHP_SAPI==”cli”) {
    echo “Navigate your http client to: {$authorizeUrl}\n”;
    } else {
    header(“Location: {$authorizeUrl}”);
    }
    } catch(OAuthException $E) {
    echo “Response: “. $E->lastResponse . “\n”;
    }
    }

    function get_a_token(){
    try {
    $o = new OAuth(GOOGLE_OAUTH_CONSUMER_KEY,GOOGLE_OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
    $request_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . “/request_token_resp”));
    $o->setToken($request_token_info["oauth_token"],$request_token_info["oauth_token_secret"]);
    $arrayResp = $o->getAccessToken(“https://www.google.com/accounts/OAuthGetAccessToken”);
    file_put_contents(OAUTH_TMP_DIR . “/access_token_resp”,serialize($arrayResp));
    echo “Finished getting the access token!\n”;
    } catch(OAuthException $E) {
    echo “Response: “. $E->lastResponse . “\n”;
    }
    }

    function delete(){
    $oauth = new OAuth(GOOGLE_OAUTH_CONSUMER_KEY,GOOGLE_OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
    $request_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . “/access_token_resp”));
    $oauth->setNonce(rand());
    $oauth->setToken($request_token_info["oauth_token"],$request_token_info["oauth_token_secret"]);
    print_r($request_token_info);
    /* put the OAuth params into the Authorization header */
    $oauth->setAuthType(OAUTH_AUTH_TYPE_AUTHORIZATION);

    $api_args = array(“empty”=>”empty”);
    $oauth->fetch(GOOGLE_YT_EDIT_VIDEO.’OJG_857fsNw’, ”, OAUTH_HTTP_METHOD_DELETE, array(“User-Agent” => “pecl/oauth”));

    }

  4. Pingback: Post status to Linkedin using PHP « 310 Stoddard

  5. Pingback: Complete oAuth script for Twitter and LinkedIn using PECL oAuth Extension | shahverdY

  6. Hey there- I get this error:

    Fatal error: Class ‘OAuth’ not found in C:\wamp\www\site_includes\twitter.php on line 14

    Little help?

  7. Huh? I don’t understand this code at all. Where do you define the class OAuth?

    $oauthc = new OAuth($oauth['twitter']['consumerkey'],

    Are you using a library that you forgot to mention?

  8. Hello,
    I am also getting the error like OAuth class not found in…/linkedin.php. Can you tell me what the corrections I need to do?

  9. I get this exception: exception ‘OAuthException’ with message ‘Invalid auth/bad request (got a 400, expected HTTP/1.1 20X or a redirect)’

    Which raises on this line: $data = $oauthc->fetch(‘http://api.linkedin.com/v1/people/~’);

    Can anyone help me with this please? Thanks!

    PS. Shouldn’t “$oauth_verifier” be used in somewhere?

    • I’ve fixed that problem replacing the line by this:

      $data = $oauthc->fetch(‘http://api.linkedin.com/v1/people/~‘, NULL, OAUTH_HTTP_METHOD_GET);

  10. I tried it and nothing works. All I get is this error:
    PHP Fatal error: Class ‘OAuth’ not found in C:\Inetpub\wwwroot\marioninteractive.com\linkedin\linkedin.php on line 14

    I checked line 14 and even the other lines and don’t see any issues.

    Anyone?

  11. Pingback: connecting to flickr using PHP and PECL oAuth extension « The Storyteller

  12. Some notes for people having trouble.

    $oauth = new OAuth

    is a standard PHP package. One that a lot of server don’t have by default. You have to install it or request your hosting company to do so (if they will). It’s not easy, but googling should help find the specifics for your OS.

    Problems with getAccessToken

    I found I had to change to code to the following:

    $access_token_info = $oauth->getAccessToken($accesstokenurl, “”, $token);

    $token is five digit number you get from linkedin.

    Problems with $_REQUEST['oauth_token']

    This should be saved in the beginning like so:

    $_SESSION['lrequest_oauth_token']= $request_token_info['oauth_token'];

    and then before setting the token, use :

    $oauth_token = $_SESSION['lrequest_oauth_token'];

    use $oauth_token instead of $_REQUEST['oauth_token']

  13. Hey just wanted to give you a quick heads up. The words in your article seem to be running off the screen in
    Firefox. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I figured I’d post to let you know.

    The layout look great though! Hope you get the issue resolved soon.
    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s