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.
Related
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;
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()
im pretty stuck.. Im trying to get all post data from a specific category ID, using Wordpress REST API. But it dosen't output the content, only the ID & Title.. Cant see what I am doing wrong..
Heres the code:
/* Register Route http://dev.mpblogg.se/wp-json/api/v1/feedposts/id */
add_action( 'rest_api_init', function () {
register_rest_route( 'api/v1', '/feedposts/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'getAllPostsfromCategory',
));
});
/* Get all posts from the specific Caetgory */
function getAllPostsfromCategory( $data ) {
$secret = '2lpMh5EHaEiavhMONpWD';
$qs = explode('&', $_SERVER['QUERY_STRING'])[0];
$qs = explode('=', $qs)[1];
if($qs != $secret){
return false;
}
$posts = get_posts( array(
'category' => $data['id'],
));
$returnArray = array();
foreach($posts as $post) {
array_push($returnArray, array(
'id' => $post->ID,
'title' => $post->post_title,
'content' => $post->post_content
));
}
// die();
if(empty($posts)){
return null;
}
return $returnArray;
}
The JSON output looks like this:
After changing to array_push($returnArray,$post); it looks like this:
Okay... here's a clue that I got from the array_push image that you shared. The last string of the JSON output reads:
"filer": "raw"
This means that the resultant value would be stored as a raw, unfiltered content of the post.
So, you can try adding apply_filters() to the extracted content and see if it helps you display the required content.
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
This is used to apply the content filters to raw unfiltered post content, which usually comes from the use of $post->post_content .
As usual the answer why it didnt work is so dumb. Im not using the the_content.. Im using a custom field from ACF called post_excerpt. So I just added:
'excerpt' => get_field('post_excerpt', $post->ID),
Now it works.. Sorry all, but thank's for all the help.
I've just integrated the marketing tool Klaviyo with our Wordpress/WooCommerce set up and I'm trying to push user meta data through a cURL API - but failing!
You can find out how the API works here: https://www.klaviyo.com/docs/http-api#people
I'm hoping to add an action so when the user profile saves, it hooks in my function sending the meta data through to Klaviyo.
Can anyone see what I've done wrong please - code below?
Thanks so much in advance.
Linz
<?php
// Hook into the action which saves the User Meta Data (written by LD)
add_action( 'personal_options_update', 'klaviyo_send' );
add_action( 'edit_user_profile_update', 'klaviyo_send' );
function klaviyo_send () {
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://a.klaviyo.com/api/identify?data=eyJ0b2tlbiI6ICJoYXFYaXEiLCAicHJvcGVydGllcyI6IHsiJGVtYWlsIjogInRob21hcy5qZWZmZXJzb25AZXhhbXBsZS5jb20iLCAiJGxhc3RfbmFtZSI6ICJKZWZmZXJzb24iLCAiUGxhbiI6ICJUcmlhbCIsICJTaWduIFVwIERhdGUiOiAiMjAxMy0wMS0yNyAxMjoxNzowNiIsICIkZmlyc3RfbmFtZSI6ICJUaG9tYXMifX0=',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'token' => 'haqXiq', //This is the public 'key' in Klaviyo
'$email' => $user_id->email, //This translates the wordpress field into the Klaviyo field
'twitter' => $user_id->twitter,
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
}
?>
Try sending data by this way .. change the posted data to url friendly ways like ?key=value&key=value&key=value
//extract data from the post
//set POST variables
$url = 'https://a.klaviyo.com/api/identify?data=eyJ0b2tlbiI6ICJoYXFYaXEiLCAicHJvcGVydGllcyI6IHsiJGVtYWlsIjogInRob21hcy5qZWZmZXJzb25AZXhhbXBsZS5jb20iLCAiJGxhc3RfbmFtZSI6ICJKZWZmZXJzb24iLCAiUGxhbiI6ICJUcmlhbCIsICJTaWduIFVwIERhdGUiOiAiMjAxMy0wMS0yNyAxMjoxNzowNiIsICIkZmlyc3RfbmFtZSI6ICJUaG9tYXMifX0=';
$fields = array(
'token' => 'haqXiq', //This is the public 'key' in Klaviyo
'$email' => $user_id->email, //This translates the wordpress field into the Klaviyo field
'twitter' => $user_id->twitter,
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
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
));