LoginSignup
4
7

More than 3 years have passed since last update.

【PHP】Twitter, Facebookページ, Instagram自動投稿(OAuth認証)

Last updated at Posted at 2021-04-21

Twitter、Facebookページ、Instagramビジネスアカウントへの自動投稿について、簡単なサンプルコードを作成しました。
※Facebookはページ(個人アカウントではない)、InstagramはそのFacebookページに紐づけられたビジネスアカウントである必要があります。

※2018年8月に、Facebookタイムライン(個人アカウント)へ自動投稿できる機能は廃止されています。

Twitter

準備

各詳細手順はこの記事では省きます。

サンプルプログラム

Twitterログインを行う⇒成功すると、自動で該当Twitterアカウントに投稿される

login.php
<?php
// twitteroauth の読み込み
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

//Twitterのコンシュマーキー(APIキー)等読み込み
define('TWITTER_API_KEY', '取得したconsumer key'); //Consumer Key (API Key)
define('TWITTER_API_SECRET', '取得したconsumer secret');//Consumer Secret (API Secret)

//コールバックページのURL
define('CALLBACK_URL', 'https://*********/callback.php');

//Twitterからリクエストトークンを取得する
$connection = new TwitterOAuth(TWITTER_API_KEY, TWITTER_API_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => CALLBACK_URL));

//リクエストトークンはコールバックページでも利用するためセッションに格納しておく
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

//Twitterの認証画面のURL
$oauthUrl = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));

echo '<a href="' . $oauthUrl . '">Log in with Twitter!</a>';
?>
callback.php
<?php
// twitteroauth の読み込み
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

//Twitterのコンシュマーキー(APIキー)等読み込み
define('TWITTER_API_KEY', '取得したconsumer key'); //Consumer Key (API Key)
define('TWITTER_API_SECRET', '取得したconsumer secret');//Consumer Secret (API Secret)

session_start();

