13

클라이언트 만드는 방법 : 특히 https://github.com/google/google-api-ruby-client, 나는 구글 API 클라이언트 사용하기 위해 노력하고 있습니다

을, 나는 google_contacts_api.rb 다음 사용하여 Google의 API 클라이언트를 통해 Google 주소록에 액세스하려면 : https://gist.github.com/lightman76/2357338dcca65fd390e2

나는 (x는 의도적이고 실제로 올바른 키입니다)과 같이 google_contacts_api.rb를 사용하는 것을 시도하고있다 :이나요 #에 대한 'undefined method GET으로 실수를 범됩니다

require './lib/google_contacts_api.rb' 
auth = User.first.authentications.first 
client = OAuth2::Client.new('x', 'x', :site => 'https://accounts.google.com') 
oauth2_object = OAuth2::AccessToken.new(client, auth.token) 
x = ContactList::GoogleContactsApi.new(client, oauth2_object).all_contacts 

요 제말은? gem`

나는 client을 정확하게 보내지 않고 있다고 생각하며, client을 만드는 방법을 보여주는 문서 나 예제를 찾을 수 없습니다. 이걸 어떻게 작동시킬 수 있을지에 대한 제안?

감사

+0

당신이 여기 앨빈의 답변을 확인 했 유튜브 콘텐츠를 검색하기 위해, 예를 들어 다음과 같이 사용하는 객체를 조회 할 준비가되어 stackoverflow.com/questions/25637485/access-google-contacts-api-on-ruby? –

+0

어떤 Signet :: OAuth2 :: 클라이언트를 사용하고 있습니까? – jpgeek

+0

@jpgeek 다음이 설치되어 있습니다 : gem 'signet', '0.7.3' – AnApprentice

답변

9

참고 : 일반적으로 연락처 목록을 점점 필요로가 에 대한 사용자의 인증이 개인 읽기 데이터, 아래의 예에서는 충분한 범위의 Oauth2 인증을 으로 이미 구현했으며 그 첫 번째 단계에서 에 유효한 '토큰'이 있다고 가정합니다.

API의 인증 및 API 자체가 여러 번 업그레이드 되었기 때문에 온라인으로 오래된/혼란스러운 설명서가 많습니다. 나에게 은 가장 유용한 문서는 http://www.rubydoc.info/github/google/google-api-ruby-client/

보석 '구글-API 클라이언트가'나는 유튜브에 인증 된 통화와 함께 작동 할 수있었습니다 고민을 많이 후, 알파와 매우 빠르게 움직이는 여전히, Gmail에서의 하나입니다 및 분석 APIS. 연락처 API가 동일하게 작동하기를 바랍니다.

Google API Ruby Client에는 API 인증을 관리하고 권한이 부여 된 서브 서비스 API를 요청하는 데 필요한 모든 것이 포함되어 있습니다. 헐리 (Hurley), 인장 (Signet) 또는 기타 HTTP/Rest 클라이언트와 어려움을 겪지 않아도됩니다. HTTP : //

#Gemfile 
gem 'google-api-client' 


#Class file 
require 'google/api_client/client_secrets.rb' #Manage global google authentication 
require 'google/apis/youtube_v3' #To be replaced with the proper Contact API 

access = {...} #Credentials object returned by your Oauth strategy (gem 'omniauth-google-oauth2' works like a charm) 
secrets = Google::APIClient::ClientSecrets.new({ 
"web" => {"access_token" => access['token'], 
"refresh_token" => access['refresh_token'], 
"client_id" => "xxxxxxxx.apps.googleusercontent.com", 
"client_secret" => "xxxxxxxxxxxx"}}) 

client = Google::Apis::YoutubeV3::YouTubeService.new #As per the require line, update it with you service API 
client.authorization = secrets.to_authorization 
client.authorization.refresh! 

지금까지 client 변수는 공인 내가

client.list_searches('snippet', q: 'xxxxxx', type: 'channel'){ |res, err| 
+2

이것은 나에게도 매우 실망스러운 문제였습니다. 당신과 비슷한 결론을 내린 블로그 글을 올렸습니다 : https://medium.com/@_benrudolph/end-to-end-devise-omniauth-google-api-rails-7f432b38ed75 –

+1

항상 '새로 고침'을 실행합니까? ? 'access_token'이 만료되지 않은 경우 Google에 추가 여행을하는 것은 불필요하다고 느낍니다. –

+0

@FellowStranger 정확히 그런 식으로 구현되지는 않지만 그렇습니다. 새로 고침을 요청하기 전에 실제 토큰의 만료 날짜를 먼저 테스트하여 요청을 저장하는 것이 좋습니다. – Roms

2

https://gist.github.com/lightman76/2357338dcca65fd390e2는 클라이언트가 헐리 클라이언트해야했다. 당신은 분명히 클라이언트와 인증을 위해

get() 

에 응답하지 않는 OAuth2를 :: 클라이언트를 전달하는 것처럼, 나는 헐리 클라이언트와 인장 :: OAuth2를 :: 클라이언트 인증을 시도하는 것이 좋습니다 보인다.

+0

감사합니다.하지만 어떻게 할 수 있습니까? – AnApprentice

3

잘못된 개체를 에 전달하면 해당 오류가 발생합니다. 이 요점은 clientHurley HTTP clientauth의 인스턴스가 Google's Signet library의 OAuth2 인스턴스가 될 것으로 예상합니다. 대신에 Intridea's OAuth2 libary을 시도하고 있습니다.

require 'google_contacts_api' 

auth = User.first.authentications.first 
client = OAuth2::Client.new('x', 'x', :site => 'https://accounts.google.com') 
oauth2_object = OAuth2::AccessToken.new(client, auth.token) 
google_contacts_user = GoogleContactsApi::User.new(oauth2_object) 

: 헐리는 죽은 프로젝트이며, 그 요점은 어떤 단위 테스트가 부족하기 때문에

, 나는 당신이 그런 Intridea의 OAuth2를 라이브러리와 호환되는 google_contacts_api gem로 테스트 작업 구현을 사용하는 것이 좋습니다 것

토큰 새로 고침 문제는 실제로는 별도의 질문에 속합니다. 즉, 당신이 주기적으로 새로 고침을 사용하여 새 토큰에 대한 요청을해야합니다 토큰 구글이 제공

data = { 
    :client_id => GOOGLE_APP_KEY, 
    :client_secret => GOOGLE_APP_SECRET, 
    :refresh_token => oauth2_refresh_token_for_user, 
    :grant_type => "refresh_token" 
} 
response = ActiveSupport::JSON.decode(RestClient.post("https://accounts.google.com/o/oauth2/token"), data) 
if response["access_token"].present? 
    puts response["access_token"] 
else 
    # No Token 
end 
rescue RestClient::BadRequest => e 
    # Bad request 
rescue 
    # Something else bad happened 
end 
+0

고마워요.하지만이 예제는 내가 갇혀있는 토큰을 새로 고침 할 필요가 없습니다. 이 추천 보석에 대한 토큰을 새로 고치는 방법에 대한 아이디어가 있습니까? – AnApprentice

+0

토큰을 직접 새로 고쳐야합니다. 예제는 http://stackoverflow.com/questions/21707734/refresh-token-using-omniauth-oauth2-in-rails-application 및 https://github.com/zquestz/omniauth-google-oauth2/issues/37을 참조하십시오. . 위의 짧은 것을 포함했습니다. – fny