Create Google Contact

740 views Asked by At

My goal is to register, on a Google Account, all phone numbers that I save on my php based CRM. I've checked on Google APIs documentation but I've not understood which API I have to use. I can use PHP or JS to develop this function. The only information I found is in these two pages :

The first is a REST call and this is good ... but I'm not understanding how to create this call. The second has a possibility to create contact just with CardDAV.

Can someone help me on this or is there somewhere a guide step by step about how to create a Google Contact using PHP or JS?

1

There are 1 answers

0
Bryan Monterrosa On

Google Workspace People API can be used to create a contact which will be displayed at contacts.google.com, you can follow these steps to set up Google Cloud Project and perform the API call in PHP:

1. Create a Google Cloud Project and enable the People API:

enter image description here

2. Create a Consent screen:

  • Go to "API's & Services" > "OAuth consent screen" and create one using only the required information.

3. Download a credentials.json file.

  • Go to "AP's & Services" > "Credentials". Click "Select credentials" > "OAuth client ID".
  • Select "Desktop app", give it a name and click "Create". Click Download and save it in your working directory as credentials.json.

4. Set up the project.

composer require google/apiclient:^2.12.1

5. The code:

  • Use this code to create an API call to create a Google Contact using the authorized account.
  • This is a CLI project, you'll need to open a URL in the browser, get the code from the resulting URL and then use it in the terminal.
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

use Google\Client;
use Google\Service\PeopleService;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('People API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/contacts');
    $client->setAuthConfig('PATH/TO/credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // 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.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new PeopleService($client);

//Create a new person object.
$person = new Google\Service\PeopleService\Person([
    'names' => [
        [
            'givenName' => 'foobar',
            'familyName' => 'barfoo'
        ]
    ],
    'emailAddresses' => [
        [
            'value' => '[email protected]'
        ],
        [
            'value' => '[email protected]'
        ]
    ],
    'phoneNumbers' => [
        [
            'value' => '0777677305',
            'type' => 'home'
        ],
        [
            'value' => '0777677305',
            'type' => 'mobile'
        ],
    ]
]);

//Perform the API call.
$result = $service->people->createContact($person);

enter image description here

  • Use this modification to create multiple contacts using batchRequests:
// Get the API client and construct the service object.
$client = getClient();
$service = new PeopleService($client);

// Create a batch request object and the array that will contain the contacts:
$batchRequest = new Google\Service\PeopleService\BatchCreateContactsRequest;
$contacts = array();

// Create contacts and add them to the array:
for ($x = 0; $x < 2; $x++) {
    $person = [
        'contactPerson' => [
            'names' => [
                [
                    'givenName' => 'foobar'.$x,
                    'familyName' => 'barfoo'.$x
                ]
            ],
            'emailAddresses' => [
                [
                    'value' => '[email protected]'
                ],
                [
                    'value' => '[email protected]'
                ]
            ],
            'phoneNumbers' => [
                [
                    'value' => '0777677305',
                    'type' => 'home'
                ],
                [
                    'value' => '0777677305',
                    'type' => 'mobile'
                ],
            ]
        ]
    ];
    array_push($contacts, $person);
}

// Add the array to the request.
$batchRequest->setContacts($contacts);
// Use readMask to specify the values that the API response will return. 
$batchRequest->setReadMask("names");
// Perform the batchRequest
$results = $service->people->batchCreateContacts($batchRequest);

// Print the response:
if (count($results->getCreatedPeople()) == 0) {
    print "No contacts created.\n";
} else {
    print "People:\n";
    foreach ($results->getCreatedPeople() as $person) {
        if (count($person->getPerson()->getNames()) == 0) {
            print "No names found for this contact\n";
        } else {
            $names = $person->getPerson()->getNames();
            $name = $names[0];
            printf("%s\n", $name->getDisplayName());
        }
    }
}

enter image description here


References: