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)
Related
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.
I'm trying to send a GET request to an API using PHP stream_context_create and file_get_contents.
I need to add API keys to the headers of my request, I'm storing these in an array so I easily edit them later and use them in multiple functions. What is a good way to include these arrays as headers?
In this case the key of the array would be the header keys and the value of the array the value of the header.
Some code to explain the problem
<?php
$api = array(
"X-Api-Id" => "id",
"X-Api-Key" => "key",
"X-Api-Secret" => "secret"
);
$options = array(
"http" => array(
"header" => "Content-type: application/x-www-form-urlencoded\r\n", // here I need to add the $api array
"method" => "GET"
)
);
return file_get_contents("example.com", FALSE, stream_context_create($options));
?>
Simply add the info to the header.
<?php
$api = [
'X-Api-Id' => 'id',
'X-Api-Key' => 'key',
'X-Api-Secret' => 'secret',
];
$headerData['Content-type'] = 'application/x-www-form-urlencoded';
$headerData = array_merge($headerData, $api);
array_walk($headerData, static function(&$v, $k) { $v = $k.': '.$v; });
$options = array(
'http' => [
'header' => implode("\n", $headerData),
'method' => 'GET'
]
);
return file_get_contents('example.com', FALSE, stream_context_create($options));
?>
To encode the data you can use http_build_query().
To add it to the header options you should be able to do something like:
$options = array(
"http" =>array(
'method' => 'POST', // GET in your case(?)
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($api)
)
);
I'm getting data from Couchdb to PHP using Guzzle library. Now I fetch data in POST format like this:
But I need response like this:
{
"status": 200,
"message": "Success",
"device_info": {
"_id": "00ab897bcb0c26a706afc959d35f6262",
"_rev": "2-4bc737bdd29bb2ee386b967fc7f5aec9",
"parent_id": "PV-409",
"child_device_id": "2525252525",
"app_name": "Power Clean - Antivirus & Phone Cleaner App",
"package_name": "com.lionmobi.powerclean",
"app_icon": "https://lh3.googleusercontent.com/uaC_9MLfMwUy6pOyqntqywd4HyniSSxmTfsiJkF2jQs9ihMyNLvsCuiOqrNxNYFq5ko=s3840",
"last_app_used_time": "12:40:04",
"last_app_used_date": "2019-03-12"
"bookmark": "g1AAAABweJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYorGBgkJllYmiclJxkkG5klmhuYJaYlW5paphibppkZmRmB9HHA9BGlIwsAq0kecQ",
"warning": "no matching index found, create an index to optimize query time"
} }
I only remove "docs": [{}] -> Anyone know I remove this ?
check My code:
$response = $client->post(
"/child_activity_stat/_find",
[GuzzleHttp\RequestOptions::JSON => ['selector' => ['parent_id' => ['$eq' => $userid], 'child_device_id' => ['$eq' => $deviceid]],]]
);
if ($response->getStatusCode() == 200) {
$result = json_decode($response->getBody());
$r = $response->getBody();
json_output(200, array(
'status' => 200,
'message' => 'Success',
"device_info" => $result
));
}
You just need to modify your data structure.
NOTE: Maybe you should add a limit of 1 if you want to only get one document. You will also need to validate that the result['docs'] is not empty.
Example:
<?php
$response = $client->post(
"/child_activity_stat/_find",
[GuzzleHttp\ RequestOptions::JSON => ['selector' => ['parent_id' => ['$eq' => $userid], 'child_device_id' => ['$eq' => $deviceid]], ]]
);
if ($response->getStatusCode() == 200) {
// Parse as array
$result = json_decode($response->getBody(),true);
// Get the first document.
$firstDoc = $result['docs'][0];
// Remove docs from the response
unset($result['docs']);
//Merge sanitized $result with $deviceInfo
$deviceInfo = array_merge_recursive($firstDoc,$result);
json_output(200, array(
'status' => 200,
'message' => 'Success',
"device_info" => $deviceInfo
));
}
In couchdb use PUT request is used to edit or to add data and DELETE remove data
$client = new GuzzleHttp\Client();
// Put request for edit
$client->put('http://your_url', [
'body' => [
'parent_id' => ['$eq' => $userid],
'child_device_id' => ['$eq' => $deviceid]
],
'allow_redirects' => false,
'timeout' => 5
]);
// To delete
$client->delete('htt://my-url', [
'body' = [
data
]
]);
Hi am new to WP development, I would like to add request headers to WordPress Rest API calls but don't know how, can anyone help me in this?
I tried following code but no luck
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( Fk-Affiliate-Id . ':' . YOUR_PASSWORD )
)
);
$api_url = 'https://affiliate.com/api/';
global $affiliate;
$response = wp_remote_request( add_query_arg( array(
'Affiliate-Id' => $affiliate['aff-id'],
'Affiliate-Token' => $affiliate['aff-token']
), $api_url ) , array( 'timeout' => 10));
You can send the headers you need by including those in request options - second argument of wp_remote_request function($args in my example)
$args = [
'method' => 'GET',
'timeout' => 10,
'headers' => array() //add headers here
];
wp_remote_request('http://test.com', $args);
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)
));