Google APIs Adding a contact using PeopleService

Viewed 237

I have a question about how correctly add a contact to Google Contacts using Google API. For authorization I use external Json file Generated. When I execute it , it doesn't give any mistakes but No Contact is Added to Google Contacts. What can be wrong with the code? Please find code below

Thanks

        private async Task Run()
    {

        GoogleCredential credential;

        using (Stream stream = new FileStream(@"D:\project1.json", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = GoogleCredential.FromStream(stream);
        }

        string[] scopes = new string[] {
        PeopleServiceService.Scope.Contacts,
        PeopleServiceService.Scope.ContactsReadonly,
        PeopleServiceService.Scope.ContactsOtherReadonly,
        };

        credential = credential.CreateScoped(scopes);

        BaseClientService.Initializer initializer = new BaseClientService.Initializer()
        {
            HttpClientInitializer = (IConfigurableHttpClientInitializer)credential,
            ApplicationName = "Project1",
            GZipEnabled = true,
        };

        PeopleServiceService service = new PeopleServiceService(initializer);

        Person contactToCreate = new Person();

        List<Name> names = new List<Name>();
        names.Add(new Name() { GivenName = "Alex", FamilyName = "Breen", DisplayName = "Alex Breen" });
        contactToCreate.Names = names;

        List<PhoneNumber> phoneNumbers = new List<PhoneNumber>();
        phoneNumbers.Add(new PhoneNumber() { Value = "11-22-33" });
        contactToCreate.PhoneNumbers = phoneNumbers;

        List<EmailAddress> emailAddresses = new List<EmailAddress>();
        emailAddresses.Add(new EmailAddress() { Value = "AlexBreen@mail.com" });
        contactToCreate.EmailAddresses = emailAddresses;

        PeopleResource.CreateContactRequest request = new PeopleResource.CreateContactRequest(service, contactToCreate);

        Person createdContact = request.Execute();

        Console.WriteLine(request);

    }

Results

Metrics

2 Answers

You need to go though your service object.

    var request = service.People.CreateContact(new Person()
    {
    Names = new List<Name>() { new Name() { DisplayName = "test"}}

    // Fill in the rest of the person object here.

    });

    var response = request.Execute

Make sure you are checking google contacts from the same user you are authenticating your application from.

The response should be returning the new user.

all contacts for a user

You can also test it by doing. This will give you a list of the users inserted for the user you have authorized.

var results = service.People.Connections.List("people/me").Execute();

who is the current user

var results = service.People.Get("people/me").Execute();

var results = service.People.Connections.List("people/me").Execute();

service accounts

A service account is not you. Think of a service account more as a dummy user it has its own Google contacts account. When you insert into it you are inserting into the account owned by the service account.

If you have google workspace you can set up domain wide deligation to the service account and then delegate to users on the domain and add contacts to their google contacts within the domain.

You can not use a service account to write to a standard google gmail user's google contacts. For that you would need to use Oauth2 and authorize the user to access their google contacts.

Based on the comments on the previous answer:

  • You are inserting contacts to a service account

To use your own account you have to create an OAuth client ID and then use the credentials.json to authorise on the code.

There is no C# sample on the People API samples but you can check on how to use this credentials based on the .NET quickstart for Drive API but without using Drive API scopes and code.

Basically using this part of the code:

UserCredential credential;

using(var stream =
  new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
  // The file token.json stores the user's access and refresh tokens, and is created
  // automatically when the authorization flow completes for the first time.
  string credPath = "token.json";
  credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    GoogleClientSecrets.Load(stream).Secrets,
    Scopes,
    "user",
    CancellationToken.None,
    new FileDataStore(credPath, true)).Result;
  Console.WriteLine("Credential file saved to: " + credPath);
}
Related