PHPを使いInstagramの写真をサイトへ表示 : PHP

Pocket

2016年6月にAPIの利用に関する仕様が変更なりました。下記記事は2013年時点の情報です(追記 2016.09.06)。

Instagram APIでサイトに自分の写真を表示するメモ。
Instagramから最新投稿のサムネイル画像を取得する。

Instagram Developer Documentation

クライアント情報準備

(1) Instagramアカウントを作成(アプリ)

スマートフォンでアプリをダウンロードしてアカウント作成する。

(2) Instagram Developer Documentationでアプリケーション登録(ウェブ)

Manage Clients > Register Your Applicationでアプリケーションを登録する。
下記情報が表示される。

  • Client ID
  • Client Secret
  • Website URL
  • Redirect URI

(3) code取得[^2]

下記アドレスへ(2)で取得したClient IDとRedirect URLを付けてGETリクエストしcodeを取得する。
codeがレスポンスとして返る。

https://api.instagram.com/oauth/authorize/?client_id=Client ID&redirect_uri=Redirect URI&response_type=code

Redirect URIがhttp://www.example.comのときレスポンスは下記のようになる。

http://www.example.com/?code=コード文字列

(4) アクセストークン, ユーザー名, IDなどを取得

ターミナルから下記curlコマンドを使いアクセストークンなどの情報を取得する。

$ curl \
> -F 'client_id=Client ID' \
> -F 'client_secret=Client Secret' \
> -F 'grant_type=authorization_code' \
> -F 'redirect_uri=Redirect URI' \
> -F 'code=コード文字列' \
> https://api.instagram.com/oauth/access_token

サムネイルを表示するコード

// クライアント情報
define( 'INSTAGRAM_USER_NAME', '*****' );
define( 'INSTAGRAM_USER_ID', '*****' );
define( 'INSTAGRAM_ACCESS_TOKEN', '******' );
define( 'INSTAGRAM_API_URL', 'https://api.instagram.com/v1/users/'.INSTAGRAM_USER_ID.'/media/recent?access_token='.INSTAGRAM_ACCESS_TOKEN );

$uri = INSTAGRAM_API_URL . '&count=10';
$options[ 'request_type' ] = 0;
$ch = curl_init();

// 画像情報取得
curl_setopt( $ch, CURLOPT_URL, $uri );
curl_setopt( $ch, CURLOPT_POST, $options[ 'request_type' ] );
if( !empty( $options[ 'post' ] ) ) {
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $options[ 'post' ] );
}
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
$json =  curl_exec( $ch );
curl_close( $ch);

// 画像情報(JSON)を配列へ
$images = array();
if( ! empty( $json  ) ) {
    foreach( json_decode( $json )->data as $item ){
        $src   = $item->images->standard_resolution->url;
        $thumb = $item->images->thumbnail->url;
        $url   = $item->link;

        $images[] = array(
            "src"   => htmlspecialchars( $src ),
            "thumb" => htmlspecialchars( $thumb ),
            "url"   => htmlspecialchars( $url )
        );

    }
}

// サムネイル表示
if ( ! empty( $images ) ) {
    foreach( $images as $image ){
        echo '<a href="' . $image[ 'url' ] . '"><img src="' . $image[ 'thumb' ] . '"></a>';
    }
}

参考サイト

» InstagramAPIを使って写真取得してみる – ONILOQ NOTE
» Instagram Photo Search Engine With JQuery And PHP

https://api.instagram.com/oauth/authorize/?client_id=Client ID&redirect_uri=Redirect URI&response_type=token

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。