呼び出し順
認証
JavaScript で次のコードを呼んで、Instagram の認証ウィンドウで認証します。
window.location.href = `https://api.instagram.com/oauth/authorize
?client_id=${app-id}
&redirect_uri=${window.location.protocol}//${window.location.host}/
&scope=user_profile,user_media
&response_type=code`;

認証に成功すると、URLに認証コードが付与されて返ってきます。

アクセストークン
認証コードを使って、アクセストークンを取得します。
const searchParams = new URLSearchParams(window.location.search);
const response = await axios.post("https://api.instagram.com/oauth/access_token", {
client_id: {app-id},
client_secret: {app-secret},
grant_type: 'authorization_code',
redirect_uri: `${window.location.protocol}//${window.location.host}/`,
code: searchParams.get('code')
});
成功すると次のJSONが返ってきます。
- アクセストークン
- ユーザーID
{
"access_token": "IGQVJ...",
"user_id": 17841405793187218
}
ただしここで注意が必要です。
ここで返ってきたユーザーIDは使えません。
次の工程で改めてユーザーIDを取得して、そのユーザーを使っていくようにします。これに気がつくまで丸1日かかりました。
ユーザー情報
アクセストークンを使って、ユーザーIDを取得します。
const response = await axios.get(`https://graph.instagram.com/v16.0/me?fields=id,username&access_token=${access_token}`);
成功すると次のJSONが返ってきます。
- ユーザーID
- ユーザー名
{
"id": "5846129734852319",
"username": "Emily.Nathan"
}
InstagramグラフAPI
これでやっと必要な情報がそろいました。
ユーザー情報で取得したユーザーIDとアクセストークンを使って、 InstagramグラフAPI が使えるようになります。
const response1 = await axios.get(`https://graph.instagram.com/v16.0/${me.id}?access_token=${access_token}`);
const response2 = await axios.get(`https://graph.instagram.com/v16.0/${me.id}/media?access_token=${access_token}`);
おわりに
参考サイト
Instagramプラットフォーム - ドキュメンテーション - Meta for Developers