im trying to send to my api site, the following Json with one record.
It works Ok, but I want to send more than one record, how can I do that?
Later i want to read a txt and make a json with all the records in it.
<?php
//API URL
$url = 'http://mysitexder.net/receiveJson.php';
//create a new cURL resource
$ch = curl_init($url);
//setup request to send json via POST
$data = array(
'cod' => '321',
'name' => 'Jane',
'address' => 'Route 123456'
);
$payload = json_encode(array("user" => $data));
//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute the POST request
$result = curl_exec($ch);
//close cURL resource
curl_close($ch);
Send a 2-dimensional array:
$data1 = array(
'cod' => '321',
'name' => 'Jane',
'address' => 'Route 123456'
);
$data2 = array(
'cod' => '555',
'name' => 'John',
'address' => '123 Main St'
);
$payload = json_encode(array('users' => array($data1, $data2)));
Later i want to read a txt and make a json with all the records in it.
It's hard to tell what you mean by this. But you should parse the text in whatever way you want (e.g. each line is a record), create a PHP array from that, and call json_encode().
Related
I want to send data from site A to site B. I've successfully transferred data but I want to redirect the url to the returned url generated from Curl. Below is my code.
$jsonData = array(
'first_name' => "$fname",
'last_name' => "$lname",
'phone_number' => "$phone",
'gender' => "$gender",
'email' => "$email",
'businessname' => "$businessname",
'natureofbusiness' => "$biznature",
'address' => "$address",
'utm' => "esg",
'date' => "$d"
);
$jsonDataEncoded = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
This is the result
{"data":{"success":true,"redirectUrl":"https://url.com/authorize
/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODU5MDg4MzgsImRhdGEiOnsidXRtIjoiZXNnIiwiZW1haWwiOiJjbm5lYnVlNGFsbEB5YWhvby5jb20iLCJmaXJzdE5hbWUiOiJDaGlt
YSIsImxhc3ROYW1lIjoiT3NjYXIiLCJjb250YWN0TnVtYmVyIjoiOTg3MzczNjM3MyIsInRpbWVTdGFtcCI6IjE1ODU5MDc4NTUifSwiaWF0IjoxNTg1OTA4NTM4fQ.v6ecH7Tu5WB0ZkK-
U2ob_sQRSNn13rOU95Zo4BgwSF4?utm=esg","status":200}}
I need help to redirect to that Url.
Convert JSON result into array
$result = '{"data":{"success":true,"redirectUrl":"https://url.com/authorize/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODU5MDg4MzgsImRhdGEiOnsidXRtIjoiZXNnIiwiZW1haWwiOiJjbm5lYnVlNGFsbEB5YWhvby5jb20iLCJmaXJzdE5hbWUiOiJDaGltYSIsImxhc3ROYW1lIjoiT3NjYXIiLCJjb250YWN0TnVtYmVyIjoiOTg3MzczNjM3MyIsInRpbWVTdGFtcCI6IjE1ODU5MDc4NTUifSwiaWF0IjoxNTg1OTA4NTM4fQ.v6ecH7Tu5WB0ZkK-U2ob_sQRSNn13rOU95Zo4BgwSF4?utm=esg","status":200}}';
$result = json_decode($result, true);
Now get url from array.
if(isset($result["data"])){
if($result["data"]["success"]==true){
$url = $result["data"]["redirectUrl"];
header("location:".$url);
}
}
I am working on a slash command that'll invoke a dialog.
$dialog = [
'callback_id' => 'ryde-46e2b0',
'title' => 'Request a Ride',
'submit_label' => 'Request',
'elements' => [
[
'type' => 'text',
'label' => 'Pickup Location',
'name' => 'loc_origin'
],
[
'type' => 'text',
'label' => 'Dropoff Location',
'name' => 'loc_destination'
]
]
];
// get trigger ID from incoming slash request
$trigger = filter_input(INPUT_POST, "trigger_id");
// define POST query parameters
$query = [
'token' => 'XXXXXXXXX MY TOKEN XXXXXXXXX',
'dialog' => json_encode($dialog),
'trigger_id' => $trigger
];
// define the curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://slack.com/api/dialog.open');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/x-www-form-urlencoded'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// set the POST query parameters
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
// execute curl request
$response = curl_exec($ch);
// close
curl_close($ch);
var_export($response);
When I issue the slash command, my test dialog opens successfully
I then fill two test values test1 and test2 in the fields and submit the request. My endpoint is being hit with the dialog data payload correctly, but the data sent is not valid JSON:
The value of $_POST is: (I've masked all identifying tokens/IDs with xxx)
{"payload":"{\\\"type\\\":\\\"dialog_submission\\\",\\\"token\\\":\\\"XXX\\\",\\\"action_ts\\\":\\\"1536603864.688426\\\",\\\"team\\\":{\\\"id\\\":\\\"xxx\\\",\\\"domain\\\":\\\"ourdomain\\\"},\\\"user\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"my_name\\\"},\\\"channel\\\":{\\\"id\\\":\\\"xxx\\\",\\\"name\\\":\\\"directmessage\\\"},\\\"submission\\\":{\\\"loc_origin\\\":\\\"test1\\\",\\\"loc_destination\\\":\\\"test2\\\"},\\\"callback_id\\\":\\\"ryde-46e2b0\\\",\\\"response_url\\\":\\\"https:\\\\/\\\\/hooks.slack.com\\\\/app\\\\/XXX\\\\/XXX\\\\/XXX\\\",\\\"state\\\":\\\"\\\"}"}
This is an invalid JSON, even when the "\\" instances are removed. Why is this happening?
Here is the code that handles the POST from Slack:
error_log(" -- dialog response: " . json_encode($_POST) . "\n", 3, './runtime.log');
Which results in the output above.
I'm not sure why you are calling json_encode($_POST). The documentation is very clear on the format that will be sent:
$payload = filter_input(INPUT_POST, 'payload');
$decoded = json_decode($payload);
var_dump($decoded);
I want to send these three array data into the external api. For that firstly I encode this into JSON, but always it sends the last array.
$params = array( array('receiverName' => 'sample_name',
'receiverEmail' => 'krishanuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'),array('receiverName' => 'sample_name',
'receiverEmail' => 'karamuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'),array('receiverName' => 'sample_name',
'receiverEmail' => 'krishanuniyalas#gmail.com',
'senderEmail' => 'info#hotelpalacio.net',
'roomNumber' => '12456',
'accessToken' =>'ca5629d0-6810-11e8-9d40-d7194ac0ac8d'));
$data_string = json_encode($params);
foreach($params as $pa) {
$r=json_encode($pa);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $r);
Here 's a working example ...
$data = [
[
'a' => 'bla',
],
[
'b' => 'blubb',
],
];
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, "http://www.example.com/");
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$result = [];
foreach ($data as $value) {
$json = json_encode($value);
curl_setopt($handle, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
]);
$result[] = curl_exec($handle);
}
Open a valid curl resource and set the corresponding curl options for your purpose. You want to send a json string as post request. Furthermore you should tell the other side, that you send json data. Say curl, that you 're awaiting a response and the fire every time running through the foreach loop. That 's all ...
If you want to send the whole data at once leave out the foreach loop end encode the whole data array and send it.
You need to just create a simple query params like $data = http_build_query($params)
And then pass data to your curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
i'm trying to invite a person via email to Trello from my website. Here is the API reference. When I try to invite him, the plain reply is "invalid key". Here is my function:
public function inviteEmployeeToTrello ($email, $name, $isAdmin)
{
$organazationTrelloID = 'myOrganazationID';
$trelloAuthToken = 'myTrelloAuthToken';
$trelloInviteUrl = 'https://trello.com/1/organizations/'.$organazationTrelloID.'/members';
if ($isAdmin == 1)
{
$type = 'admin';
}
else
{
$type = 'normal';
}
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,
'token' => $trelloAuthToken
);
// open connection
$ch = curl_init();
// set the url, number of PUT vars, PUT data
curl_setopt($ch, CURLOPT_URL, $trelloInviteUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// exec
$replyRaw = curl_exec($ch);
$reply = json_decode($replyRaw, true);
// close connection
curl_close($ch);
dd($ch);
}
CURLOPT_POSTFIELDS does not want a JSON,
if you want a urlencoded request, use http_build_query($fields) , or if you want a multipart/form-data request, just give it $fields array directly. (the API doc's doesn't seem to mention which request types it accept, though. urlencoded is the most common one.)
As the error code says, you forgot to pass your application key. Here's an example from the API reference :
https://api.trello.com/1/organizations/publicorg?members=all&member_fields=username,fullName&fields=name,desc&key=[application_key]&token=[optional_auth_token]
You have to include it in your query, hence in your case, add it to the
$fields array :
$fields = array(
'fullName' => $name,
'email' => $email,
'type' => $type,,
'key' => $trelloAppKey
'token' => $trelloAuthToken
);
I'm not quite understanding how to format my cURL call to the Mandrill API...
$specific_api = "/messages/send.json";
$url = "https://mandrillapp.com/api/1.0/" . specific_api . "?";
$param_array = array(
'key' => $apikey,
'template_name' => 'mytemplate',
'template_content' => array(
'name' => 'main',
'content' => 'This is HAPPENING RIGHT NOW!'
),
'message' => array(
'subject' => 'blanketID Service: Pet Found',
'from_email' => 'no-reply#blanketid.com',
'from_name' => 'blanketID Service',
'to' => array(
'email' => 'devinmightbe#gmail.com',
'name' => 'Devin Columbus'
)
)
);
$encoded = json_encode($param_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$data = curl_exec($ch);
curl_close($ch);
$arr = json_decode($data, true);
echo $data;
I'm really not even sure that I've got this all setup correctly ...
I'm not confident, but having the read the documentation at php.net with regards to CURLOPT_POSTFIELDS, I believe the format you are passing is not accepted.
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix.