I am trying to write my first REST API with PHP. We want to send shipping data to the shipping company and get labels for printing in return. The shipping company has given me test api credentials.
So I started to write a plugin with this code inside:
$url = "https://mywebsite/endpoint/";
$username = "myusername";
$password = "mypassword";
$data = array(
'key1' => 'value1',
'key2' => 'value2'
);
$response = wp_remote_post( $url, array(
'body' => $data,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
),
)
);
var_dump($response); // not being called
When I run this code, I get a white screen with no error message, the last line with var_dump($response) is not being called. I am a bit stuck here because I se no success and no error...what could it be? Why this behaviour of the remote server? Does it mean "sorry, wrong credentials" or "data has the wrong format"? I have the feeling that the server doesn't even notice that I'm trying to contact him...
I tried a number of other variatons of the above code that I found somwehere online, and also outside of WordPress, but no success.
The shipping company gave me a documentation. It says:
HTTP Method: POST
Authentication Header: Basic Authentication (user name/ password)
so I thought I could do no wrong when trying that. Hm.
I found a solution, so I can share it here with you.
I installed the free Software Postman and created a simple POST query there. After entering $url, $username and $password I ran a query and it worked well. the good thing abort Postman is that it creates code snippets for you. "very_long_cryptic_string" is obviously created from $username and $password. The PHP for my case goes like this, and it works:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic very_long_cryptic_string'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Related
I want to use POST methon from REST API tu update a user profile from a backend website to FrontEnd WordPress. The next code is suppose to update the name, description and the slug.
if (isset($_POST['update_frontend'])) {
$url = $setting['front_end_host_wp'].'users/'.$item_id.'/';
$data1 = array(
'description' => $data['content'],
'name' => $data['nume'],
'slug' => $data['slug'],
'parent' => 0,
'meta' => array()
);
$result = $df->runGuzzle('POST', $url, $data1);
printpre($result);
}
I want to update the user_status(Approved, Pending or Denied) and other info like, name, email etc. But the code above is not working.
I want to submit contact form by custom function
The code below is getting the instance of form but when submitted. It submit the form but not the fields which I wanted.
$item = wpcf7_contact_form( $formId );
$result = $item->submit();
Here where I can pass the fields I define in admin panel like "textarea-123" & "email-234" ?
I did not get exact answer for what I look but I found the alternate solution.
function cf7Submit($formId , $args) {
$url = 'http://example.com/wp-json/contact-form-7/v1/contact-forms/'.$formId.'/feedback';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'body' => $args
)
);
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
}
I can call this function like this:
cf7Submit(128, array(
'textarea-123' => 'test email',
'email-234' => 'asd#asd.com'));
#daraptoor has found a good solution, but as #davevsdave noticed in the comment, it does not work properly in CF7 5.6.
Error 415 is caused by added to API check for content type passed into a request header:
// part of create_feedback() from CF7's rest-api.php
if ( ! str_starts_with( $content_type, 'multipart/form-data' ) ) {
To figure it out, just add the expected content type into a request header:
$response = wp_remote_post( $url, array(
'method' => 'POST',
'headers' => array(
'Content-Type' => 'multipart/form-data'
),
'body' => $args
)
);
UPD
Faced with an issue, that wp_remote_post() send data in body and not in POST, so CF7 API does not get any fields. It is caused because the WP's function uses http_build_query() (read more here).
I have used cURL request as a workaround:
// Same user agent as in regular wp_remote_post().
$userAgent = 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url');
// Note that Content-Type wrote in a bit different way.
$header = ['Content-Type: multipart/form-data'];
// Same array with fields to pass, not changed.
$body = ['foo' => 'bar'];
$curlOpts = [
// Send as POST
CURLOPT_POST => 1,
// Get a response data instead of true
CURLOPT_RETURNTRANSFER => 1,
// CF7 will reject your request as spam without it.
CURLOPT_USERAGENT => $userAgent,
CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $body,
];
$ch = curl_init($apiUrl); // Create a new cURL resource.
curl_setopt_array($ch, $curlOpts); // Set options.
$response = curl_exec($ch); // Grab response.
if (!$response) {
// Do something if an error occurred.
} else {
$response = json_decode($response);
// Do something with the response data.
}
// Close cURL resource, and free up system resources.
curl_close($ch);
Hope it saves someones time :)
You can add a piece of JS code, like:
$("form.wpcf7").submit()
I'm trying to update the user meta with spaces registered on my website. I am using register_meta hook to register user meta. And for updating users using WordPress REST API I use wp_remote_post but the problem is when I tried to update a user meta with spaces it will add as array in response then it will add as new user meta.
For example the value of user meta is - community test
Sample Response:
[meta] => Array
(
[agent_community] => Array
(
[0] => community
[1] => test
)
)
Sample Code for registering user meta.
register_meta('user', 'agent_community', array(
"type" => "string",
"show_in_rest" => true
));
Update using wp_remote_post
$update_data = array('email'=> 'test#mail.com', 'meta[agent_community]' => 'community test');
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'username:password' ),
),
'body' => array_filter($update_data));
$update_url = 'https://test-url.com/wp-json/wp/v2/users/17';
$response = wp_remote_post( $update_url, $args);
Database:
Is there a way that can merge the array on user meta?
implode() might help you. And you can change spaces with HTML entities. Or use function like urledncode() / urlendecode() or something like this.
I'm using the Google Closure Compiler RESTFul API with WordPress.
The request is created using wp_remote_post() and so far everything went okay.
What I want to know is how to get the API to not only return the compiled code, but also the warnings, errors and statistics.
Supplying 'output_info' => array( 'compiled_code', 'warnings', 'errors', 'statistics' ) in the body parameter seems not to work and the API returns errors. Any ideas?
Thank you very much!
Just looked around and found out that Closure Compiler accepts output_info parameter multiple times. This is not possible with the WP_Http API without some modifications.
So I looked at the source of WP_Http and did the following, now it's working :)
// Default request data
$request_data = array(
'output_info' => array( 'compiled_code', 'warnings', 'errors', 'statistics' ),
'output_format' => 'json'
);
$request_data = array_merge( $request_data, $args, compact( 'js_code' ) );
// Process the request body manually to make same named parameters possible
$body = http_build_query( $request_data, null, '&' );
$body = preg_replace( '/output_info%5B\d+%5D=/', 'output_info=', $body );
// Initiate request
$response = wp_remote_post( CLOSURE_COMPILER_URL, array(
'sslverify' => false,
'timeout' => 10,
'headers' => array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' )
),
'body' => $body
));
I am using a service that accepts URL in this format...
http://www.mydomain.com/zone1/code/verify/?data1=Apple&data1=Banana&data3=Orange&data4=Pear
I am trying to use wp_remote_post to submit it and receive a response....
$url = 'http://www.mydomain.com/zone1/code/verify/';
$fields = array();
$fields['data1'] = 'Apple';
$fields['data2'] = 'Banana';
$fields['data3'] = 'Orange';
$fields['data4'] = 'Pear';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $fields,
'cookies' => array()
)
);
This isn't working and the response I am recieving back is that the fields are missing.
Can anyone see anything wrong with my approach and also is there an easy way to echo out exactly the URL it is sending?
This url:
http://www..../verify/?data1=Apple&data1=Banana&data3=Orange&data4=Pear
is in a GET format, not POST so you should check the API docs for that request, but it likely does not support the POST format so you will need to use the GET syntax, like so:
$url = 'http://www.mydomain.com/zone1/code/verify/';
$url .= '?data1=Apple';
$url .= '&data2=Banana';
$url .= '&data3=Orange';
$url .= '&data4=Pear';
$args = array(); //the default arguments should be ok unless the API needs something special like authentication headers
$response = wp_remote_get($url, $args);
I like to use the kint-debugger plugin to dig through output like this, using that you could call dd($response); and get a nicely formatted display of the response. Without that plugin, just add this afterwards:
print '<pre>';
print_r($repsonse);
die();
This should show everything in the response variable.