How to prevent wp_remote_post to add backslashes - php

To publish a plugin I must change my code to use the Wordpress HTTP Api.
Therefore, I have translate my code.
Before.
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
After
$data = array("Param1" => 'ValueParam1', "Param2" => "ValueParam2");
$data_string = json_encode($data);
$result = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode($data_string),
'method' => 'POST',
'timeout' => 60, // added
'redirection' => 5, // added
'blocking' => true, // added
'httpversion' => '1.0',
'sslverify' => false,
));
But with the function wp_remote_post I have this problem.
When JSON data is sended to remote host, the data has the backslashes inside.
Example:
{\"Param1\":\"ValueParam1\","Param2\":\"ValueParam2\"}
What is wrong?
Have I wrong something in translate the origin code?
I need some help to send JSON data without these escaping characters.
Thanks.

Pass JSON_HEX_QUOT as a second parameter to wp_json_encode to escape the double quotes without a slash. See: https://developer.wordpress.org/reference/functions/wp_json_encode/ and https://www.php.net/manual/en/json.constants.php for more details.

Related

POST Request PHP with Curl

I'm working on a wordpress project where I have to modify my theme, so I can request a JSON to an external API.
I've been searching through the internet how to do that and a lot of people use CURL.
I must do a POST request, yet I don't know how it works or how to do it.
So far I've got this code running:
$url='api.example.com/v1/property/search/';
$data_array = array(
$id_company => '123456',
$api_token => 'abcd_efgh_ijkl_mnop',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_array);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo($result);
I don't know where exactly I should put my authentication info or how does the curl methods work in PHP. Can you guys check it out and help me solve this?
There are some answers out there that would help you, such as this one.
However, WordPress actually has built-in functions to make GET and POST requests (that actually fall back to cURL I believe?) named wp_remote_get() and wp_remote_post(). Clearly in your case, you'll want to make use of wp_remote_post().
$url = 'https://api.example.com/v1/property/search/';
$data_array = array(
'id_company' => 123456,
'api_token' => 'abcde_fgh'
);
$headers = array(
'APIKEY' => 1111111111,
'Content-Type' => 'application/json'
);
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => $headers,
'body' => $data_array,
'cookies' => array()
)
);
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Success! Response:<pre>';
print_r( $response );
echo '</pre>';
}

Using cURL to get JSON from an API returns nothing

I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);

You must log in before using this part of Bugzilla, code:410

I am able to get the GET request working but having issues related to authentication in POST and PUT request. I am getting the error "You must log in before using this part of Bugzilla". I have provided the correct username and password. I have tried CURLAUTH_ANY as well as CURLAUTH_BASIC. I have tried both PUT and POST request. Any help is appreciated.
$url ="http://localhost:8080/bugzilla/rest/bug/2";
$apikey = "IZC4rs2gstCal0jEZosFjDBRV9AQv2gF0udh4hgq";
$data = array(
"product" => "TestProduct",
"component" => "TestComponent",
"version" => "unspecified",
"summary" => "This is a test bug - please disregard",
"alias" => "SomeAlias",
"op_sys" => "All",
"priority" => "P1",
"rep_platform" => "All"
);
$str_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-Type: application/json", "Accept: application/json"));
$username = 'ashish.sureka#in.abb.com';
$password = 'abbincrc';
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo $result
Following code solved my problem. I have written a blog on it which might be useful to others encountering the same problem.
<?php
$url = 'http://localhost:8080//bugzilla/xmlrpc.cgi';
$ch = curl_init();
$header = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: text/xml', 'charset=utf-8' )
);
curl_setopt_array($ch, $header);
$bugreport = array(
'login' => 'ashish.sureka#in.abb.com',
'password' => 'abbincrc',
'product' => "TestProduct",
'component' => "TestComponent",
'summary' => "Bug Title : A One Line Summary",
'assigned_to' => "ashish.sureka#in.abb.com",
'version' => "unspecified",
'description' => "Bug Description : A Detailed Problem Description",
'op_sys' => "All",
'platform' => "All",
'priority' => "Normal",
'severity' => "Trivial"
);
$request = xmlrpc_encode_request("Bug.create", $bugreport);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_exec($ch)
?>

Paypal API, Curl not returning any output

I'm trying to figure out the paypal API, and I have the following code, which should make a call, get an access token, and then make the API call. The first part works(up until the $accesstoken line), and returns the access token properly, but the second part doesn't return anything. The code this is supposed to mimic can be found here: Make Your First Call
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";
$headers = array(
'Accept' => 'application/json',
'Accept-Language' => 'en_US',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $clientID . ':' . $clientSecret);
$curl = curl_exec($ch);
$x = json_decode($curl, TRUE);
print_r($x);
$accesstoken = $x['access_token'];
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer' . $accesstoken
);
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(
"transactions" => array(
"total" => ".99",
"currency" => "USD"
)
)
);
$saleurl = "https://api.sandbox.paypal.com/v1/payments/payment";
$sale = curl_init();
curl_setopt($sale, CURLOPT_URL, $saleurl);
curl_setopt($sale, CURLOPT_VERBOSE, TRUE);
curl_setopt($sale, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($sale, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($sale, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($sale, CURLOPT_HTTPHEADER, $headers2);
$finalsale = curl_exec($sale);
$verb = json_decode($finalsale, TRUE);
print_r($verb);
Curl doesn't make complete sense to me, any help would be appreciated.
UPDATE:
I changed the format of the headers to:
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
as per one of the answers. Now it is displaying:
[name] => MALFORMED_REQUEST
[message] => Incoming JSON request does not map to API request
[information_link] => https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST
[debug_id] => f53a882702a04
You are not setting your headers correctly ...
$headers = array(
'Accept: application/json',
'Accept-Language: en_US'
);
and
$headers2 = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $accesstoken
);
Is the correct format.
Also note the (space) after Bearer inbetween your $accesstoken
Edit: Update for your JSON ( i think this is right but echo it out and check it against the reference, I might have one to many array()
$data = array(
"intent" => "sale",
"redirect_urls" => array(
"return_url" => "http://example.com/your_redirect_url/",
"cancel_url" => "http://example.com/your_cancel_url/"
),
"payer" => array(
"payment_method" => "paypal"
),
"transactions" => array(array(
"amount" => array(
"total" => ".99",
"currency" => "USD"
)
)
)
);
You need a space here
$headers2 = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $accesstoken // Added a space after Bearer
);
See if it works now
Change
curl_setopt($sale, CURLOPT_POSTFIELDS, json_encode($data));
to
curl_setopt($sale, CURLOPT_POSTFIELDS, $data);
The json encode function breaks it

How can I forward $_POST with PHP and cURL?

I receive a POST request at my PHP script and would like to forward this POST call to another script using POST too. How can I do this?
I can use cURL if it's required for this action.
Perhaps:
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
From curl_setopt:
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
Do this,
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($_POST));
Here's a fully functional cURL request that re-routes $_POST where you want (based on ZZ coder's reply)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://urlOfFileWherePostIsSubmitted.com");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// ZZ coder's part
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$response = curl_exec($ch);
curl_close($ch);
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If need any HTTP authentication
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This can be $arrPostData = $_POST;
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your POST data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // ONLY use this when requesting JSON data
$arrResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // ONLY use this when request json data
),
// If HTTP authentication is required , use the below lines
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));

Categories