0

上のRubyでGoogleのOAuth2のAPIを使用して、各アカウントはGoogle Analyticsアカウントを持っている、少なくとも1つのウェブサイトを持っています。 私のクライアントはGoogle Analyticsアカウントにアクセスするためにシステムを認証する必要がありますので、私は毎月の自動レポートページビューを生成し、この情報を自分のシステムの他の情報と共に提示することができます。お客様がGoogleアナリティクスアカウントへの申請を再度承認する必要はありません。私は複数の顧客アカウントを持つシステムを持っているRailsの

クライアントがGoogleアナリティクスへのアクセスを許可する場合、それは(私はトークンexpires_in: 3600セッション時間であることを信じている)約1時間動作します。この後はGoogleアナリティクスクライアントにアクセスできません。コードでわかるように、すでにaccess_type:: offlineを使用し、クライアントトークンをclient.update_token!で更新しようとしましたが、これを行う方法はわかりません。私がやろうとしていることが可能であるかどうか誰にでも教えてもらえますか?これを行う方法を教えてください。クライアントを使わずに毎月のレポートを生成できます。

私は(私はそれだけでテストですが、コードが良くありません知っている、多分私は私のデータベースに書き込む前に、アクセストークンを暗号化する必要があります)私のコントローラ内のいくつかのメソッドを作成しました。

簡単でしたが、私は、私は私のテストでは、APIの呼び出しで token_credential_uriを入れていなかったと思います
class ContractedProductsController < ApplicationController 

    def analytics_connection 
     client_info = { 
       client_id: Rails.configuration.x.google_api['client_id'], 
       client_secret: Rails.configuration.x.google_api['client_secret'], 
       authorization_uri: Rails.configuration.x.google_api['authorization_uri'], 
       scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY, 
       redirect_uri: url_for(action: :analytics_callback), 
       state: Base64.encode64('{ "account": ' + params[:account_id] + ', "contracted_product": ' + params[:id] + ' }'), 
       additional_parameters: { access_type: :offline, approval_prompt: :force } 
     } 
     client = Signet::OAuth2::Client.new(client_info) 

     redirect_to client.authorization_uri.to_s 
    end 

    def analytics_callback 
     client_info = { 
       client_id: Rails.configuration.x.google_api['client_id'], 
       client_secret: Rails.configuration.x.google_api['client_secret'], 
       token_credential_uri: Rails.configuration.x.google_api['token_credential_uri'], 
       redirect_uri: url_for(action: :analytics_callback), 
       code: params[:code] 
     } 
     client = Signet::OAuth2::Client.new(client_info) 
     response = client.fetch_access_token! 

     session[:google_api] = response 
     state = JSON.parse(Base64.decode64(params[:state]), object_class: OpenStruct) 

     redirect_to account_contracted_product_analytics_list_path(state.account, state.contracted_product) 
    end 

    def analytics_list 
     client = Signet::OAuth2::Client.new(access_token: session[:google_api]['access_token']) 
     service = Google::Apis::AnalyticsV3::AnalyticsService.new 
     service.authorization = client 

     @account_summaries = service.list_account_summaries 
    end 

    def analytics_save 
     api_integrations = [ 
       { 
         entity_type: ContractedProduct.name, 
         entity_id: @contracted_product.id, 
         key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:access_token], 
         value: session[:google_api]['access_token'] 
       }, 
       { 
         entity_type: ContractedProduct.name, 
         entity_id: @contracted_product.id, 
         key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token], 
         value: session[:google_api]['refresh_token'] 
       }, 
       { 
         entity_type: ContractedProduct.name, 
         entity_id: @contracted_product.id, 
         key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id], 
         value: params[:profile_id] 
       } 
     ] 
     @api_integration = ApiIntegration.create(api_integrations) 

     respond_to do |format| 
      if @api_integration 
       format.html { redirect_to [@account, @contracted_product], notice: I18n.t('controllers.contracted_products.analytics_data_successfully_saved', default: 'Analytics data was successfully saved.') } 
       format.json { render :show, status: :ok, location: [@account, @contracted_product] } 
      else 
       format.html { render :analytics_save, status: :ok, location: [@account, @contracted_product] } 
       format.json { render json: @contracted_products_service.errors, status: :unprocessable_entity } 
      end 
     end 
    end 

    def analytics_report 
     entity_conditions = { entity_type: ContractedProduct.name, entity_id: @contracted_product.id } 
     api_integration_access_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:access_token]) 
     # api_integration_refresh_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token]) 
     api_integration_profile_id = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id]) 

     client = Signet::OAuth2::Client.new(access_token: api_integration_access_token.value) 
     service = Google::Apis::AnalyticsV3::AnalyticsService.new 
     service.authorization = client 
     profile_id = 'ga:' + api_integration_profile_id.value 
     start_date = Date.today.at_beginning_of_month.last_month.to_s 
     end_date = Date.today.at_beginning_of_month.last_month.to_s 
     metrics = 'ga:pageviews' 
     dimensions = { 
       dimensions: 'ga:date' 
     } 

     @report = service.get_ga_data(profile_id, start_date, end_date, metrics, dimensions) 
    end 

end 
+0

ユーザーが認証すると、リフレッシュトークンが返されます。アカウントにアクセスする必要があるときに新しいアクセストークンを取得するために使用できるこの更新トークンを保存する必要があります。 – DaImTo

+0

私はすでにそれを保存しています。リフレッシュトークンで新しいアクセストークンを取得するにはどうすればよいですか? – maurymmarques

答えて

0

この回答を見る "How do I refresh my google_oauth2 access token using my refresh token? "私は正しい方法を見つけました。

API呼び出しに次のパラメータを追加しました:client_idclient_secrettoken_credential_uriおよびrefresh_token

def analytics_report 
    entity_conditions = { entity_type: ContractedProduct.name, entity_id: @contracted_product.id } 
    api_integration_refresh_token = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:refresh_token]) 
    api_integration_profile_id = ApiIntegration.find_by entity_conditions.merge(key: ApiIntegration::GOOGLE_ANALYTICS_KEYS[:profile_id]) 

    client_info = { 
      client_id: Rails.configuration.x.google_api['client_id'], 
      client_secret: Rails.configuration.x.google_api['client_secret'], 
      token_credential_uri: Rails.configuration.x.google_api['token_credential_uri'], 
      refresh_token: api_integration_refresh_token.value 
    } 
    client = Signet::OAuth2::Client.new(client_info) 
    service = Google::Apis::AnalyticsV3::AnalyticsService.new 
    service.authorization = client 
    profile_id = 'ga:' + api_integration_profile_id.value 
    start_date = Date.today.at_beginning_of_month.last_month.to_s 
    end_date = Date.today.at_beginning_of_month.last_month.to_s 
    metrics = 'ga:pageviews' 
    dimensions = { 
      dimensions: 'ga:date' 
    } 

    @report = service.get_ga_data(profile_id, start_date, end_date, metrics, dimensions) 
end 
関連する問題