PHPでTwitterのOAuthを試してみる(Opauth版)

PHPでTwitterのOAuthを試してみる
の続き

PHPのOpauthライブラリを使って、TwitterのOAuthを試してみる。

【参考】
OpauthとtmhOAuthで極めてお手軽にTwitterと連携してみる – Mach3.laBlog
http://blog.mach3.jp/2012/08/24/opauth-and-tmhoauth-for-twitter.html

.htaccessの有効化

Opauthのライブラリでは、mod_rewriteを使うので、
AllowOverrideがNoneになっている場合は、有効にしておく。

$ sudo vi /etc/httpd/conf/httpd.conf
<Directory "/var/www/html">
・・・
AllowOverride None
↓
AllowOverride All
$ sudo service httpd restart

Opauthのダウンロード

下記のサイトからダウンロードし、

Opauth – Multi-provider authentication framework for PHP
http://opauth.org/

.htaccessとlibディレクトリをindex.phpと同じ階層に置く。

下記のような感じになる。

lib/
└Opauth/
 ├Strategy/
 │└・・・
 ├Opauth.php
 └OpauthStrategy.php
.htaccess
oauth.conf.php
index.php
callback.php

あと、
lib/Opauth/Strategy/Twitter/TwitterStrategy.php
を開いて、1を1.1に修正する。でないとエラーになる。

'verify_credentials_json_url' => 'https://api.twitter.com/1/account/verify_credentials.json',
	↓
'verify_credentials_json_url' => 'https://api.twitter.com/1.1/account/verify_credentials.json',

アプリケーションの設定

前回の記事と同様、下記のように設定する。

サンプルプログラムの作成

opauth.conf.php
<?php
// アプリケーション設定
$config = array(
	'path' => '/',
	'callback_url' => '{path}callback.php',
	'security_salt' => 'abcdefghijklmnopqrstuvwxyz',

	'Strategy' => array(
		'Twitter' => array(
			'key' => 'bbvhN3kLGqD6ipXmkR5jw9b9A',
			'secret' => 'P52p4DYvijL0uyiMqq1rQwtBTxyPLfYXS6gChHcUxBksUbHFqK'
		),
	),
);
index.php
<?php
require('lib/Opauth/Opauth.php');
require('opauth.conf.php');

// 認証
new Opauth($config);
callback.php
<?php
require('lib/Opauth/Opauth.php');
require('opauth.conf.php');


//--------------------------------------
// アクセストークンの取得
//--------------------------------------
session_start();
new Opauth($config, false);
if(!isset($_SESSION['opauth']['auth']['credentials'])){
	echo 'エラー発生';
	exit;
}


//--------------------------------------
// ユーザー情報を取得してみる
//--------------------------------------
require('lib/Opauth/Strategy/Twitter/Vendor/tmhOAuth/tmhOAuth.php');

// APIを利用するにはtmhOAuthという別のライブラリを使う
$twitter = new tmhOAuth(
	array(
		"consumer_key" => $config['Strategy']['Twitter']['key'],
		"consumer_secret" => $config['Strategy']['Twitter']['secret'],
		"user_token" => $_SESSION['opauth']['auth']['credentials']['token'],
		"user_secret" => $_SESSION['opauth']['auth']['credentials']['secret'],
		"curl_ssl_verifypeer" => false,
	)
);

// 取得
$status = $twitter->request("GET", $twitter->url("1.1/account/settings"));
if($status != 200){
	echo 'エラー発生';
	exit;
}

// 表示
echo "<pre>" . print_r(json_decode($twitter->response["response"]), true) . "</pre>";

サンプルプログラムの確認

http://192.168.56.101/twitter
にアクセスする。

[連携アプリを認証]をクリックすると、
http://192.168.56.101/callback.php
が呼ばれ、ユーザーの設定情報が表示される。