【问题标题】:cURL POST request in PHP script using file_get_contents使用 file_get_contents 在 PHP 脚本中的 cURL POST 请求
【发布时间】:2021-08-13 04:26:37
【问题描述】:

我正在使用 Zapier Webhook 将表单连接到 Salesforce。

我正在尝试从表单获取数据以 POST 到我的 Zap。

在连接到 Zapier 之前,我有一个连接到自定义 api 的脚本,我们使用 file_get_contents 来获取我们的输入。此脚本不起作用,也没有触发 Zap。我通常不使用 PHP,所以我不确定问题可能是什么。

这是我正在使用 Zapier 编写的新脚本:


<?php
$json_data = file_get_contents('php://input');
$json = json_encode($json_data);
$curl = curl_init();

curl_setopt_array($curl, $json, array(
  CURLOPT_URL => 'zapier webhook url',
  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 => $json,
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

我们使用自定义 api 的旧脚本(这个有效):

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

$json_data = file_get_contents('php://input');

$opts = array(
    'http' => array(
        'header' => "Content-type: application/json\r\n" . "ClientID: id#\r\n",
        'method' => 'POST',
        'content' => $json_data,
    ),
);

$context = stream_context_create($opts);

$url = 'custom api';

$response = file_get_contents($url, false, $context);

exit();

我尝试将 Zapier Webhook 放入旧脚本中,但它也不起作用。这似乎不是我们的 Zap 的问题,因为我可以提交成功的 Postman 请求,并且我的新脚本接近 Postman 为我生成的内容(除了尝试从 file_get_contents 获取数据而不是硬编码对象.)

【问题讨论】:

  • 这可能是一个很长的镜头,但是转储你的 json 编码数据,可能有一个额外的外括号或那里的东西

标签: php curl zapier


【解决方案1】:

你基本上是对的。我能发现的唯一错误是 JSON 数据对象作为 curl_setopt_array() 调用的第二个参数提供。那不是它所属的地方。

只需删除 $json 数据对象,它已经作为 cURL 请求中的 postfield 提交。

curl_setopt_array($curl, array(
...
));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多