I need to export woocommerce order data using a POST request to a third-party url.I have this code in functions.php
add_action('woocommerce_thankyou', 'wdm_send_order_to_ext');
function wdm_send_order_to_ext ( $order_id ){
// get order object and order details
$order = new WC_Order( $order_id );
$email = $order->get_billing_email();
$phone = $order->get_billing_phone();
$shipping_type = $order->get_shipping_method();
$shipping_cost = $order->get_total_shipping();
// set the address fields
$user_id = $order->get_user_id();
$address_fields = array('country',
'title',
'first_name',
'last_name',
'company',
'address_1',
'address_2',
'address_3',
'address_4',
'city',
'state',
'postcode');
$address = array();
if(is_array($address_fields)){
foreach($address_fields as $field){
$address['billing_'.$field] = get_user_meta( $user_id, 'billing_'.$field, true );
$address['shipping_'.$field] = get_user_meta( $user_id, 'shipping_'.$field, true );
}
}
// set the username and password
$api_username = 'username';
$api_password = 'password';
// setup the data which has to be sent
$data = array(
'username' => $api_username,
'password' => $api_password,
'name1' => $address['billing_first_name'],
'street' => $address['billing_address_1'],
'city' => $address['billing_city'],
'country' => $address['billing_country'],
'pcode' => $address['billing_postcode'],
'phone' => $phone,
'weight' => 4.0,
'parcel_type' => 'D',
'num_of_parcel' => 1
);
// send API request via cURL
$curl = curl_init();
/* set the complete URL, to process the order on the external system. Let’s consider http://example.com/buyitem.php is the URL, which invokes the API */
curl_setopt($curl, CURLOPT_URL, "https://easyship.si/api/parcel/parcel_import");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($curl);
curl_close ($curl);
}
However, it does not pass the request, the third-party API does not receive anything. WP_DEBUG doesn't see any errors. Tell me where to look, what is wrong?
You can use https://requestbin.com/ as endpoint to see data you are posting and if they are being posted correctly. If it successfully posting it to requestbin endpoint you can see the header and body formats as well. If its not working try debugging line by line.
Sorry I wasn't able to add this as comment
Related
I want to redirect my buyers to my second website 'B' to make payment for my product on website 'A' and after successful payment on website 'B', it should automatically update the order status on website 'A' as the order is completed. I am using woo commerce plugin for my websites. Please any plugins, Add-ons, or custom code suggestions. please I need help
Site 'A'
function action_woocommerce_new_order( $order_id ) {
//get all order details by $order_id
//post your data to site B
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://yoursiteB.com/wp-json/api/v2/create_wc_order");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2");
// In real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
};
add_action( 'woocommerce_payment_complete', 'action_woocommerce_new_order', 10, 1 );
Site 'B'
Class WC_Rest_API {
public function __construct() {
add_action( 'rest_api_init', array( $this, 'init_rest_api') );
}
public function init_rest_api() {
register_rest_route('api/v2', '/create_wc_order', array(
'methods' => 'POST',
'callback' => array($this,'create_wc_order'),
));
}
public function create_wc_order( $data ) {
//$data - all the details needs to be send from site A
global $woocommerce;
$user_id = $data['user_id'];
$user = get_user_by( 'ID', $user_id);
$phonenumer = get_user_meta( $user_id,'user_phoneno', true);
if($user) {
$address = array(
'first_name' => $user->display_name,
'last_name' => $user->display_name,
'email' => $user->user_email,
'phone' => $phonenumer,
);
$order = wc_create_order();
//get product details from rest api site A
$order->add_product();
$order->set_address( $address, 'billing' );
$order->calculate_totals();
$order = wc_get_order( $order->id );
$response['status'] = 'success';
$response['message'] = 'Order created on wordpress site B.';
return new WP_REST_Response($response, 200);
}
}
}
$rest_api = new WC_Rest_API();
this doesn't work as it create product on the second website.
I want to use the second website to make only payment if it can pull user data and order id only
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 created custom PHP file in WordPress to send order data to an accounting server via its web service.
Now I need to take amount of goods from that accounting server and update the stock of each product.
I do not access that server, and they don't have any document for their web-service.
I tried to find some info about using web service to do this, but the only thing that I got was to send (not receiving) data of a WordPress site via web service.
This is my code that send order details to accounting server:
<?php
require_once('../wp-config.php');
require_once('../wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-order.php');
$today = new DateTime();
$today->setTime( 0, 0, 0 );
$args = array(
'limit' => 9999,
'return' => 'ids',
'date_completed' => $today,
'status' => 'completed'
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
$url = "http://###.###.###.###:8081/Service1.svc/InsertInvoice";
foreach( $orders as $order_id ) {
$order = wc_get_order( $order_id );
$order_date_completed = $order->get_date_completed();
if (false === strtotime($order_date_completed)) {
echo 'Invalid date for order number '.$order_id.'<br>';
}else {
$order_date_completed->setTime( 0, 0, 0 );
$diff = $today->diff( $order_date_completed );
$diffDays = (integer)$diff->format( "%R%a" );
if($diffDays == 0){
$items = $order->get_items();
$InvoiceInfo = array();
foreach( $items as $item ){
$product = $item->get_product();
$item_sku = $product->get_sku();
$saleType = substr($item_sku, 1, 2);
$item_code = substr($item_sku, 3, 8);
$user_id = substr($item_sku, 11, 6);
$data2 = array(
'CustomerCode' => $user_id,
'SaleTypeNumber' => $saleType,
'ItemCode' => $item_code,
'Quantity' => $item->get_quantity(),
'Fee' => $product->get_price(),
'Discount' => 0,
'Addition' => 0,
'Tax' => 0,
'Duty' => 0,
'Rate' => 1,
'StockCode' => 5,
);
array_push($InvoiceInfo,$data2);
}
$postdata = json_encode($InvoiceInfo);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
}
}
}
?>
In order to send data to WooCommerce, you can use WordPress REST API custom endpoint that can receive data from anywhere.
But, as you didn't provide the name of the accounting server or even any information about the accounting app, you have to check if it is possible to send data from your accounting app to a webhook (with a service like Zapier).
How can I use wp_remote_post to send SMS from Twilio?
The code below work nice, but it need to be done with WordPress HTTP API using wp_remote_post
function send_twilio_text_msg($id, $token, $from, $to, $body)
{
$url = "https://api.twilio.com/2010-04-01/Accounts/".$id."/SMS/Messages";
$data = array (
'From' => $from,
'To' => $to,
'Body' => $body,
);
$post = http_build_query($data);
$x = curl_init($url );
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($x, CURLOPT_USERPWD, "$id:$token");
curl_setopt($x, CURLOPT_POSTFIELDS, $post);
$y = curl_exec($x);
curl_close($x);
print_r($y);
}
To make a call to the Twilio API using wp_remote_post you need to do a few things:
Create the URL, as you did in your example
Collect the data you want to send (your From, To, and Body from your example)
Create an Authorization header out of your Account Sid and Auth Token. To do so, you need an array with one key, Authorization and the value made from base 64 encoding the Account Sid and Auth Token concatenated with a colon.
The $url is the first argument to wp_remote_post the second argument is an associative array with body and headers properties.
See the example below:
function send_twilio_text_msg($id, $token, $from, $to, $body)
{
$url = "https://api.twilio.com/2010-04-01/Accounts/".$id."/SMS/Messages";
$data = array(
'From' => $from,
'To' => $to,
'Body' => $body
);
$headers = array(
'Authorization' => 'Basic ' . base64_encode($id . ':' . $token)
);
$result = wp_remote_post($url, array(
'body' => $data,
'headers' => $headers
));
}
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);