Inserting record in zoho api v2 in PHP - php

I want to insert data in zoho crm using api v2. first make an array then i encoded json .Request url https://www.zohoapis.com/crm/v2/Contacts.
But i got this error.
Code:
$authtoken = ***********;
$fields={"data":["{\"Last_Name\":\"Test John insert\",\"Email\":\"testjhon#jhon.com\"}"]};
$zoho_url = "https://www.zohoapis.com/crm/v2/Contacts";
Error:
{"data":[{"code":"INVALID_DATA","details":{"expected_data_type":"jsonobject","index":0},"message":"invalid data","status":"error"}]}

Working example:
$fields = json_encode(
array(
"data" => array([
"Company" => "abc",
"Last_Name" => "Tom",
"City" => "Egham"
],
[
"Company" => "abc",
"Last_Name" => "Jerry",
"City" => "Egham"
])
)
);
Send headers this way :
$headers = array(
'Content-Type: application/json',
'Content-Length: ' . strlen($fields),
sprintf('Authorization: Zoho-oauthtoken %s', $oauth)
);

Use this json array:
$fields = "{\"data\":[{\"Last_Name\": \"Test\",\"First_Name\": \"TESTING\",\"Email\": \"demo#w3scloud.com\"}],\"trigger\":[\"approval\",\"workflow\"]}";

send this way :
[{ "data": \[ { "Company":"company name", "Last_Name":"your last name", "Phone":"123456789", "First_Name": "your first name", "Email":"first#gmail.com" } \], “triggger”:\[“workflow”,”approval”,”blueprint”\] }]
click here to view image (request and response via postman)
hope this will help you.

I've noticed that Zoho seems to want an extra pair of brackets around the data. And you might try encoding the data array to a JSON-string before sending it to cURL.
$fields = json_encode([
["data" => ["Last_Name" => "Test John insert","Email" => "testjhon#jhon.com"]],
]);
As #Ghost mentioned, you may also need to change the content-type. According to the PHP docs, passing an array to CURLOPT_POSTFIELDS will set the content-type to multipart/form-data; what you probably want is application/json.
CURLOPT_HTTPHEADER => array(
"Authorization: ".$authtoken,
"Content-Type: application/json"
),

You must send the json file to zoho api, and all be works.:
$fields=["data"=> ['Last_Name'=>'Test John insert','Email'=>'testjhon#jhon.com']];
$fields = json_encode($fields);

Related

Guzzle: Sending POST with Nested JSON to an API

I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:
{
"startCountryCode": "CH"
"endCountryCode": "US",
"products": {
"quantity": 1,
"vid": x //Variable ID
}
}
Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate
$body = [
"endCountryCode" => "US",
"startCountryCode" => "CN",
"products" => [
'vid' => $vid,
'quantity' => 1
],
];
$request = $this->client->request(
'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
[
'headers' => [
'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
],
'body' => json_encode( $body )
],
);
I've also tried using 'json' => $body instead of the 'body' parameter.
I am getting 400 Bad Request error.
Any ideas?
Try to give body like this.
"json" => json_encode($body)
I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.
In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!
You don't need to convert data in json format, Guzzle take care of that.
Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...
$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);

Send JSON from a slash command using PHP

I have created a slash command for Slack and I need to send JSON data to Slack. This is the code I am using but the response is treated as plain text by Slack.
$data = "payload=" . json_encode(array(
"content-type" => "application/json",
"text" => "a message",
"response_type" => "ephemeral",
"username" => "user",
"icon_emoji" => ":icon:"
),JSON_UNESCAPED_SLASHES);
echo $data;
Am I missing something?
It seems I wasn't building my JSON file according to SLACK conventions.
It should not have the payload parameter which is only used for incoming web hooks.
The PHP page should include this line:
header('Content-Type: application/json');
The slash command response should be built as follows:
$data = json_encode(array(
"content-type" => "application/json",
"text" => "a message",
"response_type" => "ephemeral",
"username" => "user",
"icon_emoji" => ":icon:"
),JSON_UNESCAPED_SLASHES);
echo $data;

Field "to" must be a JSON string [Firebase]

