MastodonOAuthPHP をダウンロードして使用します。通信部分で、file_get_contents が使われているので、他方面でも参考になるでしょう。
必要なファイルは以下の三つ
1) HttpRequest.php (通信)
2) oAuth.php
3) Mastodon.php (API)
※ Mastodon API overview
ただ、ちょっと古い php のバージョンを使っている場合はエラーとなるので、Mastodon.php の 81 行目を変更する必要があります。( 5.4 以前では言語構造である empty の 引数に関数の戻り値を指定できないので、いったん変数にセットして使う)
※ ソースコードは全て UTF8N で保存
PHP 5.4 以前での変更箇所
/**
* Post a new status to your {visibility} timeline
* @param type $text
* @param type $visibility
*/
public function postStatus($text = "", $visibility = "public", $in_reply_to_id = null){
$credentials = $this->getCredentials();
if(!empty($credentials)){
$headers = $this->getHeaders();
//Create our object
$http = HttpRequest::Instance($this->getApiURL());
$status = $http::Post(
"api/v1/statuses",
array(
"status" => $text,
"visibility" => $visibility,
"in_reply_to_id" => $in_reply_to_id
),
$headers
);
return $status;
}
return false;
}
PHP でリダイレクトする URL の設定
oAuth.php の中で3箇所あります。最初の値は、redirect_uris なので、複数の URL を指定できるようですが、ここでは一つの localhost の テスト用の redirect.php を指定しています。
private $app_config = array(
"client_name" => "MastoTweet",
"redirect_uris" => "http://localhost/0502/redirect.php",
"scopes" => "read write",
"website" => "https://www.thecodingcompany.se"
);
public function getAuthUrl(){
if(is_array($this->credentials) && isset($this->credentials["client_id"])){
//Return the Authorization URL
return "https://{$this->mastodon_api_url}/oauth/authorize/?".http_build_query(array(
"response_type" => "code",
"redirect_uri" => "http://localhost/0502/redirect.php",
"scope" => "read write",
"client_id" => $this->credentials["client_id"]
));
}
return false;
}
public function getAccessToken($auth_code = ""){
if(is_array($this->credentials) && isset($this->credentials["client_id"])){
//Request access token in exchange for our Authorization token
$http = HttpRequest::Instance("https://{$this->mastodon_api_url}");
$token_info = $http::Post(
"oauth/token",
array(
"grant_type" => "authorization_code",
"redirect_uri" => "http://localhost/0502/redirect.php",
"client_id" => $this->credentials["client_id"],
"client_secret" => $this->credentials["client_secret"],
"code" => $auth_code
),
$this->headers
);
//Save our token info
return $this->_handle_bearer($token_info);
}
return false;
}
最初の処理 : アプリの登録
登録と言っても、実行する毎に client_id と client_secret が取得されます。実行は一度きりでいいですが、後でアクセストークンを取得するので、いったんファイルに保存します
require_once は、autoload.php のみでできるように example.php に書かれていますが、逆に初見では解りづらいのでカレントに置いて全て require_once しています。
mstdn.jp は、登録したいインスタンスのドメインです。
create_app.php
<?php
require_once("HttpRequest.php");
require_once("oAuth.php");
require_once("Mastodon.php");
$mastodon = new \theCodingCompany\Mastodon("mstdn.jp");
$token_info = $mastodon->createApp("appname", "サイトURL");
// appname : 認証済みアプリに表示される id
// サイトURL : 上記のリンク先となる URL
print "<pre>";
print_r( $token_info );
print "</pre>";
file_put_contents("token_info.txt", json_encode( $token_info, JSON_PRETTY_PRINT ) );
?>
アクセストークンの取得
いわゆる認証のいつもの流れですが、アクセストークンを取得する為の code を取得する URL を取得して、その URL に header 関数でリダイレクトします。
get_token.php
<?php
require_once("HttpRequest.php");
require_once("oAuth.php");
require_once("Mastodon.php");
$mastodon = new \theCodingCompany\Mastodon("mstdn.jp");
// client_id と client_secret のセット
$mastodon->setCredentials( json_decode( file_get_contents('token_info.txt'), true ) );
// アクセストークン取得の為のトークンを取得する URL
$auth_url = $mastodon->getAuthUrl();
// その URL をブラウザで表示
header("Location: $auth_url");
?>
そうすると、ログインしていなければ以下の画面になります
そして、ログインすると承認画面です。
承認したら、oAuth.php で指定した場所に飛ばされるので、以下のソースコードで受け取ります。
redirect.php
<?php
header( "Content-Type: text/html; Charset=utf-8" );
require_once("HttpRequest.php");
require_once("oAuth.php");
require_once("Mastodon.php");
$mastodon = new \theCodingCompany\Mastodon("mstdn.jp");
// client_id と client_secret のセット
$mastodon->setCredentials( json_decode( file_get_contents('token_info.txt'), true ) );
$access_token = $mastodon->getAccessToken($_GET['code']);
file_put_contents("token_info.txt", json_encode( $mastodon->getCredentials(), JSON_PRETTY_PRINT ) );
?>
AccessToken を取得して保存しました
これで準備は完了です。あとは FORM 作って投稿です。
mstdn_post.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
require_once("HttpRequest.php");
require_once("oAuth.php");
require_once("Mastodon.php");
$mastodon = new \theCodingCompany\Mastodon("mstdn.jp");
// client_id と client_secret と AccessToken のセット
$mastodon->setCredentials( json_decode( file_get_contents('token_info.txt'), true ) );
$mastodon->postStatus($_POST[text]);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width initial-scale=1.0 minimum-scale=1.0 maximum-scale=1.0 user-scalable=no" name="viewport">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
<form method="post">
<div>
<textarea name="text" style='width:400px;height:200px;'></textarea>
</div>
<input name="send" type="submit" value="send">
</form>
</body></html>