How to submit contact form 7 programmatically - wordpress

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

Related

Send file via Buzz\Browser

I'm using Symfony with Buzz\Browser vendor, I need to send file to my Slack channel via POST. This's the Slack method that I should call: Slack file upload
This's my code:
public function uploadFile(array $channels, File $file, $initial_comment = '', $title = '') {
$channels = implode(',', $channels);
$headers['Content-Type'] = 'multipart/form-data';
$content = json_encode(array(
'channels' => $channels,
'file' => new FormUpload($file->getPathname()),
'filename' => $file->getFilename(),
'filetype' => $file->getExtension(),
'initial_comment' => $initial_comment,
'title' => $title
));
return $this->post('/files.upload', $headers, $content);
}
Post method:
public function post($endpoint, $headers = array(), $content = '') {
$headers['Authorization'] = sprintf('Bearer %s', $this->getToken());
return $this->browser->post($this->url . $endpoint, $headers, $content);
}
I receive the response error message: invalid_form_data
EDIT:
I find this solution: How to send file data as post parameter in BuzzBrowser post call
and works fine, but is there a way to send file via Buzz's post method?

Wordpress User Data sent through cURL

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

Custom WooCommerce Gateway

I`m trying to develop a custom payment gateway for WooCommerce plugin, but I have a problem with the checkout page. What I want is to insert a form on the checkout final step page that is submitted automatically after 5 seconds.
My code is:
...
add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
add_action('woocommerce_api_wc_' . $this->id, array($this, 'handle_callback'));
}
function handle_callback() {
wp_die('handle_callback');
}
function receipt_page( $order )
{
echo "receipt page";
$this->generate_submit_form_elements( $order );
}
The problem is that "receipt_page" action is not triggered.
Thanks!
oh, its because you forgot to set the has_fields flag to true.
//after setting the id and method_title, set the has_fields to true
$this -> id = 'kiwipay';
$this -> method_title = 'KiwiPay';
$this->has_fields = true; // if you want credit card payment fields to show on the users checkout page
then in the process_payment function put this:
// Payload would look something like this.
$payload = array(
"amount" => $order.get_total(),
"reference" => $order->get_order_number(),
"orderid" => $order->id,
"return_url" => $this->get_return_url($order) //return to thank you page.
);
response = wp_remote_post( $environment_url, array(
'method' => 'POST',
'body' => http_build_query( $payload ),
'timeout' => 90,
'sslverify' => false,
) );
// Retrieve the body's response if no errors found
$response_body = wp_remote_retrieve_body( $response );
$response_headers = wp_remote_retrieve_headers( $response );
//use this if you need to redirect the user to the payment page of the bank.
$querystring = http_build_query( $payload );
return array(
'result' => 'success',
'redirect' => $environment_url . '?' . $querystring,
);

Closure Compiler RESTFul API output_info Parameter

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

Send URL with wp_remote_post not working

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.

Resources