[英]POSTing cURL to Zapier Webhook
我正在尝试使用 cURL 发布到 Zapier webhook。
Zapier 的配置使得如果我像这样输入他们的 URL -- https://zapier.com/hooks/catch/n/abcd?email=foo@bar.com&guid=foobar
它会收到邮件,但是当我尝试用 cURL 做同样的事情时,它似乎没有收到。
这是我使用 cURL 发帖的代码 -->
<?php
// Initialize curl
$curl = curl_init();
// Configure curl options
$opts = array(
CURLOPT_URL => 'https://zapier.com/hooks/catch/n/abcd',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'guid='+ $_POST["guid"] + '&video_title=' + $_POST["video_title"] + '&email=' + $_POST["email"],
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
?>
当我运行它时,它显示成功,但 Zapier 没有收到它。
在 Zapier 的文档中,有人给出了一个正确的 cURL 帖子的例子,就像这样 -->
curl -v -H "Accept: application/json" \
-H "Content-type: application/json" \
-X POST \
-d '{"first_name":"Bryan","last_name":"Helmig","age":27}' \
https://zapier.com/hooks/catch/n/Lx2RH/
我猜我在 PHP 文件中遗漏了一些东西,非常感谢帮助!
您需要对要发送的数据进行 json 编码并设置内容类型:
改变:
$opts = array(
CURLOPT_URL => 'https://zapier.com/hooks/catch/n/abcd',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => 'guid='+ $_POST["guid"] + '&video_title=' + $_POST["video_title"] + '&email=' + $_POST["email"],
);
到:
$data = array('guid' => $_POST["guid"], 'video_title' => $_POST["video_title"], 'email' => $_POST["email"]);
$jsonEncodedData = json_encode($data);
$opts = array(
CURLOPT_URL => 'https://zapier.com/hooks/catch/n/abcd',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $jsonEncodedData,
CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Length: ' . strlen($jsonEncodedData))
);
这应该有效。
您没有正确发送POSTFIELDS
,您需要使用.
不是+
并且你应该对字符串进行 url 编码...
$opts = array(
CURLOPT_URL => 'https://zapier.com/hooks/catch/n/abcd',
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(array('guid' => $_POST['guid'], 'video_title' => $_POST['video_title'], 'email' => $_POST['email']))
);
为了提供一些功能,从之前的代码中提取并制作了一个简单的可重复使用的 function。
function send_array_to_zapier_webhook($php_array, $hook_url){
// Initialize curl
$curl = curl_init();
$json_encoded_data = json_encode($php_array);
$opts = array(
CURLOPT_URL => $hook_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json_encoded_data,
CURLOPT_HTTPHEADER => array('Content-Type: application/json','Content-Length: ' . strlen($json_encoded_data))
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.