railsでgoogle adwords apiを使う案件があるのですが、refresh_tokenが返ってきたり返ってこなかったりしたのでメモ。
結論から言うと、下記パラメータをリクエストのURLに必ず付与してあげるとrefresh_tokenが必ず返ってきます。
- approval_prompt=force : 認可画面をスキップしない
- access_type=offline : オフラインでAPIを使う
作成したクラスです。(Baseのままがいけてない)
GoogleApiHandler::Base.new.oauth2_authenticate_urlでrefresh_tokenが必ず返ってくる認証URLが返ってきます。
require 'adwords_api' module GoogleApiHandler class Base def initialize adword_api_client end def oauth2_authenticate_url begin api.authorize(oauth2_callback: login_callback_url) rescue AdsCommon::Errors::OAuth2VerificationRequired => e "#{e.oauth_url.to_s}&approval_prompt=force" end end # response example # { # :access_token => "xxxxxxxxxxxxxxxxxxx", # :refresh_token => "xxxxxxxxxx", # :issued_at => 2018-01-19 12:04:24 +0900, # :expires_in => 3600, # :id_token => nil # } def response(oauth2_verification_code) @response ||= api.authorize(oauth2_callback: login_callback_url, oauth2_verification_code: oauth2_verification_code) end private attr_reader :api def adword_api_client @api = AdwordsApi::Api.new(File.join(Rails.root, 'config', 'adwords_api.yml')) end def login_callback_url ENV.fetch('GOOGLE_OAUTH2_REDIRECT_URL') end end end
コメントを残す