fazlurr
4/26/2018 - 8:23 AM

Google Contacts Sync

<?php

/** @var string Google API Host */
protected $api_host = 'https://people.googleapis.com';

/**
 * Create Person Object from Contact Data
 * 
 * @param array $contact Contact Data
 * @return array $person Google Person Object
 */
public function build_person( $contact ) {
	$person = array(
		'names' => array(
			array(
				'givenName' => $contact['names']['first_name'],
				// 'displayName'	=> $contact['names']['display_name'],
				// 'familyName'	=> $contact['names']['last_name'],
			),
		),
		'phoneNumbers' => array(
			array(
				'value' => $contact['phone'],
				'type' 	=> 'mobile',
			),
		),
		'addresses' => array(
			array(
				'type'				    => $contact['address']['type'],
				'country' 			  => $contact['address']['country'],
				'countryCode' 		=> $contact['address']['country_code'],
				'region' 			    => $contact['address']['region'],
				'city' 				    => $contact['address']['city'],
				'extendedAddress' => $contact['address']['districts'],
				'streetAddress'		=> $contact['address']['street'],
			),
		),
	);
	return $person;
}

/**
* Save Contact Data to Google Contacts
*
* @param array $contact Contact Data
*/
public function save_contact( $contact ) {
	$oauth_token = $this->get_access_token();

	// Google Person Object
	$person = $this->build_person( $contact );

	// Do request
	// $response = wp_remote_post( $this->get_google_api_url( '/v1/people:createContact' ), array(
	// 	'timeout' => 15,
	// 	'headers' => array(
	// 		'Authorization' => 'Bearer ' . $oauth_token,
	// 		'content-type' => 'application/json',
	// 	),
	// 	'body' => json_encode( $person ),
	// ) );

	$response = wp_remote_post( $this->get_request_api_url( '/v1/people:createContact' ), array(
		'timeout' => 20,
		'body' => array(
			'token' => $oauth_token,
			'person' => $person,
		),
	) );

	if ( is_wp_error( $response ) ) {
		$error_message = $response->get_error_message();
		write_log( $error_message );
	} else {
		write_log( $response['body'] );
	}
}