googleworkspace / go-samples Goto Github PK
View Code? Open in Web Editor NEWGo samples for Google Workspace APIs
License: Apache License 2.0
Go samples for Google Workspace APIs
License: Apache License 2.0
The Go documentation is incomplete and need help urgently on the step to create new credentials.json which it has additional missing key but I tried to generate a private JSON in Google API console is confusing that I'm stuck with no proper guidance.
https://developers.google.com/sheets/api/quickstart/go?authuser=2
Someone has changed the credential requirements without inform anyone and create all the mess.
Go code for Sheetv4 is running on web server.
hi there,
from this demo: https://github.com/googleworkspace/go-samples/blob/master/gmail/quickstart/quickstart.go
I got an error with message:
2023/03/29 14:40:18 Unable to retrieve token from web: oauth2: cannot fetch token: 400 Bad Request
Response: {
"error": "invalid_grant",
"error_description": "Malformed auth code."
}
After i copy the url redirect from browser and then enter in command line, It shows the above error
The Apps Script API provides a scripts.run method that remotely executes a specified Apps Script function.
The Apps Script API is either not working, or not properly documented enough for me to be able to use within a reasonable amount of time and effort.
function setProp() { var props = PropertiesService.getScriptProperties().setProperty('testKey', 'testValue'); } function clearProp() { PropertiesService.getScriptProperties().deleteAllProperties(); } function testProp() { Logger.log('Props: ' + JSON.stringify(PropertiesService.getScriptProperties().getProperties(), null, 5)); }
Props: { "testKey": "testValue" }
Props: {}
403 cache-control: private content-encoding: gzip content-length: 128 content-type: application/json; charset=UTF-8 date: Sun, 10 Mar 2019 01:58:03 GMT server: ESF vary: Origin, X-Origin, Referer { "error": { "code": 403, "message": "The caller does not have permission", "status": "PERMISSION_DENIED" } }
I have tried the following:
In each case, I get the same 403 error.
None applicable
From the example provided in - https://developers.google.com/sheets/api/quickstart/go#run_the_sample , the expected behaviour upon running the app first time is:
In your browser, go to http://localhost:8000.
The first time you run the sample, it prompts you to authorize access:
If you're not already signed in to your Google Account, you're prompted to sign in. If you're signed in to multiple accounts, select one account to use for authorization.
Click Accept.
Copy the code from the browser, paste it into the command-line prompt, and press Enter.
Authorization information is stored in the file system, so the next time you run the sample code, you aren't prompted for authorization.
nothing running in localhost
curl http://localhost:8000 7 ↵ ryemane@robel-cs
curl: (7) Failed to connect to localhost port 8000 after 4 ms: Connection refused
and when following the link that the app suggest to visit i.e.
go run quickstart2.go 1 ↵ ryemane@robel-cs
Go to the following link in your browser then type the authorization code:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=372148273502-3kj1acfo674on8q2hodqdbbnv67vvn2r.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets.readonly&state=state-token
I get asked that the app wants to access my google account but when I allow it, it fails to continue and site is unrechable
go version
): go version go1.19.5 darwin/arm64go vet ./...
produces no error.
go vet
produces errors.
Run code in https://developers.google.com/gmail/api/quickstart/go success
I got error:
Go to the following link in your browser then type the authorization code:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=547117123835-tkhmlkohvj3rncvahj0h1o59vl4kgjpk.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly&state=state-token
2019/10/09 18:19:30 Unable to read authorization code: EOF
go get -u google.golang.org/api/docs/v1
go get -u golang.org/x/oauth2/google
go version
)It should return the downloadable link
Its not returning the downloadable link
go version
)Data in G Suite Admin API should return JSON response
This condition is also handled in https://github.com/gsuitedevs/go-samples/blob/master/drive/activity-v2/quickstart/quickstart.go line 213
I'm unable to replicate the scenario, can you please tell me a solution.
go version
) : 1.12.9I'm trying to use this example:
https://developers.google.com/admin-sdk/directory/v1/quickstart/go
I expect to see a list of users names and email addresses from my domain
I get an error from this line:
https://github.com/gsuitedevs/go-samples/blob/master/admin_sdk/directory/quickstart.go#L104
Unable to retrieve users in domain: googleapi: Error 400: Bad Request, badRequest
I am using ... .Customer("<my-domain>") ...
, there are several users in the org that have email addresses in that domain.
quickstart.go runs as expected
quickstart.go:11:9: no required module provides package golang.org/x/net/context: go.mod file not found in current directory or any parent directory; see 'go help modules'
quickstart.go:12:9: no required module provides package golang.org/x/oauth2: go.mod file not found in current directory or any parent directory; see 'go help modules'
quickstart.go:13:9: no required module provides package golang.org/x/oauth2/google: go.mod file not found in current directory or any parent directory; see 'go help modules'
quickstart.go:14:9: no required module provides package google.golang.org/api/drive/v3: go.mod file not found in current directory or any parent directory; see 'go help modules'
success send
googleapi: Error 400: Recipient address required, invalidArgument
when I don't set message.Raw, response is '... raw required, invalidArgument'
my code :
srv, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
var message gmail.Message
var gmailheader []*gmail.MessagePartHeader
to := gmail.MessagePartHeader{}
to.Name = "To"
to.Value = "***@***"
gmailheader = append(gmailheader, &to)
from := gmail.MessagePartHeader{}
from.Name = "From"
from.Value = "me"
gmailheader = append(gmailheader, &from)
subject := gmail.MessagePartHeader{}
subject.Name = "Subject"
subject.Value = "Testing"
gmailheader = append(gmailheader, &subject)
messagePartBody := new(gmail.MessagePartBody)
messagePart := new(gmail.MessagePart)
content := `<a href="google.com" target="_blank">google</ a>`
html := base64.StdEncoding.EncodeToString([]byte(content))
html = strings.Replace(html, "/", "_", -1)
html = strings.Replace(html, "+", "-", -1)
html = strings.Replace(html, "=", "", -1)
messagePartBody.Data = html
messagePart.MimeType = "text/html"
messagePart.Body = messagePartBody
messagePart.Headers = gmailheader
message.Payload = messagePart
bytebody,err := messagePart.MarshalJSON()
if err !=nil{
log.Fatal(err)
}
message.Raw = base64.StdEncoding.EncodeToString(bytebody)
_, err = srv.Users.Messages.Send("me", &message).Do()
if err != nil {
log.Fatalf("Unable to send. %v", err)
}
Hi!
How i can specify sheet(gid) in google spreadsheets?
e.g. url https://docs.google.com/spreadsheets/d/1{...}0/edit#gid=6{...}1
In
readRange := "Class Data!A2:E"
i can specify only cells.
First time run, unclear as to the specific behavior I am supposed to see, but I believe the error is not one that I am expected to see.
2018/10/10 08:47:50 Unable to retrieve people. googleapi: Error 400: personFields mask is required. Please specify one or more validpaths. Valid paths are documented at https://developers.google.com/people/api/rest/v1/people/get., badRequest
exit status 1
go version
)I've been following the https://developers.google.com/sheets/api/quickstart/go but I couldn't make it work. In fact, I am getting all the time this error:
2019/01/20 14:39:00 Unable to retrieve data from sheet: Get https://sheets.googleapis.com/v4/spreadsheets/[..............]?alt=json&prettyPrint=false: oauth2: cannot fetch token: 401 Unauthorized
Response: {
"error": "unauthorized_client",
"error_description": "Unauthorized"
}
I first changed the spreadsheetId and the readRange of the quickstart:
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
readRange := "Class Data!A2:E"
resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v", err)
}
if len(resp.Values) == 0 {
fmt.Println("No data found.")
} else {
fmt.Println("Name, Major:")
for _, row := range resp.Values {
// Print columns A and E, which correspond to indices 0 and 4.
fmt.Printf("%s, %s\n", row[0], row[4])
}
}
Because, since I have already implemented the Google Drive API V3, I put an id of a spreadsheet I have (and used the credentials.json of the account that created this spreadsheet)
However, I am still getting this error, any idea why?
Thanks for any help
PS: Original link: https://stackoverflow.com/questions/54280274/golang-google-spreadsheet-api-v4-unable-to-read-a-sheet
given admin access with Oauth2 scope: "https://www.googleapis.com/auth/calendar"
i should be able to see calendar event attendees even if user sets event visibility:private
i see "events" schema data, but no admin visibility to see attendees.
{ "accessRole": "freeBusyReader", "etag": "\"p32ke99md......\"", "items": [ { "end": { "dateTime": "2017-08-31T17:30:00-07:00" }, "etag": "\"30081064......\"", "htmlLink": "https://www.google.com/calendar/event?eid=MGw3aWVz.....", "iCalUID": "[email protected]", "id": "0l7iesgjgpb.......", "kind": "calendar#event", "start": { "dateTime": "2017-08-31T15:30:00-07:00" }, "status": "confirmed", "updated": "2017-08-30T00:33:59.851Z", "visibility": "private" },
don't get token
from "https://oauth2.googleapis.com/token"
Go to the following link in your browser then type the authorization code:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=851591631538-pl9nb3n05fvu8tamfbuvglf4d0l9iet1.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets.readonly&state=state-token
4/4wGMPRRuG3u8cHzDh-N6gH-QW7ZE17RJl23hkscryDjmQW7Ekcmvcxg
2020/10/05 03:31:45 Unable to retrieve token from web: %v Post "https://oauth2.googleapis.com/token": x509: certificate signed by unknown authority
Add People API Quickstart:
In Step 4: Run the sample
.
The credentials provided in the credentials.json
file is correct according to the structs. And I get the message Go to the following link in your browser then type the authorization code:
In Step 4: Run the sample
.
I run the project and get
$ go run quickstart.go
2018/11/10 23:01:12 Unable to parse client secret file to config: oauth2/google: missing redirect URL in the client_credentials.json
exit status 1
The parameter redirect_uris
is required in the code but it is optional in the GUI.
go run quickstart.go
and get2018/11/10 22:56:52 Unable to read client secret file: open credentials.json: no such file or directory
exit status 1
Authorized redirect URIs
and Authorized JavaScript origins
quickstart.go
credentials.json
go run quickstart.go
2018/11/10 23:01:12 Unable to parse client secret file to config: oauth2/google: missing redirect URL in the client_credentials.json exit status 1
less credentials.json
. The parameters existing under web
are client_id
, project_id
, auth_uri
, token_uri
, auth_provider_x509_cert_url
and client_secret
. No redirect_uris
exists.go version go1.11 darwin/amd64
)I do an example with php's language, it works until $authCode = trim(fgets(STDIN)); line and return nothing and i cannot know why it doesn't work, can you help me?
go version
)I would really appreciate some Golang snippets demonstrating manage-group-members operations, especially checking group membership, adding members to a group.
package google_groups_sync
import (
"context"
"io/ioutil"
"log"
"strings"
"time"
"github.com/dxe/adb/config"
"github.com/dxe/adb/model"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
)
func getAdminService() (*admin.Service, error) {
key, err := ioutil.ReadFile(config.SyncMailingListsConfigFile)
if err != nil {
return nil, errors.Wrap(err, "Could not read google auth key")
}
oauthConfig, err := google.JWTConfigFromJSON(key, "https://www.googleapis.com/auth/admin.directory.group")
if err != nil {
return nil, errors.Wrap(err, "Could not read JWT config from google auth key")
}
oauthConfig.Subject = config.SyncMailingListsOauthSubject
client := oauthConfig.Client(context.Background())
adminService, err := admin.New(client)
if err != nil {
return nil, errors.Wrap(err, "Could not construct admin service")
}
return adminService, nil
}
func listMembers(adminService *admin.Service, groupEmail string) ([]string, error) {
var memberEmails []string
call := adminService.Members.List(groupEmail)
err := call.Pages(context.Background(), func(members *admin.Members) error {
for _, m := range members.Members {
memberEmails = append(memberEmails, m.Email)
}
return nil
})
if err != nil {
return nil, errors.Wrapf(err, "Could not page members for group %s", groupEmail)
}
return memberEmails, nil
}
func insertMember(adminService *admin.Service, groupEmail, memberEmail string) error {
_, err := adminService.Members.Insert(groupEmail, &admin.Member{Email: memberEmail}).Do()
return errors.Wrapf(err, "Could not insert member %s into group %s ", memberEmail, groupEmail)
}
func removeMember(adminService *admin.Service, groupEmail, memberEmail string) error {
err := adminService.Members.Delete(groupEmail, memberEmail).Do()
return errors.Wrapf(err, "Could not delete member %s from group %s", memberEmail, groupEmail)
}
// something something main mumble unit tests
I started using your example. and I get this error.
2020/03/19 17:06:41 Unable to parse client secret file to config: oauth2/google: missing redirect URL in the client_credentials.json
exit status 1
Any suggestions please
go version
) : go version go1.13.7 windows/amd64Show the mail labels
go run quickstart.go
2020/08/27 13:30:46 Unable to retrieve messages: Get https://gmail.googleapis.com/gmail/v1/users/me/messages?alt=json&prettyPrint=false&q=subject%3AUpdate+Your+Account: oauth2: cannot fetch token: 401 Unauthorized
Response: {
"error": "unauthorized_client",
"error_description": "Unauthorized"
}
exit status 1
1.Created a gmail.Tried the steps in https://developers.google.com/gmail/api/quickstart/go
2.The script worked.
3.Created another gmail. Tried the same steps in https://developers.google.com/gmail/api/quickstart/go
4.Tried the script with new credentials.json.
5.Got error
2020/08/27 13:30:46 Unable to retrieve messages: Get https://gmail.googleapis.com/gmail/v1/users/me/messages?alt=json&prettyPrint=false&q=subject%3AUpdate+Your+Account: oauth2: cannot fetch token: 401 Unauthorized
Response: {
"error": "unauthorized_client",
"error_description": "Unauthorized"
}
exit status 1
6.With the credential created in step #1, script is working.
go version
) go version go1.13 darwin/amd64When running go run quickstart.go, it fails and returns: ../../../golang.org/x/oauth2/google/default.go:16:2: cannot find package "cloud.google.com/go/compute/metadata" in any of:
/usr/local/go/src/cloud.google.com/go/compute/metadata (from $GOROOT)
So then you need to run: go get -u cloud.google.com/go/compute/metadata
It would be great to have this step in the Go Quickstart Guide.
The first time you run the sample, it will prompt you to authorize access:
Browse to the provided URL in your web browser.
If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
Click the Accept button.
Copy the code you're given, paste it into the command-line prompt, and press Enter.
When I run go run quickstart.go
, the error is Unable to read client secret file: open credentials.json.
go run quickstart.go
go1.11.2
This issue provides visibility into Renovate updates and their statuses. Learn more
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
go.mod
github.com/stretchr/testify v1.7.0
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8@d3ed0bb246c8
google.golang.org/api v0.64.0
Currently all other languages have Google Sheets examples besides Go.
Failed to validate the config schema at '.github/sync-repo-settings.yaml': [
{
"instancePath": "/permissionRules/1/permission",
"schemaPath": "#/properties/permissionRules/items/properties/permission/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"pull",
"push",
"admin"
]
},
"message": "must be equal to one of the allowed values"
}
]
Schema can be found at https://github.com/googleapis/repo-automation-bots/blob/main/packages/sync-repo-settings/src/schema.json
credentials.json file
How to download credentials.json ?
Step 1: Download credentials.json, how ? I'm not familiar with Google Console Manager, and on browser link dosen't work!
go version
)Following the gmail quickstart.go guide should produce a token.json file
The instructions ask to go to http://localhost:8000 which produces a site can't be reached dialog box
BTW - the quickstart.py works as expected. There seems to be something missing from the quickstart.go file if it really does need a webserver for localhost:8000.
go version
) go version go1.19.1 linux/amd64The quickstart tutorial doesn't seem to be compatible with the require OOB migration.
https://developers.google.com/identity/protocols/oauth2/resources/oob-migration
load labels with go run quickstart
unable to retrieve labels: Get https://www.googleapis.com/gmail/v1/users/isomorphismes%20gmail.com/labels?alt=json&prettyPrint=false: oauth2: token expired and refresh token is not set
exit status 1
if
statementgo version
) 1.13.5 linux/386works fine
get fail:
$ go run quickstart.go
it works after:
use google.DefaultClient instead google.ConfigFromJSON
'''
client, err := google.DefaultClient(oauth2.NoContext,
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/spreadsheets.readonly")
if err != nil {
log.Fatal(err)
}
'''
and need: export GOOGLE_APPLICATION_CREDENTIALS=/path/to/my-token.json before go run
Go version (go version
)
go version go1.10.8 linux/amd64
OS (Mac/Linux/Windows)
Linux
Hey googlers!
Your sample code seems to be out of date. I am trying to run the code but this line gives me a problem. It seems like sheets.New()
function was deprecated. Please, update the sample with correct function
go version
) --> go1.14.4 darwin/amd64
Currently the documentation doesn't have code samples for calendar API for delete, get, patch, update the events in go.
I would like to contribute for the following sections and improve the documentation.
Thank you.
From the "View" menu, choose "Logs"
Should come out the log likes this:
[19-10-14 10:05:16:913 HKT] Hello, world!
From the "View" menu, choose "Logs"
Come out the log likes this:
No logs found. Use Logger API to add logs to your project.
1.From the "View" menu, choose "Logs"
In 100 line of quickstart.go is as below:
Source: "function helloWorld() {\n console.log('Hello, world!');}",
change to:
Source: "function helloWorld() {\n Logger.log('Hello, world!');}",
go version
)A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.