LoginSignup
1
1

More than 1 year has passed since last update.

GASでTwitter APIのOAuth2.0 Bearer Tokenの認証をする

Last updated at Posted at 2021-12-23

公式ドキュメントに書いてあることをやるだけです

公式ドキュメント

必要なもの

Twitter Developperアカウント
それで得られるConsumer Keys(API Key, API Secret)

ここでは解説しないので以下のサイトとか各自検索したりしてください

やり方

上記に書いた通り公式ドキュメントに書いてあることをやるだけです

function twitterOauth2(){
  const encodedKey = encodeURIComponent(TWITTER_API_KEY)
  const encodedSecret = encodeURIComponent(TWITTER_API_SECRET)

  const bearerTokenCredentials = Utilities.base64Encode(encodedKey + ':'+ encodedSecret)

  const option = {
    headers: {
      'Accept-Encoding': 'gzip',
      Authorization: 'Basic '+ bearerTokenCredentials ,

    },
    'contentType': 'application/x-www-form-urlencoded;charset=UTF-8',
    method: 'POST',
    payload: 'grant_type=client_credentials'
  }
  const res = UrlFetchApp.fetch('https://api.twitter.com/oauth2/token', option)
  Logger.log(res.getContentText())

}

Consumer Keysのエンコード, 証明書の生成

const encodedKey = encodeURIComponent(TWITTER_API_KEY)
const encodedSecret = encodeURIComponent(TWITTER_API_SECRET)

まずそれぞれのkeyをURLエンコード(RFC 1738)します.keyのエンコードに関してはencodeURIの方でも問題ないけどencodeURIはRFC 2396なのでちょっと仕様が違う1.そもそも「現状の仕様だとこのエンコードに意味はないよ.でも仕様変わるかもしれないから一応やってね」って書いてある.

URL encode the consumer key and consumer secret according to RFC 1738. Note that at the time of writing, this will not actually change the consumer key and secret, but this step should still be performed in case the format of those values changes in the future.

const bearerTokenCredentials = Utilities.base64Encode(encodedKey + ':'+ encodedSecret)

エンコードしたkeyを:でくっつけた後にbase64にエンコードしたら証明書の完成です.

Bearer Tokenの取得

const option = {
  headers: {
    'Accept-Encoding': 'gzip',
    Authorization: 'Basic '+ bearerTokenCredentials ,

  },
  'contentType': 'application/x-www-form-urlencoded;charset=UTF-8',
  method: 'POST',
  payload: 'grant_type=client_credentials'
}

const res = UrlFetchApp.fetch('https://api.twitter.com/oauth2/token', option)
Logger.log(res.getContentText())

UrlFetchApp.fetch()仕様のoptionは上記の感じ.ここまで何も間違ってなければログにBearer Tokenが表示されるのでメモって環境変数にでも設定しておきましょう.

使い方

おまけです.queryはエンコードしなくても大丈夫です.

function searchTwitter(){
  const url = 'https://api.twitter.com/2/tweets/search/recent?max_results=10&expansions=author_id&tweet.fields=attachments&query='

  const query = encodeURIComponent('from:yuzukichococh url:twitter.com/i/spaces')

  const option = {
    method: 'get',
    contentType: 'application/json',
    muteHttpExceptions: true,
    headers:{
      Authorization: 'Bearer '+ TWITTER_BEARER_Oauth2
    },
  }

  const res = JSON.parse(UrlFetchApp.fetch(url+query, option))
  Logger.log(res)
}

querylist:検索できないのが残念.streamで使いたかった...

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