[英]How do I authorize a service account for Google Calendar API in Ruby?
[英]How can I authorize with OAuth 2.0 for google's predictive API in Ruby?
我試圖簡單地向Google的托管模型sample.sentiment發送請求。 我無法弄清楚如何通過Google使用Oauth 2.0進行授權,而我卻花了無數的時間。 如果可以提供我的代碼,將很有幫助。 這是我正在做的事情。
client = Google::APIClient.new({:application_name => "CCE",:application_version => "1.0"} )
plus = client.discovered_api('prediction')
# Initialize OAuth 2.0 client
client.authorization.client_id = 'my client id'
client.authorization.client_secret = 'my client secret'
client.authorization.redirect_uri = 'my callback url'
client.authorization.scope = 'https://www.googleapis.com/auth/prediction'
# Request authorization
redirect_uri = client.authorization.authorization_uri
# Wait for authorization code then exchange for token
client.authorization.code = '....'
client.authorization.fetch_access_token!
# Make an API call
result = client.execute(
:api_method => plus.activities.list,
:parameters => {'hostedModelName' => 'sample.sentiment', 'userId' => ''})
`
嗯,Web上的示例可能會有些混亂,但是如果您想利用服務器與服務器之間的通信-意味着不涉及最終用戶和瀏覽器,那么以下代碼應該對您有用:
前提條件:
client.p12
(或使用原始名稱,但為清楚起見,我將使用較短的私鑰)。 client = Google::APIClient.new(
:application_name => "CCE",
:application_version => "1.0"
)
prediction = client.discovered_api('prediction', 'v1.5')
key = Google::APIClient::KeyUtils.load_from_pkcs12('client.p12', 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/prediction',
:issuer => '..put here your developer email address from Google API Console..',
:signing_key => key,
)
client.authorization.fetch_access_token!
# Now you can make the API calls
result = client.execute(...
值得注意的是, client.discovered_api
調用似乎需要版本號。 否則可能會引發異常“ NotFound”。
密碼短語實際上是字符串' notasecret '!
另一件事:在API調用中,請確保您調用了正確的方法-對於托管模型,我相信您可以調用的唯一方法是:api_method => prediction.hostedmodels.predict
或類似的方法。 我還沒有使用托管模型。 (有關詳細信息,請參閱API文檔)
client.execute
調用返回的result
可能有趣的字段是:
result.status
result.data['error']['errors'].map{|e| e['message']} # if they exist
JSON.parse(result.body)
如果您檢查它們,它們可能會極大地幫助您調試任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.