2012-04-19 94 views
1

我試圖執行使用到谷歌日曆API的捲曲請求,上面寫着:插入事件,谷歌日曆使用PHP

POST https://www.googleapis.com/calendar/v3/calendars/{name_of_my_calendar}/events?sendNotifications=true&pp=1&key={YOUR_API_KEY} 

Content-Type: application/json 
Authorization: OAuth 1/SuypHO0rNsURWvMXQ559Mfm9Vbd4zWvVQ8UIR76nlJ0 
X-JavaScript-User-Agent: Google APIs Explorer 

{ 
"start": { 
    "dateTime": "2012-06-03T10:00:00.000-07:00" 
}, 
"end": { 
    "dateTime": "2012-06-03T10:20:00.000-07:00" 
}, 
"summary": "my_summary", 
"description": "my_description" 
} 

我應該怎麼做,在PHP?我想知道我應該發送什麼參數以及我應該使用哪些常量。目前,我正在做的:

 $url = "https://www.googleapis.com/calendar/v3/calendars/".urlencode('{name_of_my_calendar}')."/events?sendNotifications=true&pp=1&key={my_api_key}"; 

     $post_data = array( 
      "start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"), 
      "end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"), 
      "summary" => "my_summary", 
      "description" => "my_description" 
     ); 

     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_POST, 1); 
     // adding the post variables to the request 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 

     $output = curl_exec($ch); 

     curl_close($ch); 

但響應:

{ 
    error: { 
     errors: [ 
     { 
      domain: "global", 
      reason: "required", 
      message: "Login Required", 
      locationType: "header", 
      location: "Authorization" 
     } 
     ], 
     code: 401, 
     message: "Login Required" 
    } 
} 

我應該如何格式化我的參數?

+0

您是否閱讀了https://developers.google.com/google-apps/calendar/auth? – Daan 2012-04-19 08:44:17

+0

是的,我的代碼只用於解析來自同一日曆的事件的示例。 – Gustav 2012-04-19 08:46:12

+0

嗯。不知道,我以前從未使用過此API。你可能想試試官方的PHP API包:http://code.google.com/p/google-api-php-client/希望這會有所幫助! – Daan 2012-04-19 17:45:52

回答

2

我注意到這個問題在一段時間以前就被問過了,但是經過一段時間後我發現後參數問題,我認爲它可能對其他人有用。首先在 '$ post_data',我打開 '開始' 和 '結束':

$post_data = array(
    "end" => array("dateTime" => "2012-06-01T10:40:00.000-07:00"), 
    "start" => array("dateTime" => "2012-06-01T10:00:00.000-07:00"), 
    "summary" => "my_summary", 
    "description" => "my_description" 
); 

其次,我想谷歌日曆API所期望的數據是JSON,所以在curl_setopt:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); 

這對我來說非常合適,希望對其他人也有用!

+0

對我來說不行。 我嘗試了這個代碼,或者我做錯了關鍵,但我不這麼認爲。是下面的一個:「服務器應用程序的關鍵(IP鎖定)」我現在允許所有的IP。即使對我也需要授權。我可以訪問您的完整示例嗎? – AndreaBogazzi 2013-10-25 10:57:51