如何将原始请求转换为php post curl请求

时间:2020-04-10 04:55:21

标签: php api curl

我正在尝试将扩展API用于我的PHP网站。在外展活动中,这是他们提到的要求:

POST https://api.outreach.io/api/v2/prospects

{ “数据”: { “属性”:{ “ firstName”:“ Test_3”, “ lastName”:“ API” }, “ type”:“前景” } }

在PHP中,我将其转换为以下代码,但给出错误“ Bad Request”。请帮助我我在做什么错,以下代码中的accessToken具有正确的值。

$urlCreateAccount = "https://api.outreach.io/api/v2/prospects";
$attributes = array("firstName"=> "Sally","lastName"=> "Biu");
$paramsCreateAccount = "type=prospect$attributes=".$attributes;
$headr[] = "Authorization:bearer $accessToken";

$curl = curl_init($urlCreateAccount);
curl_setopt($curl, CURLOPT_HTTPHEADER,$headr);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $paramsCreateAccount);

$jsonResponseCreateAccount = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

2 个答案:

答案 0 :(得分:0)

我真的可以说代码有什么问题。但是,请尝试一次此代码。我已获取示例JSON数据扩展api文档

$jsonData = "{
  "data": {
    "type": "prospect",
    "attributes": {
      "emails": ["sally.smith@acme.example.com"],
      "firstName": "Sally",
      "title": "CEO"
    },
    "relationships": {
      "account": {
        "data": {
          "type": "account",
          "id": 1
        }
      }
    }
  }
}";

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.outreach.io/api/v2/prospects",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>$jsonData,
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/vnd.api+json",
    "Authorization: Bearer <Access Token>",
    "Content-Type: text/plain"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

希望您会得到结果。您也可以先使用邮递员测试api,然后从那里取出所需语言的代码

答案 1 :(得分:0)

它需要JSON,因此您需要POST JSON。像这样...

$data = json_encode($data);
$ch = curl_init($host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $access,'Content-Type: application/json','Content-Length: ' . strlen($data)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);