OAuth 認証
TwitterOAuthというライブラリを使用して認証します。
下記のサイト参考にしました。
PHP で Twitter API OAuth 認証 「ログイン」…(1)
概要
下記でツイッターアプリケーションの登録をする
https://developer.twitter.com/en/apps
※参考サイトTwitter Developerの開発者申請(例文あり)とAPIキー取得方法まとめ【2019年版】(1)を参考に下記phpファイルを作成する。まずはコピペする
config.php
login.php
logout.php
callback.php
※member.phpは認証後のページなので任意のページでOKconfig.phpは環境変数(.htaccess)から取得するように、下記の修正をする
修正前.php
<?php
//アプリケーションの Consumer Key と Consumer Secret
$sTwitterConsumerKey = '***********************************'; //Consumer Key (API Key)
$sTwitterConsumerSecret = '***********************************'; //Consumer Secret (API Secret)
//アプリケーションのコールバックURL
$sTwitterCallBackUri = 'https://wepicks.net/code-example/twitter-restapi/login/callback.php'; //コールバックURL
//~~~~~~~以下省略
?>
修正後.php
<?php
//アプリケーションの Consumer Key と Consumer Secret
$sTwitterConsumerKey = getenv('TW_CONSUMER_KEY');
$sTwitterConsumerSecret= getenv('TW_CONSUMER_SECRET');
$sTwitterCallBackUri = getenv('TW_CALLBACK_URL');
//~~~~~~~以下省略
?>
- callback.php終了後のページを任意のページに変更する
//~~~~~~~以上省略
header('location: member.php'); //←任意のページに変更する
投稿
以下を参考に実施
PHPからTwitterに投稿する
<?php
##############################################
### 初期設定
//セッションスタート
session_start();
//文字セット
header("Content-type: text/html; charset=utf-8");
//インクルード
require_once 'config.php';
require_once 'twitteroauth/autoload.php';
//インポート
use Abraham\TwitterOAuth\TwitterOAuth;
if(empty($_SESSION['twAccessToken'])){
echo 'error access token!!';
exit;
}
##############################################
$objTwitterConection = new TwitterOAuth
(
$sTwitterConsumerKey,
$sTwitterConsumerSecret,
$_SESSION['twAccessToken']['oauth_token'],
$_SESSION['twAccessToken']['oauth_token_secret']
);
// ツイート
$result = $objTwitterConection->post(
"statuses/update",
array("status" => "自動ツイートテスト")
);
?>