[AS3.0] OAuth認証をPHPで試してみる! (1)

そうだ! OAuth認証をPHPで試してみよう!

twitteroauthってライブラリがあるので、それを使うよ。 :boy:
:check: 「abraham/twitteroauth - GitHub

Cookieを使わない方法は、 :banana: [AS3.0] OAuth認証をPHPで試してみる! (2) で。

:caution: 要 Flash Player 9 以上
:caution: ひよこちゃんをクリックすると「ぴよぴよ」と自動的にtwitterに投稿されます。

This movie requires Flash Player 9.0.0

Main.as
package {

  import flash.display.Sprite;
  import flash.events.MouseEvent;
  import flash.external.ExternalInterface;
  import flash.net.URLLoader;
  import flash.net.URLLoaderDataFormat;
  import flash.net.URLRequest;
  import flash.net.URLRequestMethod;
  import flash.net.URLVariables;
  import flash.events.Event;
  import flash.events.IOErrorEvent;

  import de.aggro.utils.CookieUtil;
  import jp.nya.project.character.Piyo;

  [SWF(backgroundColor="#FFFFFF", width="600", height="200", frameRate="30")]

  public class Main extends Sprite {
    // プロパティ
    private var piyo:Piyo;
    private var access_token:Object;
    private var access_token_secret:Object;
    private var loader:URLLoader;

    // コンストラクタ
    public function Main() {
      init();
    }

    // メソッド
    private function init():void {
      piyo.buttonMode = true;
      piyo.mouseChildren = false;
      piyo.addEventListener(MouseEvent.CLICK, click, false, 0, true);
      loader = new URLLoader();
      loader.dataFormat = URLLoaderDataFormat.TEXT;
      loader.addEventListener(IOErrorEvent.IO_ERROR, ioerror, false, 0, true);
      loader.addEventListener(Event.COMPLETE, complete, false, 0, true);

      CookieUtil.init();
    }
    private function click(evt:MouseEvent):void {
      access_token = CookieUtil.getCookie("piyotweet_access_token");
      access_token_secret = CookieUtil.getCookie("piyotweet_access_token_secret");

      if (access_token == null || access_token_secret == null) {
        ExternalInterface.call("function() { window.open(‘request.php’, ‘view’, ‘width=600, height=400, toolbar=no, status=no, menubar=no, scrollbars=no, resizable=no’); void(0); }");
      } else {
        var variables:URLVariables = new URLVariables();
        variables.access_token = access_token;
        variables.access_token_secret = access_token_secret;
        var request:URLRequest = new URLRequest("tweet.php");
        request.method = URLRequestMethod.POST;
        request.data = variables;
        try {
          loader.load(request);
        } catch (err:Error) {
          trace(err.message);
        }

      }
    }
    private function ioerror(evt:IOErrorEvent):void {
      trace(evt.text);
    }
    private function complete(evt:Event):void {
      if (evt.target.data != "null") {
        trace("piyo ! piyo !");
      } else {
        trace("cannot tweet !?");
      }
    }

  }

}

twitteroauth フォルダ内に、OAuth.php, twitteroauth.php を設置。

config.php
<?php

define(‘CONSUMER_KEY‘, ‘**********************‘);
define(‘CONSUMER_SECRET‘, ‘******************************************‘);
define(‘OAUTH_CALLBACK’, ‘http://blog.project-nya.jp/callback.php’);

?>

request.php
<?php

session_start();

require_once(‘twitteroauth/twitteroauth.php’);
require_once(‘config.php’);

$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
$oauth_callback = OAUTH_CALLBACK;

$connection = new TwitterOAuth($consumer_key, $consumer_secret);

$oauth_request_token = $connection->getRequestToken($oauth_callback);

$_SESSION[‘request_token‘] = $oauth_request_token[‘oauth_token‘];
$_SESSION[‘request_token_secret‘] = $oauth_request_token[‘oauth_token_secret‘];

$authorize_url = $connection->getAuthorizeURL($_SESSION[‘request_token‘]);

header(‘Location: ‘ . $authorize_url);

?>

callback.php
<?php

session_start();

require_once(‘twitteroauth/twitteroauth.php’);
require_once(‘config.php’);

$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
$oauth_callback = OAUTH_CALLBACK;

$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION[‘request_token‘], $_SESSION[‘request_token_secret‘]);

$access_token = $connection->getAccessToken($_REQUEST[‘oauth_verifier‘]);

setcookie(‘piyotweet_access_token’, $access_token[‘oauth_token’], time()+60*60*24*30, ‘/’);
setcookie(‘piyotweet_access_token_secret’, $access_token[‘oauth_token_secret’], time()+60*60*24*30, ‘/’);


$_SESSION[‘access_token‘] = $access_token;

unset($_SESSION[‘request_token‘]);
unset($_SESSION[‘request_token_secret‘]);

header(‘Location: access.php’);

?>

access.php
<?php

session_start();

require_once(‘twitteroauth/twitteroauth.php’);
require_once(‘config.php’);

$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
$oauth_callback = OAUTH_CALLBACK;

$oauth_access_token = $_SESSION[‘access_token‘];

$access_token = $oauth_access_token[‘oauth_token‘];
$access_token_secret = $oauth_access_token[‘oauth_token_secret‘];

$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
$connection->format = ‘json’;

$entry = ‘ぴよぴよ’;
$link = ‘http://blog.project-nya.jp/1151’;
$hashtag = ‘ #piyotweet’;
$message = $entry . $link . $hashtag;
$tweet = $connection->post(‘https://api.twitter.com/1.1/statuses/update.json’, array(‘status’ => $message));

?>
<script type="text/javascript">
<!-
  window.close();
->
</script>

tweet.php
<?php

require_once(‘twitteroauth/twitteroauth.php’);
require_once(‘config.php’);

$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
$oauth_callback = OAUTH_CALLBACK;

$access_token = $_POST[‘access_token‘];
$access_token_secret = $_POST[‘access_token_secret‘];

$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
$connection->format = ‘json’;

$entry = ‘ぴよぴよ’;
$exclamation = ‘!’;
for ( $n = 0; $n < rand(1, 10); $n++ ){
  $entry = $entry . $exclamation;
}
$link = ‘ http://bit.ly/hbyTGs’;
$hashtag = ‘ #piyotweet’;
$message = $entry . $link . $hashtag;
$tweet = $connection->post(‘https://api.twitter.com/1.1/statuses/update.json’, array(‘status’ => $message));

echo json_encode($tweet);

?>

[修正] (11/04/21 Thu 12:48)
認証して access_token を持っている人には、別ウィンドウを開かない仕組みに変更。callback.php で、cookie を保存。Flash側で cookie を読み取るのは、CookieUtilクラスで。
:check: 「Actionscript Cookie Util « in:flex Blog
[修正] (11/04/21 Thu 16:24)
Status is a duplicate.というエラーが返ってくるので、ぴよぴよにランダム要素を入れた。
[修正] (11/04/21 Thu 23:48)
CookieUtil の initメソッドを public にしてみた。
[修正] (11/04/30 Sat 23:58)
OAUTH_CALLBACK を絶対パスに変更。
[修正] (14/01/23 Thu 22:08)
http://api.twitter.com/1 を https://api.twitter.com/1.1 に変更。xml を json に変更。json_encode()も追加。投稿できるようになった。