//リクエストトークンを使い、アクセストークンを取得する
$twitter_connect = new TwitterOAuth(TWITTER_API_KEY, TWITTER_API_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitter_connect->oauth('oauth/access_token', array('oauth_verifier' => $_GET['oauth_verifier'], 'oauth_token'=> $_GET['oauth_token']));

//アクセストークンからユーザの情報を取得する
$user_connect = new TwitterOAuth(TWITTER_API_KEY, TWITTER_API_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user_info = $user_connect->get('account/verify_credentials');//アカウントの有効性を確認するためのエンドポイント

if(isset($user_info->id_str)){   
     //画像をアップロードし、画像のIDを取得
     $imageId = $user_connect->upload('media/upload', ['media' => 'test.png']);
     $tweet = [
       'status' =>
           '💡ログインに成功しました❗❗' . PHP_EOL .
           '' . PHP_EOL .
           '✋✨' . PHP_EOL .
           '' . PHP_EOL .
           '💻https://example.com' . PHP_EOL .
           '' . PHP_EOL .
           '#test #開発 #プログラミング',
           'media_ids' => implode(',', [
               $imageId->media_id_string
           ])
     ];

     $user_connect->post('statuses/update', $tweet);
     echo $user_info->name.'さん、ログインに成功しました!';
}else{
     echo 'ログイン失敗に失敗しました';
}
?>

Facebook, Instagram

準備

各詳細手順はこの記事では省きます。

  • Facebookページ、Instagramアカウントの作成
     ※Instagramは作成後、設定画面から「プロアカウント」に切り替え必要、FacebookページとInstagramアカウントを紐づける必要あり
  • Facebook for Developers登録 
  • アプリケーションの作成、設定
     ※プロダクトに、「Facebookログイン」「InstagramグラフAPI」を追加
  • App ID, App secretの取得
  • Facebook SDKのインストール:GitHub(https://github.com/facebookarchive/php-graph-sdk)

実際にコードを書く前に、以下のツールで確認することができます。
グラフAPIエクスプローラ

サンプルプログラム

Facebookログインを行う⇒成功すると、自動で該当Facebookページ、Instagramアカウントに投稿される

login.php
<?php
require_once __DIR__ . "/vendor/autoload.php";

session_start();

$fb = new Facebook\Facebook([
    'app_id' => '取得したapp id',
    'app_secret' => '取得したapp secret',
    'default_graph_version' => 'v2.10',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://*******/callback.php', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';
?>
callback.php
<?php
require_once __DIR__ . "/vendor/autoload.php";

session_start();

$fb = new Facebook\Facebook([
    'app_id' => '取得したapp id',
    'app_secret' => '取得したapp secret',
    'default_graph_version' => 'v2.10',
]);

$helper = $fb->getRedirectLoginHelper();

try {
    $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    // When validation fails or other local issues
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

if (! isset($accessToken)) {
    if ($helper->getError()) {
        header('HTTP/1.0 401 Unauthorized');
        echo "Error: " . $helper->getError() . "\n";
        echo "Error Code: " . $helper->getErrorCode() . "\n";
        echo "Error Reason: " . $helper->getErrorReason() . "\n";
        echo "Error Description: " . $helper->getErrorDescription() . "\n";
    } else {
        header('HTTP/1.0 400 Bad Request');
        echo 'Bad request';
    }
    exit;
}

//長期トークンへの変換処理は省略

$_SESSION['fb_access_token'] = (string) $accessToken;

header('Location: index.php');
?>
index.php
<?php
require_once __DIR__ . "/vendor/autoload.php";

session_start();

$fb = new Facebook\Facebook([
    'app_id' => '取得したapp id',
    'app_secret' => '取得したapp secret',
    'default_graph_version' => 'v2.10',
]);

try {
    // Returns a `Facebook\FacebookResponse` object
    $response = $fb->get('/me?fields=id,name', $_SESSION['fb_access_token']);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}
$user = $response->getGraphUser();

//FBページアクセストークンを取得する
$response = $fb->get('/'.$user['id'].'/accounts', $_SESSION['fb_access_token']);
$result = $response ->getDecodedBody();

$page_id = $result['data'][0]['id'];
$page_access_token = $result['data'][0]['access_token'];
$page_name = $result['data'][0]['name'];

try {
    // Returns a `FacebookFacebookResponse` object
    $response = $fb->post(
        '/'.$page_id.'/feed',
        array (
            'message' => 'Facebook PHP-sdkのテストです。',
            'link' => 'https://developers.facebook.com/docs/'
        ),
        $page_access_token
    );
} catch(FacebookExceptionsFacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}
echo $page_name.'への投稿が完了しました!'. PHP_EOL;

//Instagramプロアカウントを取得する
try {
    $response = $fb->get('/'.$page_id.'?fields=instagram_business_account', $_SESSION['fb_access_token']);
    $result = $response ->getDecodedBody();

    $insta_id = $result['instagram_business_account']['id'];
} catch(FacebookExceptionsFacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

//media create
try {
    $response = $fb->post(
        '/'.$insta_id.'/media',
        array (
            'image_url' => 'https://*****/*****.jpg',
            'caption' =>
                '💡お知らせが更新されました❗❗' . PHP_EOL .
                '✋✨' . PHP_EOL .
                '' . PHP_EOL .
                '#test #開発 #プログラミング'
        ),
        $_SESSION['fb_access_token']
    );
    $result = $response ->getDecodedBody();

    $media_id = $result['id'];
} catch(FacebookExceptionsFacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

//media publish
try {
    $response = $fb->post(
        '/'.$insta_id.'/media_publish',
        array (
            'creation_id' => $media_id
        ),
        $_SESSION['fb_access_token']
    );
} catch(FacebookExceptionsFacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

echo 'instagramへの投稿が完了しました!';

$graphNode = $response->getGraphNode();
?>

あくまで超簡易的なコードになりますが、ご参考になれば幸いです。

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