0
0

More than 3 years have passed since last update.

PHPからTwitterを操作する

Last updated at Posted at 2020-07-23

OAuth 認証

TwitterOAuthというライブラリを使用して認証します。
下記のサイト参考にしました。
PHP で Twitter API OAuth 認証 「ログイン」…(1)

概要

修正前.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" => "自動ツイートテスト")
);

?>

参考

TwitterOAuth
Twitter REST APIの使い方
OAuth 2.0 の仕組みと認証方法

0
0
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
0
0