php - 如何使用 PHP 从 Google 获取完整的联系信息?

标签 php api oauth

我正在使用 Oauth 2.0 导入联系人,但我只获得了电子邮件地址。有什么方法可以获取其他字段?另外,如何使用 Google API 创建联系人。 只需要使用 PHP。

这是我的代码:

//setting parameters
$authcode= $_GET["code"];
$clientid='xxxxxxx';
$clientsecret='secret';
$redirecturi='validate.php';
$fields=array(
 'code'=>  urlencode($authcode),
 'client_id'=>  urlencode($clientid),
 'client_secret'=>  urlencode($clientsecret),
 'redirect_uri'=>  urlencode($redirecturi),
 'grant_type'=>  urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response=  json_decode($result);
$accesstoken= $response->access_token;
//passing accesstoken to obtain contact details
$xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default     /full?oauth_token='.$accesstoken.'&max-results=5');
//reading xml using SimpleXML
 $xml=  new SimpleXMLElement($xmlresponse);
 $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
 $result = $xml->xpath('//gd:email');
 foreach ($result as $title) {
  $addrss=$title->attributes()->address;
  echo $addrss."<br><br>";

最佳答案

好吧,如果您只是解析 gd:email 的 XML,那么您肯定只会得到电子邮件地址。查看Contact kind documentation了解您还可以解析的元素的概述。

要创建联系人,您只需向同一端点发出一个 POST 请求,其中包含正文中的联系人详细信息:

https://www.google.com/m8/feeds/contacts/default/full

有关详细联系信息格式的详细文档,请参阅 API documentation .

关于php - 如何使用 PHP 从 Google 获取完整的联系信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920525/

相关文章:

javascript - 从 javascript 数组获取 php 的日期时间

php - 以编程方式设置运输方式 Woocommerce

java - IBM Domino 上是否有 Java API 可以加密/解密服务器上的 Notes 项目?

java - Google 日历 API 和 OAuth 问题

php - 从 PHP 查询表(配置文件?)

php - 简化 PHP DOM XML 解析——怎么做?

api - 如何在Flutter中使用Future和Uri.Https构造函数进行API调用

c++ - 除了 createfile 和 openfile 之外,还有任何用于获取文件句柄的 Windows API?

swift - OAuthSwift 的自定义 header

javascript - 浏览器中来自 Javascript 的 REST API 身份验证