0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Threads APIトークン取得・管理手順まとめ (Access Token取得・長期トークン延長について)

Posted at

Threads APIのトークンは60日で失効します

知らんかった。
ThreadsのAPI利用において、Access Token(短期・長期)の取得方法や、使用・更新方法をあまり知らなかったので、忘備録とともにまとめました。

事前準備

  1. Threads用のアプリ作成後、下記項目を確認してください
    Metaの開発者ダッシュボードにて
    ユースケースカスタマイズ設定に進み、以下を準備します。
  1. .envに環境変数を設定します。(ここでは仮で記載)
.env
THREADS_APP_ID=ThreadsアプリID
THREADS_APP_SECRET=Threadsのapp secret
THREADS_AUTH_CODE=
THREADS_SHORT_LIVED_TOKEN=
THREADS_LONG_LIVED_TOKEN=

認証コード取得の手順

Threadsの認証コードは有効期限が短く、短期間で処理をする必要があります。
次のスクリプトでURLを作成してブラウザで開きます。

console.log("https://threads.net/oauth/authorize?" +
"client_id=" + process.env.THREADS_APP_ID +
"&redirect_uri=https://mztm.jp/callback" +
"&scope=threads_basic,threads_content_publish" +
"&response_type=code");

ブラウザ上で得られた認証コードを控えます。(例:https://mztm.jp/callback/?code=ccccccccc#_)
URL末尾の code=ccccccccc 部分の認証コードを環境変数へ控える。( #_ は削除して下さい。)

時間も短いので、環境変数に記入して急ぎましょう。

.env
THREADS_AUTH_CODE=ccccccccc

短期トークンの取得方法

上の認証コードをつかって、短期Tokenを取得しましょう。
以下のスクリプトを実行しましょう

const axios = require("axios");

(async () => {
  try {
    const url = "https://graph.threads.net/oauth/access_token";
    const params = {
      client_id: process.env.THREADS_APP_ID,
      client_secret: process.env.THREADS_APP_SECRET,
      grant_type: "authorization_code",
      redirect_uri: "https://mztm.jp/callback",
      code: process.env.THREADS_AUTH_CODE,
    };
    const res = await axios.post(url, params);
    console.log(res.data);
  } catch (error) {
    console.error("API Error:", error.response?.data || error.message);
  }
})();

短期トークン取得結果(サンプル)

{
  "access_token": "短期トークンの文字列",
  "user_id": 123456789
}

得られた短期トークンを環境変数に設定

.env
THREADS_SHORT_LIVED_TOKEN=短期トークンの文字列

長期トークンの取得方法

const axios = require("axios");

(async () => {
  try {
    const url = "https://graph.threads.net/access_token";

    const res = await axios.get(url, {
      params: {
        grant_type: "th_exchange_token",
        client_secret: process.env.THREADS_APP_SECRET,
        access_token: process.env.THREADS_SHORT_LIVED_TOKEN,
      },
    });

    console.log(res.data);

  } catch (error) {
    console.error("API Error:", error.response?.data || error.message);
  }
})();

長期トークン取得結果(サンプル)

{
  access_token: '長期トークンの文字列',
  token_type: 'bearer',
  expires_in: 5000000
}

取得した長期トークンを環境変数に設定

.env
THREADS_LONG_LIVED_TOKEN=長期トークンの文字列

長期Tokenの再取得

60日の有効期限を迎える前に、長期トークンを更新可能です。 定期的に実行して更新しましょう。

また、長期Tokenの再取得なのは次の場合に限られます:

  • トークンが24時間以上経過している
  • トークンが*期限切れではない
  • アプリユーザーがthreads_basicの権限を許可している
const axios = require("axios");

(async () => {
  try {
    const url = "https://graph.threads.net/refresh_access_token";

    const res = await axios.get(url, {
      params: {
        grant_type: "th_refresh_token",
        access_token: process.env.THREADS_LONG_LIVED_TOKEN,
      },
    });
    console.log(res.data);
  } catch (error) {
    console.error("API Error:", error.response?.data || error.message);
  }
})();

再取得した新たな長期トークンを再度設定しなおします。

{
  access_token: '新しい長期トークンの文字列',
  token_type: 'bearer',
  expires_in: 5000000
}
.env
THREADS_LONG_LIVED_TOKEN=新しい長期トークンの文字列

結論

トークン取得の手順は少し面倒なので、自動化スクリプトやトークン管理用のWebアプリを作ると便利かもしれません。今後検討してみたいと思います。

参考サイト

以下に全部書いてある

Get Access Tokens
https://developers.facebook.com/docs/threads/get-started/get-access-tokens-and-permissions
Long-Lived Access Tokens
https://developers.facebook.com/docs/threads/get-started/long-lived-tokens

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?