I'm trying to send notification using a cron job. I migrated from GCM to FCM. In my server side, I changed https://android.googleapis.com/gcm/send to https://fcm.googleapis.com/fcm/send and also updated on how to request the data changing registration_ids to to. Checking the json passed it is a valid json but I'm having an error Field "to" must be a JSON string. Is there anyway to solve this?
Here is my code
function sendNotificationFCM($apiKey, $registrationIDs, $messageText,$id) {
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $apiKey
);
$message = array(
'to' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => json_encode($message)
));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Try explicitly converting $registrationIDs to string.
$message = array(
'to' => (string)$registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Edited Answer
The 'to' parameter requires a string - which is the recipient of the message.
The $registrationIDs could be passed a separate parameter (as string array) to 'registration_ids'
Edit your code to something like this:
$recipient = "YOUR_MESSAGE_RECIPIENT";
$message = array(
'to' => $recipient,
'registration_ids' => $registrationIDs,
'data' => array(
"message" => $messageText,
"id" => $id,
),
);
Where $recipient is
a registration token, notification key, or topic.
Refer this:
Firebase Cloud Messaging HTTP Protocol
Try making to as a string:
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
...
},
}
// if you are using an array like
$fcm_ids = array();
$fcm_ids[] = "id_1";
$fcm_ids[] = "id_2";
$fcm_ids[] = "id_3";
//.
//.
//.
$fcm_ids[] = "id_n";
// note: limit is 1000 to send notifications to multiple ids at once.
// in your messsage send notification function use ids like this
$json_data = [
"to" => implode($fcm_ids),
"notification" => [
"title" => $title,
"body" => $body,
],
"data" => [
"str_1" => "something",
"str_2" => "something",
.
.
.
"str_n" => "something"
]
];
I had a similar problem. It turns out when I retrieved the Registration Token from my Firebase database (using this Firebase PHP Client), it was returned with double quotes at the beginning and at the end of the token. So I had to remove the first and last characters from the token before I could use it. The code below solved my problem
substr($registrationToken, 1, -1)

APNS PHP JSON Payload structure

I am sending push notifications via a PHP script to connect to APNS server. Everything is working fine when I use the below payload structure.
$body['aps'] = array(
'alert' => $message,
'badge' => $badge,
'sound' => 'default'
);
$payload = json_encode($body);
However, I need to add more parameters to the 'alert' element as well as want to add some more custom parameters. The way I do is is as follows, but APNS is not accepting the JSON. Is it a problem with my JSON creation method in PHP?
$payload='{
"aps": {
"alert":{
"title": "'.$message.'",
"body":"'.$notif_desc.'"
},
"badge":"'.$badge.'",
"sound": "default"
},
"type": "notification",
"id":"'.$lastid.'",
"date:"'.$date1.'"
}';
So basically, I have two queries. IS the second method wrong? If so, please show me a valid method to create nested JSON Payload for APNS server. Second question, I need to add custom PHP variables to the Payload, I want to know whether the way I have added it in the second method is right or wrong.
basically, I need to create a JSON object as below in PHP
{
"aps" : {
"alert" : {
"title" : "Game Request",
"body" : "Bob wants to play poker",
"action-loc-key" : "PLAY"
},
"badge" : 5,
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
You're missing a double quote after the "date" property:
"date:"'.$date1.'"
... should be...
"date":"'.$date1.'"
I'd recommend putting the payload together as a PHP object/array first (like your original example) as it is much easier to see the structure in that format rather than a giant concatenated string. E.g.
$payload['aps'] = array(
'alert' => array(
'title' => $title,
'body' => $body,
'action-loc-key' => 'PLAY'
),
'badge' => $badge,
'sound' => 'default'
);
$payload['acme1'] = 'bar';
$payload['acme2'] = array(
'bang',
'whiz'
);
$payload = json_encode($body);
$send_data =
array(
'aps' =>
array
(
'status_code'=>200,
'alert'=>$message,
'sound' => 'default',
'notification_type'=>'DoctorPendingRequest',
'request_id'=>$request_id
)
);
Passs $send_data to payload.

SugarmCRM REST API always returns "null"

I'm trying to test out the SugarCRM REST API, running latest version of CE (6.0.1). It seems that whenever I do a query, the API returns "null", nothing else. If I omit the parameters, then the API returns the API description (which the documentation says it should).
I'm trying to perform a login, passing as parameter the method (login), input_type and response_type (json) and rest_data (JSON encoded parameters). The following code does the query:
$api_target = "http://example.com/sugarcrm/service/v2/rest.php";
$parameters = json_encode(array(
"user_auth" => array(
"user_name" => "admin",
"password" => md5("adminpassword"),
),
"application_name" => "Test",
"name_value_list" => array(),
));
$postData = http_build_query(array(
"method" => "login",
"input_type" => "json",
"response_type" => "json",
"rest_data" => $parameters
));
echo $parameters . "\n";
echo $postData . "\n";
echo file_get_contents($api_target, false,
stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n",
"content" => $postData
)
))) . "\n";
I've tried different variations of parameters and using username instead of user_name, and all provide the same result, just a response "null" and that's it.
Try setting input_type and response_type to JSON (capitals). If it doesn't work, go to Sugar installation, edit config.php entry under logger => level and make it debug instead of fatal and see if it says about any errors.

Categories