OAuth and Twitter API integration in Kohana3 framework

    Somehow, the thought crept into my head that it would be time to start integrating the blog and twitter into a single whole. There are two wonderful things for this, such as OAuth, which connects your application with the functionality of a third-party API, and the functionality itself, implemented, in this case, in the form of the Twitter API.

    After studying several manuals (for example, Dmitry Koterov has a very good article on this topic) and understanding the basic principle of OAuth, I came to the conclusion that writing your bike is an inefficient task at the moment, and decided to see what is already ready on the Internet .

    So what do we see by going to http://dev.twitter.com/pages/libraries ? An unimaginable number of ready-made solutions for our task. I decided to stop at the library I likedTwitter-async by Jaisen Mathai. Next, I will describe how to integrate the library into Kohana 3 and how to use it.

    To get started, register your application on twitter at http://twitter.com/apps/new . Fill in the fields, select the “Browser” type for the “Application Type”, set the “Default Access type” to “Read & Write”. Be sure to fill out the “Callback URL” field - the page where the redirect to your site will be made after exchanging secret keys between your application and twitter. For example, I have a separate twitter controller responsible for this with the confirm method, the code of which I will give later (i.e. it looks something like this: sitename.com/twitter/confirm) That's all, fill in the captcha, click “Save” and get a pair of keys - “Consumer key” and “Consumer secret”. They will be needed a little later.

    The next step is to unpack the contents of the archive with the Twitter-async library into the directory / modules / epitwitter / classes / of your site on kohana3. We need only three files - EpiCurl.php, EpiOAuth.php and EpiTwitter.php. For example, the path to EpiTwitter.php will look like this: /modules/epitwitter/classes/EpiTwitter.php. The file name EpiTwitter.php is lowercase (epitwitter.php) and we add three lines to it right before the description of the class itself:


    include_once('EpiCurl.php');
    include_once('EpiOAuth.php');
    include_once('secret.php');
    class EpiTwitter extends EpiOAuth
    {


    * This source code was highlighted with Source Code Highlighter.


    These manipulations are needed to integrate the library into the Kohana3 module loading system.

    Next, create the file /modules/epitwitter/classes/secret.php, where we will store our keys:

    define('CONSUMER_KEY', 'тут_ваш_consumer_key');
    define('CONSUMER_SECRET', 'тут_ваш_consumer_secret');
    ?>

    * This source code was highlighted with Source Code Highlighter.


    Open our bootstrap.php and add a line to it to load the library into the system:

    Kohana::modules(array(

    'epitwitter' => MODPATH.'epitwitter',

    ));

    * This source code was highlighted with Source Code Highlighter.


    That's it, we completed the integration of the library into the system, now it's time to make it work.

    We create the controller /application/classes/controller/twitter.php - for CallbackURL, remember? Here's what it looks like from me:

    class Controller_Twitter extends Controller {
      … 
      public function action_confirm()
      {
        $twitterObj = new EpiTwitter(CONSUMER_KEY, CONSUMER_SECRET);
        $twitterObj->setToken($_GET['oauth_token']);
        $token = $twitterObj->getAccessToken();   
        Cookie::set('oauth_token',$token->oauth_token,60*60*24*7);
        Cookie::set('oauth_token_secret',$token->oauth_token_secret,60*60*24*7);   
        header('Location: /');
        exit();
      }
      …
    }

    * This source code was highlighted with Source Code Highlighter.


    In particular, we are interested in the confirm method - public function action_confirm (), which the CallbackURL setting of your application refers to. Here, a token is received from OAuth twitter and its value is saved (pairs oauth_token and oauth_token_secret), for example, in cookies. Then there is a redirect to the main page so that the cookies are initialized.

    What happens on the main page? The core controller is responsible for the core of the site.

    class Controller_Core extends Controller_Template {
    public $template = 'main'; // основной шаблон сайта
    … 
      public $twitterObj = NULL;
      public $twitterInfo = NULL;
    … 
      public function before()   
      {
        parent::before();
        //проверяем куки на наличие токена oAuth       
        if(isset($_COOKIE['oauth_token']) and isset($_COOKIE['oauth_token_secret']))
        {
          $twitterObj = new EpiTwitter(CONSUMER_KEY, CONSUMER_SECRET,
            Cookie::get('oauth_token'), Cookie::get('oauth_token_secret'));
    //передаем объект связки oAuth+TwitterAPI в публичное свойство класса для доступа из других методов и т.п
          $this->twitterObj = $twitterObj;
          //забираем данные о залогинившемся пользователе
          $twitterInfo = $twitterObj->get_accountVerify_credentials();
          $twitterInfo->response; 
          $this->twitterInfo = $twitterInfo;
          $this->template->twitterObj = $this->twitterObj;

          //передаем массив данных о пользователе в основной шаблон. Теперь на всех страницах будет отображаться логин пользователя и его юзерпик.
          $this->template->twitterInfo = $twitterInfo;     
        }
        else
        {
          //иначе создаем объект EpiTwitter и передаем в шаблон ссылку на авторизацию твиттер-аккаунта и получение токенов
          $twitterObj = new EpiTwitter(CONSUMER_KEY, CONSUMER_SECRET);
          $this->twitterObj = NULL;
          $this->twitterInfo = NULL;
          //Вот она, ссылка:
          $this->template->twitter_login = $twitterObj->getAuthorizationUrl();      

        }
      }


    * This source code was highlighted with Source Code Highlighter.



    The Kohana3 framework has a wonderful before () method, which is remarkable in that processes occur in it before the main method is activated. That is, before the main data of the main method and the template are processed, instances of our library classes are created, the necessary key manipulations are performed and, depending on the circumstances, either the authorization link in oAuth Twitter or the data about the authorized user is transferred to the template.

    Our library has a very convenient way to access TwitterAPI. For example, consider this line:

    $twitterInfo = $twitterObj->get_accountVerify_credentials();

    What is going on here? Everything is very simple. We tell our object: using the GET method, knock on TwitterAPI at account / verify_credentials. The result is returned in json and parsed inside the object.

    For example, to find out the public data of a twitter account, according to TwitterAPI, you need to use the users / show method (see http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-users%C2% A0show ). Accordingly, the call will look like this:

    $twitterInfo = $twitterObj->get_usersShow(array('screen_name'=>'VasyaPupkin'));

    Everything is simple :)

    If you throw out the concretization regarding integration into Kohana3, then in short the bundle of your application + OAuth + Twitter API (using the Twitter-async library ) looks like this:
    1. We register our application on Twitter, we get a pair of keys - consumer_key and consumer_secret
    2. In callbackurl, we prepare the footprint for receiving the token from OAuth Twitter, save the received tokens somewhere for permanent authorization on our website.
    3. Using the resulting pair of tokens and the consumer key pair, we create an EpiTwitter instance with which you can freely access the Twitter API. Or, if there are no tokens using a pair of consumer_key and consumer_secret, get an authorization link in oAuth twitter to get tokens.

    Also popular now: