LoginSignup
59
66

More than 5 years have passed since last update.

abraham/twitteroauthを使う

Last updated at Posted at 2015-03-05

使うための準備

ライブラリを使うにあたり、ドキュメントを確認。
インストールはComposerを使うらしいので、Composerを使う環境から整える。

Composerが何か知らなかったので、インストール方法を調べながら、何をするものか軽く確認。
どうやら、プロジェクト単位でパッケージ管理できるものみたい。
プロジェクトの作業ディレクトリにcomposer.jsonというインストールしたいパッケージを記述したファイルを用意してコマンドを走らせるとほしいものが手に入ると。

インストール方法は下記の通り。

$ curl -sS https://getcomposer.org/installer | php

完了したら、インストールを走らせたディレクトリ内にcomposer.pharというものができているので、下記コマンドで移動する。

$ sudo mv composer.phar /usr/local/bin/composer  

今度は、プロジェクトの作業ディレクトリに移動して、composer.jsonを作成する。

$ cd /work

$ vi composer.json

あとは、冒頭で記述したドキュメントに書いてある通りに書くわけだけど、requireを{}で囲む必要がある。

composer.json
{
    "require": {
        "php": ">=5.4.0",
        "abraham/twitteroauth": "0.5.0"
    }
{

最後に、

$ composer install

これで、abraham/twitteroauthを使用できる状態になる。

twitteroauthを使ってみる

ドキュメントに書いてあることを一通り試してみる。

なにはともあれ、認証するところから。

認証

tweet.phpというファイルを作成して進めていく。

$ vi tweet.php

今回は、Twitter Appsでアプリ作成して、自分のコンシューマキーやアクセストークンを使うので、Twitter Appsからその辺りの情報は確認しておく。
また、ユーザに使用してもらう系のアプリを作成したい場合は、ユーザ自身のアクセストークンを取得して、連携する必要があるので、アクセストークンを取得するための処理を書いていかなければなりません。今回は割愛しますが。

ライブラリを使用するために、下記記述を行う。

tweet.php
<?php
require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

続いて、先ほど確認しておいたoauth認証のために必要なコンシューマーキーやアクセストークンを記述する。

tweet.php
<?php
require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

$consumerKey = "xxxxxxxxxx";
$consumerSecret = "xxxxxxxxxxx";
$accessToken = "xxxxxxxxxxxxx";
$accessTokenSecret = "xxxxxxxxxxx";

ただ、このあたりのキーはconfig.phpにでも書いておきたいので、下記のようにしてみる。
(config.phpで定数として定義して、実際に使用するtweet.phpでは定数を使う。)

$ vi config.php
config.php
<?php
define('API_KEY', 'xxxxxxxxx');
define('API_SECRET', 'xxxxxxxxxx');
define('ACCESS_TOKEN', 'xxxxxxxxxxxx');
define('ACCESS_SECRET', 'xxxxxxxxxxxxxxx);
tweet.php
<?php
require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once('config.php');

$consumerKey = API_KEY;
$consumerSecret = API_SECRET;
$accessToken = ACCESS_TOKEN;
$accessTokenSecret = ACCESS_SECRET;

最後に、下記コードを入力して、認証部分が完成!

$connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

tweetする

なんかtweetする動きを上記コードに付け足して実現するわけですが、結構簡単。

//認証コードの下にこれ追加するだけ!
$result = $connection->post("statuses/update", array("status" => "hello world"));

//返ってきた内容を確認してみる
var_dump($result)

むっちゃ簡単!

ここで、twitterのREST APIを確認。
statuses/updateの部分を見てみる。これがtweetするときに使うもの。

POST statuses/update と書いてるので、
httpリクエストでpostを使用するんだなと。
Parametersもみてみると、色々なものがある。
requiredと書いているものが必須のパラメータで、statusにrequiredと付いている。これはつぶやく内容のこと。

今一度、tweetするために書いた内容を確認すると、
post("statuses/update", array("status" => "hello world"));

postや"statuses/update"はREST APIのドキュメントで確認した内容そのままで、array()の部分がパラメータを記述する、という書き方になっている!

では、続いてツイートを検索する動きを書いてみる。

searchする

//認証コードの下にこれ追加するだけ!
$result = $connection->get("search/tweets", array("q" => "twitter"));

qというパラメータが検索したい文字。
こちらもREST APIsearch/tweetsを確認してみるのがよい。

画像を投稿する

最後に画像を投稿する。
画像を投稿するには、画像をツイッターのhttps://upload.twitter.com というところにPOSTして、media_idを取得して、statuses/updateのパラメータにmedia_idをつけてtweetする、という流れになる。
ちなみに、このmedia_idは60分間有効のよう。

media_idを取得するには、REST APImedia/uploadを見る。

パラメータはアップロードしたい画像のパスを記述する。

//認証コードの下に追加
$media_id = $connection->upload("media/upload", array("media" => '/path/sample.jpg'));

//返ってきた情報を確認
var_dump($media_id)

これで、$media_idに情報が返ってくる。

object(stdClass)#7 (4) { ["image"]=> object(stdClass)#22 (3) { ["w"]=> int(48) ["h"]=> int(48) ["image_type"]=> string(10) "image/jpeg" } ["media_id"]=> int(573302141869158400) ["media_id_string"]=> string(18) "573302141869158400" ["size"]=> int(1351) }

ほしい情報はmedia_id_stringの部分なので、下記記述で取得できる。jsonデータの取得方法については、PHPでJSONのデータを処理する方法が参考になります!

$media_id->media_id_string

media_idは取得できたので、tweetしてみる。
このtweetする部分はすでに述べた通り。

パラメータが複数になったので、$parametersという変数を用意して記述。

$parameters = array(
    'status' => '画像投稿',
    'media_ids' => $media_id->media_id_string,
);
$result = $connection->post('statuses/update', $parameters);

画像投稿のコードを通しで書いておく。

<?php
require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
require_once('config.php');

$consumerKey = API_KEY;
$consumerSecret = API_SECRET;
$accessToken = ACCESS_TOKEN;
$accessTokenSecret = ACCESS_SECRET;

$connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

$media_id = $connection->upload("media/upload", array("media" => '/path/sample.jpg'));

$parameters = array(
    'status' => '画像投稿',
    'media_ids' => $media_id->media_id_string,
);
$result = $connection->post('statuses/update', $parameters);

簡単な紹介と言うかドキュメントに書いてあることしかやってないけど、tweetする、ツイートを検索する、画像投稿する、の流れを試してみました!

twitter REST APIで、ざっと何ができるか確認するのに、参考になったサイトがあったので、それを紹介して終わりとします。

【保存版】TwitterAPI1.1 REST API 全項目解説

59
66
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
66