Created
August 18, 2012 21:22
-
-
Save ricburton/3389949 to your computer and use it in GitHub Desktop.
An attempt at accessing the AdSense API from Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
protect_from_forgery | |
before_filter :check_auth | |
def check_auth | |
@client = Google::APIClient.new | |
@client.authorization.client_id = '************.apps.googleusercontent.com' | |
@client.authorization.client_secret = '***************' | |
@client.authorization.scope = 'https://www.googleapis.com/auth/adsense' | |
@client.authorization.redirect_uri = 'localhost:3000/callback' | |
@client.authorization.code = params[:code] if params[:code] | |
if @serialized_auth | |
@client.authorization = @serialized_auth | |
end | |
if @client.authorization.refresh_token && @client.authorization.expired? | |
@client.authorization.fetch_access_token! | |
end | |
@adsense = @client.discovered_api('adsense', 'v1.1') | |
unless @client.authorization.access_token || request.path_info =~ /^\/oauth2/ | |
redirect_to action: 'auths#authorize' | |
end | |
end | |
end | |
#------- | |
class AuthsController < ApplicationController | |
def index | |
call = { | |
:api_method => @adsense.reports.generate, | |
:parameters => { | |
'startDate' => '2011-01-01', | |
'endDate' => '2011-08-31', | |
'dimension' => ['CUSTOM_CHANNEL_NAME'], | |
'metric' => ['EARNINGS'] | |
} | |
} | |
@response = @client.execute(call) | |
end | |
def callback | |
@client.authorization.fetch_access_token! | |
# Persist the token here | |
@serialized_auth = @client.authorization | |
end | |
def authorize | |
redirect_to action: 'callback', status: 303 | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment