Today's Question:  What does your personal desk look like?        GIVE A SHOUT

PHP to get access token for Twitter app

  sonic0002        2013-03-03 03:49:26       16,060        0    

Previously we wrote an article about getting access token for Facebook app--PHP to get access token for Facebook app. Today we will introduce how to get access token for Twitter app using PHP.

Since now Twitter is also using OAuth 2.0 to allow some web apps to access some users information on behalf of one user. They provided some APIs for developers to easily get them integrated with their own websites. The first step to get all these done is how to get the access token, the access token seems like the password to one user's account on Twitter.

First, we need to download the SDK, in this article, we are using twitteroauth.  For the authentication flow, you can refer to the Implementing Sign in with Twitter. We will follow the flow provided here.

First you need to create an app on Twitter and get the consumer key and consumer secret. And then you can start creating your PHP page. The first page is login_twitter.php.

We need to first include the SDK and define some constants:

    include_once('twitteroauth.php');
    
    //Define app key and app secret
    define('APP_KEY','YOUR CONSUMER KEY');
    define('APP_SECRET','YOUR CONSUMER SECRET');

    //Define callback URL
    $auth_page='http://'.$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];
    $callback='twitter_show.php';

Next we need to get oauth_token and oauth_token_secret. So we need to have:

        $tweet = new TwitterOAuth(APP_KEY, APP_SECRET);    
        $request_token=$tweet->getRequestToken($auth_page);
        
        $_SESSION["oauth_token"]=$request_token["oauth_token"];
        $_SESSION["oauth_token_secret"]=$request_token["oauth_token_secret"];
        
        if($tweet->http_code==200){
            $url=$tweet->getAuthorizeURL($request_token["oauth_token"]);
            header("Location:".$url);
        }else{
            die("Error on the login_twitter page");
        }

Here the oauth_token and oauth_token_secret will be used to get the authorization page and it will be redirected to the authorization page.

The sign in endpoint will behave in one of three ways depending on the user's status:

  1. Signed in and approved: If the user is signed in on twitter.com and has already approved the calling application, they will be immediately authenticated and returned to the callback URL with a valid OAuth request token. The redirect to twitter.com is not obvious to the user.
  2. Signed in but not approved: If the user is signed in to twitter.com but has not approved the calling application, a request to share access with the calling application will be shown. After accepting the authorization request, the user will be redirected to the callback URL with a valid OAuth request token.
  3. Not signed in: If the user is not signed in on twitter.com, they will be prompted to enter their credentials and grant access for the application to access their information on the same screen. Once signed in, the user will be returned to the callback URL with a valid OAuth request token.

Once the app is authorized by the user, then it will redirect to the $auth_page with oauth_verifier returned, this will be used later to get the access token. Now we can get the access token with following codes:

            $tweet=new TwitterOAuth(APP_KEY,APP_SECRET,$_SESSION["oauth_token"],$_SESSION["oauth_token_secret"]);
            
            $access_token=$tweet->getAccessToken($_GET['oauth_verifier']);
            // Save it in a session var
            $_SESSION['access_token'] = $access_token;
            
            if($_SESSION["access_token"]!=null){
                $_SESSION["twitter_token"]=$access_token["oauth_token"];
                $_SESSION["twitter_secret"]=$access_token["oauth_token_secret"];
                header("location:".$callback);
            }

That's all. You now get the access token. It's not very difficult once you know how OAuth works and how Twitters implements it.

Below is the complete code:

    //This is to test how to integrate login with twitter component into
    //our own site
    session_start();
    
    include_once('twitteroauth.php');
    
    //Define app key and app secret
    define('APP_KEY','YOUR CONSUMER KEY');
    define('APP_SECRET','YOUR CONSUMER SECRET');
    
    //Define callback URL
    $auth_page='http://'.$_SERVER["HTTP_HOST"].$_SERVER["PHP_SELF"];
    $callback='twitter_show.php';
    
    //Start the oauth process
    if(!isset($_SESSION['oauth_token'])){
        $tweet = new TwitterOAuth(APP_KEY, APP_SECRET);    
        $request_token=$tweet->getRequestToken($auth_page);
        
        $_SESSION["oauth_token"]=$request_token["oauth_token"];
        $_SESSION["oauth_token_secret"]=$request_token["oauth_token_secret"];
        
        if($tweet->http_code==200){
            $url=$tweet->getAuthorizeURL($request_token["oauth_token"]);
            header("Location:".$url);
        }else{
            die("Error on the login_twitter page");
        }
    }else{
        if(!empty($_GET["oauth_verifier"])&&isset($_SESSION['oauth_token'])&&!empty($_SESSION["oauth_token"])&&!empty($_SESSION["oauth_token_secret"])){
            $tweet=new TwitterOAuth(APP_KEY,APP_SECRET,$_SESSION["oauth_token"],$_SESSION["oauth_token_secret"]);
            
            $access_token=$tweet->getAccessToken($_GET['oauth_verifier']);
            // Save it in a session var
            $_SESSION['access_token'] = $access_token;
            
            if($_SESSION["access_token"]!=null){
                $_SESSION["twitter_token"]=$access_token["oauth_token"];
                $_SESSION["twitter_secret"]=$access_token["oauth_token_secret"];
                header("location:".$callback);
            }
        }else{
            echo 'Error while authenticatng';
            unset($_SESSION['oauth_token']);
        }
    }
?>


Source code for twitter_show.php

<?php
    //This is to test how to integrate login with twitter component into
    //our own site
    session_start();
    
    include_once('twitteroauth.php');
    
    //Define app key and app secret
    define('APP_KEY','YOUR CONSUMER KEY');
    define('APP_SECRET','YOUR CONSUMER SECRET');
    
    if($_SESSION["access_token"]!=null&&isset($_SESSION["twitter_token"])&&isset($_SESSION["twitter_secret"])){
        $tweet=new TwitterOAuth(APP_KEY,APP_SECRET,$_SESSION["twitter_token"],$_SESSION["twitter_secret"]);
        $profile=json_decode($tweet->get('account/verify_credentials'));
        //var_dump($profile);
        
        echo $profile->id;
    }else{
        echo 'Access token is invalid or expired';
        header("Location:login_twitter.php");
    }
?>

PHP  TWITTER  OAUTH  ACCESS TOKEN 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.