使用CURL接收数据,然后将数据发送到外部Webhook

时间:2019-09-23 19:00:33

标签: php json curl webhooks

所以我试图从一个Webhook接收JSON数据,使用PHP过滤某些条件,然后根据这些条件将数据发送到外部Webhook地址。

例如,我在服务器上创建了一个名为“ webhook.php”的php文件:

$dataReceive = file_get_contents("php://input");
$dataEncode = json_encode($dataReceive, true);
print_r($dataEncode);

$curl = curl_init();
$opts = array (
 CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
 CURLOPT_RETURNTRANSFER => TRUE,
 CURLOPT_CUSTOMREQUEST => 'POST',
 CURLOPT_POST => 1,
 CURLOPT_POSTFIELDS => $dataEncode,
 CURLOPT_HTTPHEADER => array (
    'Content-type: application/json'
)
);
curl_setopt($curl, $opts);
$results = curl_exec($curl);
echo $results;
curl_close($curl);

“ php:// input”可以是原样,也可以尝试将其替换为webhook.php文件的URL,以防万一。我可以使用Postman测试Webhook,返回200 OK,但是数据永远不会发送到我的外部Webhook(https://hooks.zapier.com/hooks/catch/)。

我已经编写了条件PHP代码;我只想确保我可以先正确发送和接收此数据。任何指导深表感谢!

1 个答案:

答案 0 :(得分:1)

问题出在curl_setopt上。您需要为该方法curl_setopt(资源$ ch,int $ option,混合$ value)传递三个参数。您可以按照

进行设置
$curl = curl_init();
$opts = array (
 CURLOPT_URL => 'https://hooks.zapier.com/hooks/catch/',
 CURLOPT_RETURNTRANSFER => TRUE,
 CURLOPT_CUSTOMREQUEST => 'POST',
 CURLOPT_POST => 1,
 CURLOPT_POSTFIELDS => $dataEncode,
 CURLOPT_HTTPHEADER => array (
    'Content-type: application/json'
)
);
foreach ($opts as $key => $value) {
    curl_setopt($curl, $key, $value);
}
$results = curl_exec($curl);
echo $results;
curl_close($curl);

或者您可以像这样单独设置它们

curl_setopt($curl, CURLOPT_URL, 'https://hooks.zapier.com/hooks/catch/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
.....