Reputation: 1
I am trying to pass customer orders if they are from a particular category using the REST API from one woocommerce store to another.
I think there is a problem with how I am authenticating. I'm new to php, so I'm not sure how to authenticate to another woocommerce store with the consumer key and secret when I'm writing code in the functions.php file.
What is the proper format to authenticate when writing code in the functions.php file? And yes, I've looked at the official WOO REST API documentation, but am still not sure.
add_action( 'woocommerce_payment_complete', 'my_api_call');
function my_api_call( $order_id ){
// Order Setup Via WooCommerce
$order = new WC_Order( $order_id );
// Iterate Through Items
$items = $order->get_items();
foreach ( $items as $item ) {
// Store Product ID
$product_id = $item['product_id'];
$product = new WC_Product($item['product_id']);
// Check for "categoryx" Category and Run
if ( has_term( 'categoryx', 'product_cat', $product_id ) ) {
$name = $order->billing_first_name;
$surname = $order->billing_last_name;
$email = $order->billing_email;
$projectsku = $product->get_sku();
$apikey ="astringoflettersandnumbers";
// API Callout to URL
$url = 'https://mystagingsite/wp-json/wc/v3/orders/';
$body = array(
"Project" => $projectsku,
"Name" => $name,
"Surname" => $surname,
"Email" => $email,
"KEY" => $apikey
);
$response = wp_remote_post( $url,
array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'method' => 'POST',
'timeout' => 75,
'body' => json_encode($body),
)
);
$vars = json_decode($response['body'],true);
}
}
}
Expected: customer order is passed to store Result: customer order is not passed to store
Upvotes: 0
Views: 2055
Reputation: 703
This should have what you're looking for: https://woocommerce.github.io/woocommerce-rest-api-docs/#authentication-over-https. The idea here is HTTP basic access authentication:
a request contains a header field of the form
Authorization: Basic <credentials>
, wherecredentials
is the base64 encoding of id and password joined by a colon.
This means that you need to add an additional header to your headers
array:
'Authorization' => 'Basic '. base64_encode("user:password")
I don't have much PHP experience, so the syntax may be incorrect, but this is the gist. According to the Woocommerce documentation, user = consumer key and password = consumer secret, so make sure the "user:password"
string includes these actual values.
And if that doesn't work for some reason, it seems Woocommerce allows you to pass the parameters via url query strings, but this is less secure so don't use this unless you're sure the other method doesn't work.
https://www.example.com/wp-json/wc/v3/orders?consumer_key=123&consumer_secret=abc
Upvotes: 1