InstagramAPIを使って写真取得してみる
InstagramAPIを利用するには、以下の情報が必要となる
- ユーザー名
- ユーザーID
- CLIENTID
- CLIENTSECRET
- AccessToken
1. Instagram Developer Documentationでクライアント登録
Developer Documentationへ
→ "ManageClients"
→ "Register new OAuth Client"
で登録する
登録すると、ClientID 、ClientSecret が発行される。
2. codeを取得する
取得した、"ClientID"と登録した"OAuth redirect_uri"を下記URLの対象部分へあてはめブラウザよりアクセスする。
https://api.instagram.com/oauth/authorize/?client_id=[CLIENT_ID]&redirect_uri[REDIRECT_URI]&response_type=code
正常にアクセスできれば、"OAuth redirect_uri"のパラメーターにcodeが付与され取得できる。
[REDIRECT_URI]?code=[CODE]
3. AccessToken、UserIDを取得する
ターミナルを開き、以下のコマンドを実行
curl \ -F 'client_id=[CLIENT_ID]' \ -F 'client_secret=[CLIENT_SECRET]' \ -F 'grant_type=authorization_code' \ -F 'redirect_uri=[OAuth_REDIRECT_URI]' \ -F 'code=[CODE]' \ https://api.instagram.com/oauth/access_token
・実行結果
{{"access_token":"[ACCESS_TOKEN]", "user":{"username":"[USER_NAME]", "bio":"", "website":"[WEBSITE]", "profile_picture":"[PROFILE_PICTURE]", "full_name":"[FULL_NAME]", "id":"[USER_ID]"}}
4. PHPで写真を取得する
<?php $limit=30; /* Instagram */ define('INSTAGRAM_USER_NAME', '[USER_NAME]'); define('INSTAGRAM_USER_ID', '[USER_ID]'); define('INSTAGRAM_ACCESS_TOKEN', '[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='.$limit; $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 = json_decode(curl_exec($ch)); curl_close($ch);