2014-01-06 3 views
1

Когда я пытаюсь добавить контакт в GMAIL это всегда возвращают 40:я не могу добавить контакт в Gmail с помощью PHP

Это ошибка. В вашем запросе была ошибка. Это все, что мы знаем.

Как я могу решить эту проблему?

Я попытался следующий код

$sClientId = 'ClientID'; 
    $sClientSecret = 'ClientSecret'; 
    $sCallback = 'http://humaclab.com/development/contacts/index.php/home'; // callback url, don't forget to change it to your! 
    $iMaxResults = 500; // max results 
    $sStep = 'auth'; // current step 
    $argarray = array(); 

    // include GmailOath library https://code.google.com/p/rspsms/source/browse/trunk/system/plugins/GmailContacts/GmailOath.php?r=11 
    require_once "GmailOath.php"; 

    session_start(); 

    // prepare new instances of GmailOath and GmailGetContacts 
    $oAuth = new GmailOath($sClientId, $sClientSecret, $argarray, false, $sCallback); 
    $oGetContacts = new GmailGetContacts(); 


    if ($_GET && $_GET['oauth_token']) 
    { 
     $sStep = 'fetch_contacts'; // fetch contacts step 

     // decode request token and secret 
     $sDecodedToken = $oAuth->rfc3986_decode($_GET['oauth_token']); 
     $sDecodedTokenSecret = $oAuth->rfc3986_decode($_SESSION['oauth_token_secret']); 

     // get 'oauth_verifier' 
     $oAuthVerifier = $oAuth->rfc3986_decode($_GET['oauth_verifier']); 

     // prepare access token, decode it, and obtain contact list 
     $oAccessToken = $oGetContacts->get_access_token($oAuth, $sDecodedToken, $sDecodedTokenSecret, $oAuthVerifier, false, true, true); 
     $sAccessToken = $oAuth->rfc3986_decode($oAccessToken['oauth_token']); 
     $sAccessTokenSecret = $oAuth->rfc3986_decode($oAccessToken['oauth_token_secret']); 

     $url = 'https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$sAccessToken; 

     $doc = new DOMDocument(); 
     $doc->formatOutput = true; 

     $entry = $doc->createElement('atom:entry'); 
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom'); 
     $entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005'); 
     $doc->appendChild($entry); 

     $cat = $doc->createElement('atom:category'); 
     $cat->setAttribute('scheme', 'http://schemas.google.com/g/2005#kind'); 
     $cat->setAttribute('term', 'http://schemas.google.com/contact/2008#contact'); 
     $entry->appendChild($cat); 

     // add name element 
     $name = $doc->createElement('gd:name'); 
     $entry->appendChild($name); 
     $givenName = $doc->createElement('gd:givenName', 'First'); 
     $familyName = $doc->createElement('gd:familyName', 'Last'); 
     $fullName = $doc->createElement('gd:fullName', 'First Last'); 
     $name->appendChild($givenName); 
     $name->appendChild($familyName); 
     $name->appendChild($fullName); 

     $content = $doc->createElement('atom:content', 'Notes'); 
     $content->setAttribute('type', 'text'); 
     $entry->appendChild($content); 

     // add email element 
     $email = $doc->createElement('gd:email'); 
     $entry->appendChild($email); 
     $email->setAttribute('address', '[email protected]'); 
     //$email->setAttribute('displayName', $_POST['fname']); 
     //$email->setAttribute('primary', 'true'); 
     $email->setAttribute('rel', 'http://schemas.google.com/g/2005#work'); 


     //insert Address 
     $address = $doc->createElement('gd:structuredPostalAddress'); 
     $address->setAttribute('primary', 'true'); 
     $address->setAttribute('rel', 'http://schemas.google.com/g/2005#work'); 
     $entry->appendChild($address); 
     $postal = $doc->createElement('gd:postcode', '1212'); 
     $country = $doc->createElement('gd:country', 'BD'); 
     $fulladd = $doc->createElement('gd:formattedAddress', '1212, BD'); 
     $address->appendChild($postal); 
     $address->appendChild($country); 
     $address->appendChild($fulladd); 

     $contact_detail = $doc->saveXML(); 


     $curl = curl_init(); 
     curl_setopt($curl, CURLOPT_URL, $url); 
     curl_setopt($curl, CURLOPT_POST, 5); 
     curl_setopt($curl, CURLOPT_POSTFIELDS, $contact_detail); 
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); 
     curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); 

     $curlheader[0] = "Content-Type: application/atom+xml"; 
     $curlheader[2] = "Content-length:" . strlen($contact_detail); 
     $curlheader[1] = "Content-Transfer-Encoding: binary"; 
     curl_setopt($curl, CURLOPT_HTTPHEADER, $curlheader); 

     $xmlresponse = curl_exec($curl); 

     print_r($xmlresponse); 
    } 

    else 
    { 
     // prepare access token and set it into session 
     $oRequestToken = $oGetContacts->get_request_token($oAuth, false, true, true); 
     $_SESSION['oauth_token'] = $oRequestToken['oauth_token']; 
     $_SESSION['oauth_token_secret'] = $oRequestToken['oauth_token_secret']; 
     $login_url = 'https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token='.$oAuth->rfc3986_decode($oRequestToken['oauth_token']);   
     echo '<a href="'.$login_url.'">login</a>'; 
    } 
+3

Если это ваш реальный ClientId и clientSecret, вероятно, вы должны удалить это и повторно пост без этих деталей (редактирование сохранит их в истории вопроса). – bcmcfc

ответ

0

я не знаю библиотеку GmailOath - это кажется странным, что клиентские секреты и т.д., которые хранятся в сессии. Моя рекомендация по доступу к API Google с помощью OAuth заключается в использовании клиентских библиотек PHP, предоставленных Google: https://code.google.com/p/google-api-php-client/

Ссылка, приведенная выше, содержит пример запуска аутентификации - затем использует эту аутентификацию для вызова API для API Google+ , В вашем случае удалите эту строку и вместо этого сохраните значение, возвращаемое $client->getAccessToken(), и добавьте заголовок авторизации в запрос HTTPS (вместо того, чтобы помещать строку запроса). Ниже есть некоторые дискуссии о том, как это сделать: How to include Authorization header in cURL POST HTTP Request in PHP?

Смежные вопросы