使用php将事件插入Google日历

时间:2012-04-19 08:33:16

标签: php authentication curl google-calendar-api http-request

我正在尝试使用their guide对Google日历api执行cURL请求,其中说:

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"
    }
}

我应该如何格式化参数?

1 个答案:

答案 0 :(得分: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"
);

其次,我认为Google Calendar API期望数据为json,所以在curl_setopt中:

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

这对我来说非常有用,希望它对其他人也有用!