Updating a JSON file with Wordpress REST API - php

I am trying to insert a new object in a JSON file that is placed in my WP theme root, by using wp_remote_post command. The page does not throw any visible errors, but the JSON file is not getting updated either. I prefer this method instead of file_put_contents function so please help me understand this approach. Thanks.
front-page.php:
if(isset($_POST['save']) && !empty($_POST['specie_name']) && !empty($_POST['specie_rate'])):
$specie_name= $_POST['specie_name'];
$specie_rate=(int)$_POST['specie_rate'];
$url = get_template_directory_uri() . '/species.json';
$body = wp_json_encode(array(
'specie' => $specie_name,
'rate' => $specie_rate,
));
$args = array(
'body' => $body,
'headers' => [ 'Content-Type' => 'application/json', ],
'timeout' => 60,
'redirection' => 5,
'blocking' => true,
'httpversion' => '1.0',
'sslverify' => false,
'data_format' => 'body',
);
wp_remote_post( $url, $args );
endif;
The JSON looks like this:
[
{
"specie": "Oscar",
"rate": 300
},
{
"specie": "Piranha",
"rate": 400
},
]

I am closing this question as I believe I have figured the answer. That is, to get the json contents with wp_remote_get, and then using file_put_contents to push in data.

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

Empty Payload. JSON content expected (guzzle, php, azur active directory and outlook)

I am a student in programming and I have difficulties with my projects, little documentation meets my expectations and I would need help.
in this project I have to send from my application the token, the json flow on outlook to schedule a meeting
about Project : the principle is on a page to create a meeting which will then be linked to the outlook calendar this document helped me a lot https://learn.microsoft.com/fr-fr/graph/api/calendar-post-events?view=graph-rest-1.0&tabs=http https://youtu.be/orVsKsRs2Us
(data is on another page)
the whole function
public function Postcalendrier($ID,$data) {
$token=$_SESSION['token'];
$ID=$_SESSION["ID"];
$calendarGroup="/calendarGroups/{myID}/";
$calendar="calendars/{myID}/events";
$urlcalendar="https://graph.microsoft.com/v1.0/users/".$ID;
$url=$urlcalendar.$calendarGroup.$calendar;
$headers = [
'Authorization' => 'Bearer '.$token->access_token,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$json = json_encode([$data])
$reponse = $this->guzzle->request('POST', $url,['headers' =>
$headers,'json' => $json],['debug' => true]);
return $response->getStatusCode();
}
$data = array(
"subject" => $Subject,
"body" => array(
"contentType" => "HTML",
"content" => $Content
),
"start" => array(
"dateTime" => $StartDateTime."T".$StartHourTime.":00",
"timeZone" => "$localDatetime"
),
"end" => array(
"dateTime" => $StartDateTime."T".$EndHourTime.":00",
"timeZone" => "$localDatetime"
),
"location" => array(
"displayName" => $Location
),
"attendees"=> [array(
"emailAddress"=> array(
"address"=> $addressmail,
"name"=>$prenom
),
"type"=> "required"
)]
);
I get this error message
Empty Payload. JSON content expected
so I tried with a different JSON but
I got this message instead and I don't really understand it
code UnableToDeserializePostBody message were unable to deserialize
this is my new json
$json = [
'json' => json_encode([$data])
];
thank you for your attention

Wordpress wp_remote_post passing an array argument

I'm sending a request using wp_remote_post.. Im passing an array in one of the $args and in the body of my $response is returning wrong key and value..
Code:
$x = $_POST['x']; // 50
$y = $_POST['y']; // "sample"
if (isset($x)) {
$args['x'] = array($x);
}
if (isset($y)) {
$args['y'] = $y
}
$response = wp_remote_post($post_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $args,
'cookies' => array()
));
echo json_encode($response);
The Json encode response:
"body": "{\"x[0]\":\"50\", \"y\":\"sample\"}"
My expected response:
"body": "{\"x\":[50], \"y\":\"sample\"}"
I figured it out.. I just need to put $args inside json_encode()..
'body' => json_encode($args)

Update video using youtube api

I want to update a video using google api v3 and i get the error 400 Bad Request.
This is my code.
$url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&videoId='.$_GET['videoId'].'&access_token='.Session::get('access_token');
$params = array(
"id"=> $_GET['videoId'],
"kind"=> "youtube#video",
'snippet' => array(
"title"=> "I'm being changed.",
"categoryId"=> "10",
"tags"=> array(
"humanities",
"Harpham",
"BYU"
),
'description' => 'test!'
)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'PUT',
'content' => http_build_query($params),
),
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
I think since you don't set all parameters inside snippet, that's giving an error. What you can do is, first getting that video with videos->list, then updating the field you are interested in and sending back the update request with the whole object back.
Here's an example also utilizing php client library: https://github.com/youtube/api-samples/blob/master/php/update_video.php

Google MAP Geolocation API in PHP

I call the Google MAP Geolocation API in PHP, to get the location by the cellTower information. However, when I change any of the cellTower information, I always get the same results: { "location": { "lat": 52.519171, "lng": 13.406091 }, "accuracy": 18000.0 }.
Here is my PHP script, could anyone help to check where is the problem? Thank you.
<?php
// The data to Google API
$JsonData = array(
'CellTowers' => array (
'cellId' => 42,
'locationAreaCode' => 415,
'mobileCountryCode' => 310,
'mobileNetworkCode' => 410
));
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode($JsonData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
echo $response;
?>
The problem is the JSON data, it works when changed the $cellData to following:
$cellData = array(
'cellTowers' => array (
array ('cellId' => 42,
'locationAreaCode' => 415,
'mobileCountryCode' => 310,
'mobileNetworkCode' => 410)
));

Categories