如何使用服務帳戶為Google Calendar API設定golang客戶端?這是許多開發者在使用Google Calendar API時經常遇到的問題。在這篇文章中,php小編香蕉將為你詳細介紹如何使用服務帳戶來配置golang客戶端,以便你能夠順利地與Google Calendar API進行互動。無論你是初學者還是有一定經驗的開發者,本文都將為你提供清晰的指導,幫助你快速上手這個過程。讓我們一起來探索吧!
我看過很多有關使用者的 google api 用戶端的文檔,但有關使用服務帳戶的文檔卻很少。這並不代表用戶,我只是想讓客戶端使用客戶端 id 和客戶端密鑰來使用日曆 api,這將透過環境變數為我提供(我不想從一個文件)。
這是我到目前為止所擁有的:
package main import ( "context" clientcredentials "golang.org/x/oauth2/clientcredentials" google "golang.org/x/oauth2/google" calendar "google.golang.org/api/calendar/v3" apioption "google.golang.org/api/option" ) func main() { config := &clientcredentials.config{ clientid: "<my_id>", clientsecret: "-----begin private key-----\n...", tokenurl: google.endpoint.tokenurl, } ctx := context.background() client := config.client(ctx) service, _ := calendar.newservice(ctx, apioption.withhttpclient(client)) calendarlist, err := service.calendarlist.list().do() }
但我收到以下錯誤:
Get "https://www.googleapis.com/calendar/v3/users/me/calendarList?alt=json&prettyPrint=false": oauth2: cannot fetch token: 400 Bad Request Response: { "error": "unsupported_grant_type", "error_description": "Invalid grant_type: client_credentials" }
非常感謝這裡的任何幫助!我是 golang、oauth2 和 google api 的新手 :)
@tanaike 的回答讓我走上了正軌。這就是我最終使用的:
package main import ( "context" "encoding/json" "fmt" googleoauth "golang.org/x/oauth2/google" calendar "google.golang.org/api/calendar/v3" apioption "google.golang.org/api/option" ) var service *calendar.service // note that some of the fields are optional: type googleauthconfig struct { type string `json:"type"` projectid string `json:"project_id,omitempty"` clientemail string `json:"client_email"` clientid string `json:"client_id,omitempty"` clientsecret string `json:"private_key"` clientsecretid string `json:"private_key_id,omitempty"` authurl string `json:"auth_uri,omitempty"` tokenurl string `json:"token_uri,omitempty"` authprovidercerturl string `json:"auth_provider_x509_cert_url,omitempty"` clientcerturl string `json:"client_x509_cert_url,omitempty"` } func main() { authconfig := googleauthconfig{ type: "service_account", clientemail: "<a href="https://www.php.cn/link/89fee0513b6668e555959f5dc23238e9" class="__cf_email__" data-cfemail="82e3e1e1edf7ecf6b3b0b1c2f2f0ede8e7e1f6afb6b7b4acebe3eface5f1e7f0f4ebe1e7e3e1e1edf7ecf6ace1edef">[email protected]</a>", clientid: "1234", clientsecret: "-----begin private key-----\n...\n-----end private key-----\n", authurl: googleoauth.endpoint.authurl, tokenurl: googleoauth.endpoint.tokenurl, } authconfigjson, err := json.marshal(authconfig) ctx := context.background() service, err = calendar.newservice(ctx, apioption.withcredentialsjson([]byte(authconfigjson))) }
請注意,我不必配置網域範圍的委派或模擬使用者;將服務帳戶新增至日曆後,效果很好。
將帳戶電子郵件新增至行事曆後,服務帳戶仍需要接受行事曆邀請。這可以透過以下方式完成:
entry := calendar.CalendarListEntry{Id: calendarID} service.CalendarList.Insert(&entry).Do()
以上是如何使用服務帳戶為 Google Calendar API 設定 golang 用戶端的詳細內容。更多資訊請關注PHP中文網其他相關文章!