简体   繁体   中英

cURL POST request in PHP script using file_get_contents

I'm using a Zapier Webhook to connect a form to Salesforce.

I'm trying to get data from the form to POST to my Zap.

Before connecting to Zapier I had a script that was connected to a custom api and we used file_get_contents to get our inputs. This script isn't working and isn't triggering the Zap. I don't normally work in PHP so I'm not sure what the problem could be.

Here is the new script I'm working on utilizing 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;

Our old script utilizing a custom api (this one works):

<?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();

I tried putting Zapier Webhook into the old script and it didn't work either. It doesn't seem to be an issue with our Zap because I can submit success Postman requests and I the new script is close to what Postman generated for me (with the exception of trying to get the data from file_get_contents instead of a hard coded object.)

You basically got it right. The only error I can spot is that the JSON data object is being provided as the second argument of your curl_setopt_array() call. That's not where it belongs.

Just remove the $json data object, which is already getting submitted as a postfield within the cURL request.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM