Using CURL to receive data, then send data to external webhook - php

so I am trying to receive JSON data from one webhook, use PHP to filter for some conditions, and then send the data to an external webhook address based on those conditions.
So for example, I created a php file on my server called "webhook.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);
The "php://input" can either be exactly as it is, or I tried replacing it with the URL of my webhook.php file just in case. I can test my webhook using Postman, and I am returned a 200 OK, but the data is never sent to my external webhook (https://hooks.zapier.com/hooks/catch/).
I have written the conditional PHP code yet; I just want to ensure I can send and receive this data properly first. Any guidance is much appreciated!

Problem is with curl_setopt. You need to pass three argument for this method curl_setopt ( resource $ch , int $option , mixed $value ). You can set these by following
$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);
Or you can set them individually like this
curl_setopt($curl, CURLOPT_URL, 'https://hooks.zapier.com/hooks/catch/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
.....

Related

Codeigniter to Send form data to api url

I have form (5 fields which includes 1 file attachment field), whose field's data I need to submit on db as well as send on api url.
If I put api url in action of form tag then form data being send successfully. BUT I can't add api url in action coz like this form will redirect to that api url by leaving the site.
So to avoid putting api url in action I used following code to send form data to api url.
/* Endpoint */
$url = 'http://url_here';
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'to' => $to,
'cc' => '',
'message' => $subject,
'attachment' => '#'.$tmpfile.';filename='.$filename,
'message' => $message
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
/* Define content type */
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
/* Return json */
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
/* make request */
$result = curl_exec($ch);
/* close curl */
curl_close($ch);
echo $result;
This code giving this error.
{"timestamp":"2022-03-09T07:23:54.873+00:00","status":415,"error":"Unsupported Media Type","message":"","path":"/QRCodeGenerator/sendmail"}
While searching for solution, I also tried adding
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:application/json'));
For Accept:application/json to work I did convert array into json using jason_encode(). But it was still giving same error.
Where I am getting wrong?
UPDATE
I tried this code also which I got from postman where api working fine.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://url_here/QRCodeGenerator/sendmail',
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 => array('to' => 'example#gmail.com','cc' => '','message' => 'This is test subject','body' => 'this is body msg','attachment'=> new CURLFILE('/path/to/file')),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But this is giving blank page. $response printing nothing.

How do i parse a very large json response returned from an API call

I'm accessing data from an API endpoint using curl in my laravel application, which returns a very large JSON response. When I decode this JSON, it appears to decode up to a particular level and stops there. The output is below. You can clearly see that it creates an array and then stops, the rest is an in-iterable string. I wanted to loop over the response, creating a CSV output.
$url = $request->url;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 300000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
// Set Here Your Requesred Headers
'Content-Type: application/json',
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$data = json_decode($response, true);
dd($data);
JsonToCsv::exportCSV($data);
Please how do I properly parse this large JSON response?
Thank you in advance

POST array through cURL doesn't give me the right format

I'm using swifdil api to create users from a html form via curl.
The API expects a certain format (json) to receive but I have no idea how I can achieve the format the API looks for.
Example code by the API:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.swiftdil.com/v1/customers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"type\" : \"INDIVIDUAL\",\r\n \"email\" : \"Maria#Papakiriakou.com\",\r\n \"first_name\" : \"Maria\",\r\n \"last_name\" : \"Papakiriakou\"\r\n}",
I need to submit the values through an HTML form so I did the following:
function createNewUser()
{
// First we get all the information from the fields we need to pass on to swiftdill.
$type = $_POST['type'];
$email = $_POST['email'];
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$fields = array(
'type' => $type,
'email' => $email,
'first_name' => $first_name,
'last_name' => $last_name
);
json_encode($fields);
$fields_string = http_build_query($fields);
$curl = curl_init();
// Set the options for the curl.
curl_setopt($curl, CURLOPT_URL, "https://sandbox.swiftdil.com/v1/customers");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURL_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " .$newToken. "",
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 0c513fa9-667d-4065-8531-8c4556acbc67"
));
The output of my code is as follows:
type=Individual&email=test%40mail.nl&first_name=John&last_name=Doe
Ofcourse this isn't formatted the way the api asks for it, namely:
CURLOPT_POSTFIELDS => "{\r\n \"type\" : \"INDIVIDUAL\",\r\n \"email\" : \"Maria#Papakiriakou.com\",\r\n \"first_name\" : \"Maria\",\r\n \"last_name\" : \"Papakiriakou\"\r\n}",
And also ofcourse, a cURL error appears as follows:
{"id":"xxxx-xxxx-xxxx-xxxx-xxxxxxxxx","type":"malformed_content","message":"Content of the request doesn't conform to specification"}
What do I need to do in my php code so that the API will accept my sent data?
Change the line:
$fields_string = http_build_query($fields);
Into this:
$fields_string = json_encode($fields);
Because the API expecting JSON body, as you are sending non-JSON post body the API will don't know what is it and reject
Why don't you try the response firstly via POSTMAN by setting the data as required by the API and test what actually the API needs.
As per the information provided, it looks like you should remove the below line and just post json_encoded data.
$fields_string = http_build_query($fields);

PHP cURL JSON Object formatting issues

I'm running into an issue with formatting using the curl_setopt functions in PHP. I'm basically trying to re-create the cURL request below, but my code returns a bad request from the server. I'm pretty sure it has to do with poor formatting, but I can't figure out where I went wrong.
//This code returns the data back successfully
curl -H "Content-Type: application/json" -d '{"bio_ids": ["1234567"]}' http://localhost:9292/program
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>
There are two issues:
You need to make sure that the structure of $bio matches what you are expected to pass, so the $bio declaration needs to be:
$bio = array('bio_ids' => array('1234567'));
Secondly you need to json_encode this data structure before sending it to the server:
CURLOPT_POSTFIELDS => json_encode($bio),
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$bio = json_encode($bio);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>

How can I forward $_POST with PHP and cURL?

I receive a POST request at my PHP script and would like to forward this POST call to another script using POST too. How can I do this?
I can use cURL if it's required for this action.
Perhaps:
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
From curl_setopt:
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
Do this,
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($_POST));
Here's a fully functional cURL request that re-routes $_POST where you want (based on ZZ coder's reply)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://urlOfFileWherePostIsSubmitted.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// ZZ coder's part
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$response = curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If need any HTTP authentication
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This can be $arrPostData = $_POST;
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your POST data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // ONLY use this when requesting JSON data
$arrResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // ONLY use this when request json data
),
// If HTTP authentication is required , use the below lines
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));

Categories