方法未定义

时间:2019-09-13 16:01:40

标签: ruby google-webmaster-tools google-search-console google-api-ruby-client

我有一个旧版的Rails应用,我正在尝试获取Google Search Console数据以显示给客户。但是,当我尝试访问列在以下列表中的methods任何时,我已经成功获得工作许可:

Class: Google::Apis::WebmastersV3::WebmastersService

我收到“未定义的方法”错误。

Ruby:1.9.3

路轨:2.3.17

google-api-client(0.3.0)

这是我的代码:

    @client = Google::APIClient.new
    @client.authorization.access_token = @oauth_response['access_token']
    @service = @client.discovered_api('webmasters', 'v3')
    @client_response = @client.execute(:api_method => @service.list_sitemaps, :parameters => {'site_url' => 'https://sitename.com'})

我期望可以解析的json负载,但出现以下错误:

undefined method `list_sitemaps' for #<Google::APIClient::API:0x3fda2b78fc04 ID:webmasters:v3>

我想念什么?我一直在寻找几天。我知道,鉴于google-api-client gem很旧,这甚至可能无法实现。我认为我正在使用here中所述的正确的0.9之前的语法。

任何帮助将不胜感激!

编辑:

我尝试了另一种途径,并且能够检索访问令牌,并使用该令牌创建了Legato用户。

   @oauth_options = {
      body: {
        client_id: 'xxxxxxxx',
        client_secret: 'xxxxxx',
        refresh_token: 'xxxxxxxxx',
        grant_type: 'refresh_token'
      },
      headers: {
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    }
    @oauth_response = HTTParty.post('https://accounts.google.com/o/oauth2/token', @oauth_options)
    @user = Legato::User.new(@oauth_response['access_token'])
    @accounts = @user.accounts

从那里,我得到以下无用的错误:

undefined method 'get' for #<String:0x007fd2299e6fd0>

/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/request.rb:25:in 'oauth_2_response'
/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/request.rb:15:in 'raw_response'
/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/request.rb:11:in 'response'
/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/user.rb:14:in 'request'
/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/management/finder.rb:11:in 'all'
/Users/shorepound/.rvm/gems/ruby-1.9.3-p551@bizyellow/gems/legato-0.7.0/lib/legato/user.rb:21:in 'accounts'
/Users/shorepound/Development/apu_new/app/controllers/traffic_controller.rb:37:in 'index'

有什么想法吗?

编辑2:

似乎我在使用字符串access_token而不是oauth access_token对象。添加以下内容对我来说一切正常:

    oauth_client = OAuth2::Client.new('', '', {
      authorize_url: 'https://accounts.google.com/o/oauth2/auth',
      token_url: 'https://accounts.google.com/o/oauth2/token'
    })

    access_token = OAuth2::AccessToken.new(oauth_client, oauth_response['access_token'], expires_in: 1.hour)

这是所有东西的外观:

    oauth_options = {
      body: {
        client_id: 'YOUR_CLIENT_ID',
        client_secret: 'YOUR_CLIENT_SECRET',
        refresh_token: 'YOUR_REFRESH_TOKEN',
        grant_type: 'refresh_token'
      },
      headers: {
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    }
    oauth_response = HTTParty.post('https://accounts.google.com/o/oauth2/token', oauth_options)

    oauth_client = OAuth2::Client.new('', '', {
      authorize_url: 'https://accounts.google.com/o/oauth2/auth',
      token_url: 'https://accounts.google.com/o/oauth2/token'
    })

    access_token = OAuth2::AccessToken.new(oauth_client, oauth_response['access_token'], expires_in: 1.hour)

    @user = Legato::User.new(access_token)

编辑3:

传奇继续!我深入研究了google-api-client gem(版本0.3.0)的代码,并发现duh太老了,无法使用最新的gem版本中的新方法。无法更新Ruby和Rails,因此我仍在尝试使其与旧的0.3.0 gem一起使用。我好亲切!

这是我的代码:

@gsc_response = @gsc_client.execute(
 :version => 'v3',
 :api_method => 'webmasters.searchanalytics.query',
 :headers => {
  'Content-Type' => 'application/json',
 },
 :body => {
  startDate:  @startDate,
  endDate:  @endDate,
 },
 :parameters => {
  siteUrl:    'https://sitename.com'
 }
)

这是发帖请求:

Google Service Request: ["POST", "https://www.googleapis.com/webmasters/v3/sites/https:%2F%2Fsitename.com/searchAnalytics/query", [["Content-Type", "application/json"], ["Authorization", "OAuth **removed**"], ["Cache-Control", "no-store"]], ["[:startDate, \"2019-07-05\"][:endDate, \"2019-10-03\"]"]]

这是回应:

Google Service Response: #, @parameters={:siteUrl=>"https://bizyellow.com"}, @headers={"Content-Type"=>"application/json"}, @body={:startDate=>"2019-07-05", :endDate=>"2019-10-03"}>, @request=["POST", "https://www.googleapis.com/webmasters/v3/sites/https:%2F%2Fsitename.com/searchAnalytics/query", [["User-Agent", "google-api-ruby-client/0.3.0 Mac OS X/10.12.6"], ["Content-Type", "application/json"], ["Authorization", "OAuth ***removed***"], ["Cache-Control", "no-store"]], ["[:startDate, \"2019-07-05\"][:endDate, \"2019-10-03\"]"]], @response=[400, [["Vary", "X-Origin, Origin,Accept-Encoding"], ["Content-Type", "application/json; charset=UTF-8"], ["Date", "Thu, 03 Oct 2019 19:59:05 GMT"], ["Expires", "Thu, 03 Oct 2019 19:59:05 GMT"], ["Cache-Control", "private, max-age=0"], ["X-Content-Type-Options", "nosniff"], ["X-Frame-Options", "SAMEORIGIN"], ["X-Xss-Protection", "1; mode=block"], ["Server", "GSE"], ["Alt-Svc", "quic=\":443\"; ma=2592000; v=\"46,43\",h3-Q048=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000"], ["Accept-Ranges", "none"], ["Transfer-Encoding", "chunked"]], ["{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"global\",\n \"reason\": \"parseError\",\n \"message\": \"Parse Error\"\n }\n ],\n \"code\": 400,\n \"message\": \"Parse Error\"\n }\n}\n"]]>

我真的很茫然,因为Parse Error并没有给我太多帮助。任何帮助都将使我真正摆脱这个可怕的地狱。

编辑4:

我终于让它工作了,而且还不漂亮。我将日期串联起来,并将其全部处理为API可以解析的字符串:

@start_date = ['startDate', '2019-07-01'].to_s.gsub(',',':').gsub('[','{').gsub(']','}')
@end_date = ['endDate', '2019-10-01'].to_s.gsub(',',':').gsub('[','{').gsub(']','}')
@dates = @start_date.sub('}',',') + @end_date.sub('{','')

然后将字符串作为“合并的主体”传递:

:merged_body => @dates,

希望这会对某人有所帮助。

最终编辑

这是一个更漂亮的字符串,该字符串传递到merged_body,其中包括一个用于获取特定路径数据的过滤器:

startDate = 90.days.ago.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")
body_str = "{\"startDate\": \"#{startDate}\",\"endDate\": \"#{endDate}\",\"dimensionFilterGroups\":[{\"filters\":[{\"dimension\": \"page\",\"expression\": \"#{business_path(@business)}\",\"operator\": \"contains\"}]}]}"

0 个答案:

没有答案