例によってPHPを使いました。index.phpとlogin.phpを用意します。index.phpからlogin.phpに移動して、InstagramのOAuth認証ページを通し、access tokenを取得。index.phpに戻って、APIを叩く。そんな仕組み。
<?php $client_id = "*********************"; $client_secret = "*********************"; $redirect_uri = "*********************"; $token_uri = 'https://api.instagram.com/oauth/access_token'; $post = "client_id=".$client_id." &client_secret=".$client_secret." &grant_type=authorization_code &redirect_uri=".$redirect_uri." &code=".$_GET["code"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $token_uri); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $json = json_decode(curl_exec($ch)); curl_close($ch); // JSONから取得したユーザーデータをセッションに保存 $_SESSION['access_token'] = $json->access_token; $_SESSION['username'] = $json->user->username; $_SESSION['profile_picture'] = $json->user->profile_picture; $_SESSION['id'] = $json->user->id; $_SESSION['full_name'] = $json->user->full_name;
これはlogin.phpの一部。Instagramから返された$_GET["code"]を用いて、access tokenと同時にJSONを取得します。セッションに保存されたデータはusernameもprofile_pictureも取得できる。