2017-11-19 18 views
0

PHP를 사용하여 Google 연락처로 새 연락처 항목을 푸시하고 싶습니다.PHP를 사용하여 Google 사람들 api에 새 연락처 추가

아래는 내 index.php 코드입니다.

require_once 'vendor/autoload.php'; 
session_start(); 

$client = new Google_Client(); 


$client->setClientId('519334414648- 
f2jiml3iuuj87mjn1ofc9kbqmlsn7iqb.apps.googleusercontent.com'); 
$client->setClientSecret('0x9LpW7Qr37x89YFRtmgq6oH'); 
$client->setRedirectUri('http://example.com/demo/contacts/redirect.php'); 

$client->addScope('profile'); 
$client->addScope('https://www.googleapis.com/auth/contacts.readonly'); 

if (isset($_GET['oauth'])) { 
// Start auth flow by redirecting to Google's auth server 
$auth_url = $client->createAuthUrl(); 
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); 
} 

else if (isset($_GET['code'])) { 
// Receive auth code from Google, exchange it for an access token, and 
// redirect to your base URL 
$client->authenticate($_GET['code']); 
$_SESSION['access_token'] = $client->getAccessToken(); 
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/demo/contacts'; 
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
} 

else if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
// You have an access token; use it to call the People API 
$client->setAccessToken($_SESSION['access_token']); 
$client->setAccessType('online'); 
// TODO: Use service object to request People data 

$client->addScope(Google_Service_PeopleService::CONTACTS); 
$service = new Google_Service_PeopleService($client); 

$person = new Google_Service_PeopleService_Person(); 
$person->setPhoneNumbers('1234512345'); 

$name = new Google_Service_PeopleService_Name(); 
$name->setDisplayName('test user'); 
$person->setNames($name); 
$exe = $service->people->createContact($person); 

} 

else { 
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/demo/contacts?oauth'; 
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
} 

아래 코드를 실행하면이 오류가 발생합니다. 캐치되지 않는 예외 메시지 'Google_Service_Exception' '{ "오류": { "코드": 401, "메시지". "요청이 유효 인증 자격 증명을 가지고 예상 OAuth는이 액세스 토큰, 로그인 쿠키 또는 기타 유효한 인증 자격 증명 수 있습니다. 내 코드가 맞다면 어떤 일이 말해?하지 연락처 또는 사람들 API에 연락처를 밀어의 coorect 방법을 제안하십시오.

답변

1

당신이 documentation을 참조 할 수 있습니다.

전체 단계는 상기에 정교했다 설명서를 참조하면 좋은 결과를 얻을 수 있습니다.

Here이 코드는

<?php 
require_once __DIR__ . '/vendor/autoload.php'; 


define('APPLICATION_NAME', 'People API PHP Quickstart'); 
define('CREDENTIALS_PATH', '~/.credentials/people.googleapis.com-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/people.googleapis.com-php-quickstart.json 
define('SCOPES', implode(' ', array(
    Google_Service_PeopleService::CONTACTS_READONLY) 
)); 

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

/** 
* Returns an authorized API client. 
* @return Google_Client the authorized client object 
*/ 
function getClient() { 
    $client = new Google_Client(); 
    $client->setApplicationName(APPLICATION_NAME); 
    $client->setScopes(SCOPES); 
    $client->setAuthConfig(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
    $accessToken = json_decode(file_get_contents($credentialsPath), true); 
    } 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); 

    // Store the credentials to disk. 
    if(!file_exists(dirname($credentialsPath))) { 
     mkdir(dirname($credentialsPath), 0700, true); 
    } 
    file_put_contents($credentialsPath, json_encode($accessToken)); 
    printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
    } 
    return $client; 
} 

/** 
* Expands the home directory alias '~' to the full path. 
* @param string $path the path to expand. 
* @return string the expanded path. 
*/ 
function expandHomeDirectory($path) { 
    $homeDirectory = getenv('HOME'); 
    if (empty($homeDirectory)) { 
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); 
    } 
    return str_replace('~', realpath($homeDirectory), $path); 
} 

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

// Print the names for up to 10 connections. 
$optParams = array(
    'pageSize' => 10, 
    'personFields' => 'names,emailAddresses', 
); 
$results = $service->people_connections->listPeopleConnections('people/me', $optParams); 

if (count($results->getConnections()) == 0) { 
    print "No connections found.\n"; 
} else { 
    print "People:\n"; 
    foreach ($results->getConnections() as $person) { 
    if (count($person->getNames()) == 0) { 
     print "No names found for this connection\n"; 
    } else { 
     $names = $person->getNames(); 
     $name = $names[0]; 
     printf("%s\n", $name->getDisplayName()); 
    } 
    } 
} 

연락처를 만들려면,이 Method: people.createContact을 사용할 수 있습니다, 제공되었다.

새 연락처를 만들고 해당 연락처의 사람 리소스를 반환하십시오.

OAuth 2.0에 대한 추가 정보는 here을 참조하십시오.

또한이 문제가 해당 문제의 적용 가능한 경우 오류의 해결 방법에 대해 SO post을 확인할 수 있습니다.