如何 PHP cURL 到 SurveyMonkey API?

How to PHP cURL to SurveyMonkey API?

我正在尝试使用 PHP cURL 从 SurveyMonkey 的 API 检索一些数据,但我一直收到 500 错误。

这是我的代码:

  $requestHeaders = array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $accessToken,
  );

  $baseUrl = 'https://api.surveymonkey.net';
  $endpoint = '/v2/surveys/get_survey_list?api_key=XXXXXXXXXXXXXX';

  $fields = array(
    'fields' => array(
      'title','analysis_url','date_created','date_modified'
    )
  );

  $fieldsString = json_encode($fields);

  $ch  = curl_init();
  curl_setopt($ch, CURLOPT_URL, $baseUrl . $endpoint);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);

  $result = curl_exec($ch);

  curl_close($ch);

我得到的回复是

{
    "status": 500,
    "request_id": "e0c10adf-ae8f-467d-83af-151e8e229618",
    "error": {
        "message": "Server busy, please try again later."
    }
}

这在命令行上完美运行:

curl -H 'Authorization:bearer XXXXX' 
     -H 'Content-Type: application/json' https://api.surveymonkey.net/v2/surveys/get_survey_list/?api_key=XXXXXXXX 
--data-binary '{"fields":["title","analysis_url","date_created","date_modified"]}'

谢谢!

你很接近,但有几个小错误。

首先,虽然您正确指定了 Content-Type (application/json),但您没有指定 Content-Length

$requestHeaders 进行此更改并将其移动到 下方 创建 $fieldsString:

$requestHeaders = array(
     'Content-Type: application/json',
     'Authorization: Bearer ' . $_GET['code'],
     'Content-Length: ' . strlen($fieldsString)
);

其次,您已将 CURLOPT_POST 设置为 true。这将强制 CURL 将您的请求视为 形式 POST,其内容类型为 application/x-www-form-urlencoded。这会产生问题,因为 SurveyMonkey 需要内容类型 application/json.

删除这个:

curl_setopt($ch, CURLOPT_POST, true);

并将其替换为:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");