我想使用 PHP 将新的联系人条目推送到谷歌联系人。
下面是我的 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' 带有消息 '{ "error": { "code": 401, "message": "Request has invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. 任何 1 都可以告诉我如果我的代码是正确的?如果不是,请建议将联系人推送到联系人或人员 API 的正确方式。