Passing JSON data using CURL - php

I am using a CURL post to an existing API. The API returns the error content must be JSON or plain text. I json_encode data and post the encoded data to the API.
In the API, it says the Content-Type should be application/x-www-form-urlencoded'.
However, it still returns the error content must be JSON or plain text. What could be the issue with my code below after submitting my data in JSON format?
This is a sample request body in the API doc.
"item" : "Store",
"content" : {
"channel":"false",
"hop": "false",
"msg": "Order successfully placed."
}
Controller
public function postUrl()
{
$url = "https://api.com/";
$data = array("item" => "Nike Shoes","content" => array ("channel" => "false" ,"hop" => "false","msg" => "Item Sold"));
$postdata = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postdata);
}

Perhaps this is because boolean values are specified as strings.
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => false,
'hop' => false,
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}
Also try this
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => 'false',
'hop' => 'false',
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}

Related

Magento 2 rest API: filter category by name

I need to find categories by name using Magento 2 rest api.
I use /all/V1/categories and filters but I can't get it to work.
Here's the code:
$url = "https://*******/index.php/rest";
$token_url= $url."/V1/integration/admin/token";
$ch = curl_init();
$data = array("username" => USERNAME, "password" => PASSWORD);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
$token = curl_exec($ch);
$adminToken= json_decode($token);
$headers = array('Content-Type:application/json','Authorization:Bearer '.$adminToken);
$ch = curl_init();
$apiUrl = $url."/all/V1/categories";
$data = [
"searchCriteria" => [
"filterGroups" => [
"filters" => [
"fieldName" => "category",
"value" => 'CATEGORY NAME',
"condition_type" => 'eq'
]
]
],
];
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$response = json_decode($response, TRUE);
curl_close($ch);
This is the error that appears after launching the code:
array:3 [▼ "message" => ""%fieldName" is required." "parameters" => array:1 [▼ "fieldName" => "category" ]
You can get categories by name with Magento 2 rest api by adding search criteria to endpoint rest/all/V1/categories/list. The request to api should look like this:
https://website.com/rest/all/V1/categories/list?searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bfield%5D=name&searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bcondition_type%5D=eq&searchCriteria%5BfilterGroups%5D%5B0%5D%5Bfilters%5D%5B0%5D%5Bvalue%5D=category_name
Replace website.com with the url of your website and category_name with the search term for category.
If the search string also should match part of the category name, you can use like instead of eq.
For more information, refer to: https://devdocs.magento.com/guides/v2.4/rest/performing-searches.html

Posting JSON Data With PHP cURL returns Invalid Content Type error

I'm working with OpenSRS EMAIL API. I'm trying to create a new user email for a domain. In their first example, they are using JSON format :
{
"credentials": {
"user": "domain_admin#example.com",
"password": "sw0rdf1sh"
},
"user": "bhayden#example.com",
"attributes": {
"name": "Bob Hayden",
"password": "changeit",
"delivery_forward": true,
"forward_recipients": [
"bob.hayden#example.com
}
}
I'm sending this with cURL
$json = array(
"user" => $emailName,
"attributes" => array(
"name" => "Janet User",
"password" => $email_password,
"delivery_forward" => false
)
);
//
//
$payload = json_encode( $json );
//
$data = [
'Content-Type:application/json',
'X-Username:' . $connection_details['reseller_username'],
'X-Signature:' . md5(md5($payload . $connection_details['api_key']) . $connection_details['api_key']),
];
//
$ch = curl_init($connection_details['api_host_port']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//
$response = curl_exec($ch);
//
//header('Content-type: application/json');
//
echo '<pre>';
echo $response;
echo '</pre>';
This print following error
0.9 400 0 Invalid Content-Type XCP
What am I doing wrong?
I fixed this issue by reformarting the entire request. This worked for me
$data = array(
"user" => $emailName,
"attributes" => array(
"name" => "Janet User",
"password" => $email_password,
"delivery_forward" => false
)
);
$postdata = json_encode($data);
//
$ch = curl_init($connection_details_email['api_host_port']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

Json received = false

I am using ci framework, and i try to create notification using
onesignal API. I have hosted the website using https. But why my JSON
received is always false using onesignal API, but if i test using
postman it runs fine without error.
This is my code
function send_message($id, $nama) {
$content = array(
"en" => $nama
);
$heading =array(
"en" => $id
);
$fields = array(
'app_id' => "2cd5ad24-a2d9-4e7d-ac66-7494cebd8e84",
'included_segments' => array(
'Active Users'
),
'contents' => $content,
'headings' => $heading,
'url' => "https://esop.matahariled.com"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic MDQ0NjY0ZmYtZjQ2Yi00ODVmLTkzZjgtZmVkZDBkODk0MDFl'
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT']."/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}

Can't upload file to BOX api

I wrote this code. I send data to $url = "https://upload.box.com/api/2.0/files/content", but i don't get a response. Maybe someone has also had this problem?
$absolutePath = 'home/my/path/uploads/media/ClientPDF/0001/01/c607bea86bdb42220bb49aac722b4a5eb44be3db.pdf';
$json = json_encode([
'name' => 'c607bea86bdb42220bb49aac722b4a5eb44be3db.pdf,
'parent' => ['id' => 7479666489] //parent folder
]);
$fields = [
'attributes' => $json,
'file' => #$absolutePath
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer MY_TOKEN_KEY'
'Content-Type:multipart/form-data'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$response = curl_exec($ch);
var_dump(json_decode($response, true)); die;
var_dump - print nothing, i can't debug this request. Please, help me to solve this problem

Warning on GCM with PHP

I'm using GCM in php. Everything is fine. But im getting response as
"Field \"data\" must be a JSON array: example\n"
My code for GCM is
function sendNotification($registrationIdsArray, $messageData) {
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
var_dump($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
and my $data object is
{"data":"example","registration_ids":["apikey1", "apikey2"]}
What is the missing code for GCM here.
the data which you are passing should be an array not a string like this
$messageData = array(
'success' => 1,
'title' => $data['title'],
'desc' => $data['message']
);

Categories