logo

Pablo Guides

איך לבנות לוח מחוונים מותאם ולחבר לחנות באמצעות ה-WooCommerce REST API

  1. ניכנס ללוח הניהול של החנות, עבור אל WooCommerce ← הגדרות והפעל REST API. עבור אל הכרטיסייה מפתח/אפליקציות והזן את תיאור המפתח, בחר את ההרשאה הרצויה (עבור הדרכה זו, בחרתי בקריאה/כתיבה). כעת לחץ על הלחצן 'צור מפתח API'.
  2. נקבל את מפתח ה-API, סוד ה-API וקוד QR לסריקה,

2. נשתמש במפתחות אלה בעתיד כדי לעבוד עם WooCommerce REST API. אבל לפני כל זה, נתקין את חבילת ה-PHP API עבור WooCommerce.

אנחנו נתקין את WooCommerce PHP Package API

ל-WooCommerce יש חבילת API רשמית (כתובה ב-PHP) שניתן להשתמש בה ליצירת אפליקציות מותאמות אישית. החבילה מתוחזקת היטב וזמינה ב-GitHub.

להתקנת חבילת ה-API, אני אפעיל אפליקציית PHP מ. לאחר שהיישום מופעל, נעבור אל מסוף הSSH באמצעות אישורי הבסיס שסופקו. ואז נעבור לאפליקציית ה-PHP שלנו ונפעל את הפקודה Composer להתקנת החבילה.

3. כעת נזין בתוך הטרמינל שלנו את הפקודה הבאה :

פקודה זו תתקין את הגרסה האחרונה של החבילה הזמינה ב-GitHub. אתה יכול גם למצוא את הקובץ composer.json בתיקייה שלך. לאחר מכן, צור קובץ index.php. אני אשתמש ב-Bootstrap וב-jQuery עבור ה-frontend. כמו כן, אשתמש ב-JavaScript. אז הוסף את הקוד הבא בתג HTML head:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
דרוש קבצי autoload.php ו-Dependency

לאחר התקנת החבילה,  עליך לדרוש autoload.php כדי לאתחל את הספרייה. לספריית API זו יש פונקציית HTTP לשליחת הבקשות ולקבלת התגובות. אוסיף את ספריית לקוח ה-HTTP ב-index.php:

<?php

דורש __DIR__ . '/vendor/autoload.php';

השתמש ב-Automatic\WooCommerce\Client;

השתמש ב-Automatic\WooCommerce\HttpClient\HttpClientException;

כעת, צור את האובייקט עבור הלקוח, ספק את מפתח הצרכן ואת סוד הצרכן שבו.

$woocommerce = new Client('http://woocommerce-71265-250265.cloudwaysapps.com/',

'ck_96212f68c4a260f2a38f2045161f266c90f4de67',

'cs_26ab2d971f3f2472c1b3a796bb25e97231c58599',

[

'wp_api' => true, 'version' => 'wc/v1',

]);

בשלב זה, אתה מוכן להשתמש בקריאות API עבור GET, POST, DELETE ו PUT כדי לעבוד עם הנתונים המאוחסנים. אתה יכול להשתמש ב-`var_dump($woocommerce);` כדי לבדוק אם ה-API מחזיר TRUE או FALSE.

קבל את כל ההזמנות בחנות

WooCommerce מציעה הרבה פונקציות ואני ממליץ לך לבדוק את התיעוד הרשמי לסיקור מפורט של הפונקציות הללו. עבור הדרכה זו, בחרתי כמה מהפונקציות הללו כולל הזמנות, לקוחות ומוצרים. ה-API מספק גם ניהול חריגים.

העברת אתר PHP הראשונה בחינם ב-Cloudways

מהנדסי Cloudways יכולים להעביר את האתר שלך ללא רבב

היגר עכשיו

כך ייראה לוח המחוונים. כפי שניתן לראות, לוח המחוונים יציג את ההזמנות, הלקוחות, המוצרים והמכירות הכוללות.

הוסף את הקוד הבא לקובץ index.php.

נסה {

$results = $woocommerce->get('orders');

$products = $woocommerce->get('products');

$customers = $woocommerce->get('customers');

$result = count($results);

$customer = count($customers);

$product = count($products);

//אתה יכול להגדיר כל תאריך שתרצה

$query = ['date_min' => '2017-10-01', 'date_max' => '2017-10-30'];

$sales = $woocommerce->get('reports/sales', $query);

$sale = $sales[0]["total_sales"];

}

catch(HttpClientException $e) {

$e->getMessage(); // הודעת שגיאה.

$e->getRequest(); // נתוני בקשה אחרונה.

$e->getResponse(); // נתוני התגובה האחרונה.

}

כדי להציג את התוצאות, אוסיף את הסימון הבסיסי הבא:

<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-1">

<h1 class="page-header">מרכז השליטה</h1>

<div class="row placeholders">

<div class="col-xs-6 col-sm-3 placeholder">

<p id="large">

<?php echo $result?>

</p>

<hr>

<span class="text-muted">סה"כ הזמנות</span>

</div>

<div class="col-xs-6 col-sm-3 placeholder">

<p id="large">

<?php echo $customer?>

</p>

<hr>

<span class="text-muted">לקוחות</span>

</div>

<div class="col-xs-6 col-sm-3 placeholder">

<p id="large">

<?php echo $product?>

</p>

<hr>

<span class="text-muted">כל המוצרים</span>

</div>

<div class="col-xs-6 col-sm-3 placeholder">

<p id="large">

<?php echo $sale?>

</p>

<hr>

<span class="text-muted">סה"כ מכירות</span>

</div>

</div>

</div>

זה די פשוט. השגתי את כל הערכים על ידי בקשת ה-API של WooCommerce והצגתי אותם בקפל המודגש לתצוגה מהירה. לטיפול בחריג, השתמשתי בשיטות נסיון-תפיסה.

קבל את כל ההזמנות דרך API

generate api key

You will get the API Key, API Secret and QR code to scan,

api key

I will use these keys in the future to work with the WooCommerce REST API.  But before all this, I will install the PHP API package for WooCommerce.

Want to Test Your Changes on Free Staging URLs?

Try Cloudways managed WooCommerce hosting for a hassle-free experience.

Install WooCommerce PHP Package API

WooCommerce has an official API package (written in PHP) that can be used for creating custom apps. The package is well maintained and available on GitHub.

For installing the API package, I will launch a PHP stack app. Once the application is up, go to the SSH terminal using the provided Master Credentials. Move to your PHP application and run the Composer command for installing the package.

  1. composer require automattic/woocommerce

This command will install the latest version of the package available on GitHub. You can also find the composer.json file in your folder. Next, create an index.php file. I will use Bootstrap and jQuery for the frontend. Also, I will use JavaScript. So add the following code in the HTML head tag:

  1. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  2.  
  3. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  4.  
  5. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Require autoload.php and Dependency Files

After installing the package,  you need to require autoload.php for initializing the library. This API library has an HTTP function for sending the requests and getting the responses. I will add the HTTP client library in the index.php:

  1. <?php
  2.  
  3. require __DIR__ . '/vendor/autoload.php';
  4.  
  5.  
  6. use Automattic\WooCommerce\Client;
  7.  
  8. use Automattic\WooCommerce\HttpClient\HttpClientException;

Now, create the object for Client, providing the Consumer key and the consumer secret in it.

  1. $woocommerce = new Client('http://woocommerce-71265-250265.cloudwaysapps.com/',
  2.  
  3. 'ck_96212f68c4a260f2a38f2045161f266c90f4de67',
  4.  
  5. 'cs_26ab2d971f3f2472c1b3a796bb25e97231c58599',
  6.  
  7. [
  8.  
  9. 'wp_api' => true, 'version' => 'wc/v1',
  10.  
  11. ]);

At this point, you are all set to use API calls for GET, POST, DELETE, and PUT to work with the stored data. You can use `var_dump($woocommerce);` to check if the API return TRUE or FALSE.

api return boolean

Get All Orders at the Store

WooCommerce offers a lot of functions and I would recommend you check out the official documentation for detailed coverage of these functions. For this tutorial, I have selected a few of these functions including orders, customers, and products. The API also provides exception management.

First PHP Website Migration Is Free At Cloudways

Cloudways Engineers can migrate your website Flawlessly

Here is how the Dashboard will look like. As you could see the Dashboard will display the orders, customers, products, and total sales.

woocommerce dashboard in php api

Add the following code to the index.php file.

  1. try {
  2.  
  3.  
  4.  
  5. $results = $woocommerce->get('orders');
  6.  
  7. $products = $woocommerce->get('products');
  8.  
  9. $customers = $woocommerce->get('customers');
  10.  
  11.  
  12.  
  13. $result = count($results);
  14.  
  15. $customer = count($customers);
  16.  
  17. $product = count($products);
  18.  
  19.  
  20.  
  21. //you can set any date which you want
  22.  
  23. $query = ['date_min' => '2017-10-01', 'date_max' => '2017-10-30'];
  24.  
  25. $sales = $woocommerce->get('reports/sales', $query);
  26.  
  27. $sale = $sales[0]["total_sales"];
  28.  
  29. }
  30.  
  31.  
  32.  
  33. catch(HttpClientException $e) {
  34.  
  35. $e->getMessage(); // Error message.
  36.  
  37. $e->getRequest(); // Last request data.
  38.  
  39. $e->getResponse(); // Last response data.
  40.  
  41. }

To show the results, I will add the following basic markup:

  1. <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-1">
  2.  
  3. <h1 class="page-header">Dashboard</h1>
  4.  
  5.  
  6.  
  7. <div class="row placeholders">
  8.  
  9. <div class="col-xs-6 col-sm-3 placeholder">
  10.  
  11. <p id="large">
  12.  
  13. <?php echo $result?>
  14.  
  15. </p>
  16.  
  17. <hr>
  18.  
  19. <span class="text-muted">Total Orders</span>
  20.  
  21. </div>
  22.  
  23. <div class="col-xs-6 col-sm-3 placeholder">
  24.  
  25. <p id="large">
  26.  
  27. <?php echo $customer?>
  28.  
  29. </p>
  30.  
  31. <hr>
  32.  
  33.  
  34.  
  35. <span class="text-muted">Customers</span>
  36.  
  37. </div>
  38.  
  39. <div class="col-xs-6 col-sm-3 placeholder">
  40.  
  41. <p id="large">
  42.  
  43. <?php echo $product?>
  44.  
  45. </p>
  46.  
  47. <hr>
  48.  
  49. <span class="text-muted">All Products</span>
  50.  
  51. </div>
  52.  
  53. <div class="col-xs-6 col-sm-3 placeholder">
  54.  
  55. <p id="large">
  56.  
  57. <?php echo $sale?>
  58.  
  59. </p>
  60.  
  61. <hr>
  62.  
  63. <span class="text-muted">Total Sales</span>
  64.  
  65. </div>
  66.  
  67. </div>
  68.  
  69. </div>

This is pretty simple. I got all the values by requesting the WooCommerce API and displayed them in the highlighted fold for a quick display. For exception handling, I have used try-catch methods.

Get all Orders via API

You can get all orders through the following single line of code:

  1. $results = $woocommerce->get('orders');

Now I will show the order summary in an organized table through the following table code:

  1. <div class="container">
  2.  
  3. <h2 class="sub-header">Orders List</h2>
  4.  
  5. <div class='table-responsive'>
  6.  
  7. <table id='myTable' class='table table-striped table-bordered'>
  8.  
  9. <thead>
  10.  
  11. <tr>
  12.  
  13. <th>Order #</th>
  14.  
  15. <th>Customer</th>
  16.  
  17. <th>Address</th>
  18.  
  19. <th>Contact</th>
  20.  
  21. <th>Order Date</th>
  22.  
  23. <th>Status</th>
  24.  
  25. <th>Actions</th>
  26.  
  27. </tr>
  28.  
  29. </thead>
  30.  
  31. <tbody>
  32.  
  33. <?php
  34.  
  35. foreach($results as $details){
  36.  
  37.  
  38.  
  39. echo "<tr><td>" . $details["id"]."</td>
  40.  
  41. <td>" . $details["billing"]["first_name"].$details["billing"]["last_name"]."</td>
  42.  
  43. <td>" . $details["shipping"]["address_1"]."</td>
  44.  
  45. <td>" . $details["billing"]["phone"]."</td>
  46.  
  47. <td>" . $details["date_created"]."</td>
  48.  
  49. <td>" . $details["status"]."</td>
  50.  
  51. <td><a class='open-AddBookDialog btn btn-primary' data-target='#myModal' data-id=".$details['id']." data-toggle='modal'>Update</a>
  52.  
  53. <a class='open-deleteDialog btn btn-danger' data-target='#myModal1' data-id=".$details['id']." data-toggle='modal'>Delete</a></td></tr>";
  54.  
  55. }
  56.  
  57. ?>
  58.  
  59. </tbody>
  60.  
  61. </table>
  62.  
  63. </div>
  64.  
  65. </div>

In this table, I haven’t displayed all the data. You could extend the display as per your requirements. At this time, the Order table will look like this:

orders list

Update the Order Status

For order status, I have added two options Update and Delete. Normally when an order is placed, it defaults state is processing. As the order moves to the next state,  you can always update the status to reflect the changes. For this purpose, I will pass the order ID to the buttons in this format: `data-id=”.$details[‘id’]`. Now I will catch this ID in a Bootstrap modal and select the state for this order. The modal code will be:

  1. <div class="modal fade" id="myModal" role="dialog">
  2.  
  3. <div class="modal-dialog">
  4.  
  5.  
  6.  
  7. <!– Modal content–>
  8.  
  9. <div class="modal-content">
  10.  
  11. <div class="modal-header">
  12.  
  13. <button type="button" class="close" data-dismiss="modal">&times;</button>
  14.  
  15. <h4 class="modal-title">Modal Header</h4>
  16.  
  17. </div>
  18.  
  19. <div class="modal-body">
  20.  
  21. <p>Some text in the modal.</p>
  22.  
  23. <form action="" method="post">
  24.  
  25. <div class="form-group">
  26.  
  27. <input type="text" class="form-control" name="bookId" id="bookId" value="">
  28.  
  29.  
  30.  
  31. <label for="sel1">Select list (select one):</label>
  32.  
  33. <select class="form-control" id="status" name="ostatus">
  34.  
  35. <option>Pending Payment</option>
  36.  
  37. <option>processing</option>
  38.  
  39. <option>On Hold</option>
  40.  
  41. <option>completed</option>
  42.  
  43. <option>Cancelled</option>
  44.  
  45. <option>Refunded</option>
  46.  
  47. <option>Failed</option>
  48.  
  49. </select>
  50.  
  51.  
  52.  
  53. </div>
  54.  
  55.  
  56.  
  57. <div class="modal-footer">
  58.  
  59. <button type="submit" class="btn btn-block" name="btn-update">Update</button>
  60.  
  61. </div>
  62.  
  63. </form>
  64.  
  65. </div>
  66.  
  67. </div>
  68.  
  69. </div>
  70.  
  71. </div>

Nothing fancy in it. I have assigned the name and ID’s to the input type and select box. Next, I will add jquery to catch the order ID in the modal.

  1. <script>
  2.  
  3. $(document).on("click", ".open-AddBookDialog", function() {
  4.  
  5. var myBookId = $(this).data('id');
  6.  
  7. $(".modal-body #bookId").val(myBookId);
  8.  
  9. });
  10.  
  11. </script>

In the above script, I am simply assigning the data-id value to the input box using the input box ID. Next, for updating the status of the order I need to add PHP code to create a POST call.

  1. if (isset($_POST['btn-update'])) {
  2.  
  3. $status = $_POST['bookId'];
  4.  
  5. $st = $_POST['ostatus'];
  6.  
  7.  
  8.  
  9. $woocommerce->put('orders/' . $status, array(
  10.  
  11. 'status' => $st
  12.  
  13. ));
  14.  
  15. header('Location: https://shahroznawaz.com/woo');
  16.  
  17. }

This code is pretty simple. The condition will check the submitted form and catch the values. Next, I have appended the order ID to order URL because the update URL need the order ID with the order call, something similar to this: (orders/order-ID, orders/16)

Now, when you click on the Update button, it will show the order ID and you can select the order state and update it:

update order

Delete a Specific Order

For deleting a specific order, I will use the same logic of showing Order ID in modal, and taking the user’s confirmation for deleting the order or canceling the action. The modal code will be:

  1. <div class="modal fade" id="myModal1" role="dialog">
  2.  
  3. <div class="modal-dialog">
  4.  
  5.  
  6.  
  7. <!– Modal content–>
  8.  
  9. <div class="modal-content">
  10.  
  11. <div class="modal-header">
  12.  
  13. <button type="button" class="close" data-dismiss="modal">&times;</button>
  14.  
  15. <h4 class="modal-title">Modal Header</h4>
  16.  
  17. </div>
  18.  
  19. <div class="modal-body">
  20.  
  21. <p>Some text in the modal.</p>
  22.  
  23. <form action="" method="post">
  24.  
  25. <div class="form-group">
  26.  
  27. <input type="text" class="form-control" name="cId" id="cId" value="">
  28.  
  29. </div>
  30.  
  31.  
  32.  
  33. <div class="modal-footer">
  34.  
  35. <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
  36.  
  37. <button type="submit" class="btn btn-danger" name="btn-delete">Delete</button>
  38.  
  39. </div>
  40.  
  41. </form>
  42.  
  43. </div>
  44.  
  45. </div>
  46.  
  47. </div>
  48.  
  49. </div>

The jquery code for it:

  1. <script>
  2.  
  3. $(document).on("click", ".open-deleteDialog", function() {
  4.  
  5. var myBook = $(this).data('id');
  6.  
  7. $(".modal-body #cId").val(myBook);
  8.  
  9. });
  10.  
  11. </script>

The PHP code snippet for deleting the order through the Delete button is:

  1. if (isset($_POST['btn-delete'])) {
  2.  
  3. $oid = $_POST['cId'];
  4.  
  5. $woocommerce->delete('orders/' . $oid, ['force' => true]);
  6.  
  7. header('Location: https://shahroznawaz.com/woo');
  8.  
  9. }

Click the Delete button to delete the order or the Cancel button if you don’t want to do it.

order deletion

Get All Customers

All the customers can be retrieved using the following GET call:

  1. $customers = $woocommerce->get('customers');

Now to show the details of the customer, add one more Bootstrap container with the table:

  1. <div class="container">
  2.  
  3. <h2 class="sub-header">Customers List</h2>
  4.  
  5. <div class='table-responsive'>
  6.  
  7. <table id='myTable' class='table table-striped table-bordered'>
  8.  
  9. <thead>
  10.  
  11. <tr>
  12.  
  13. <th>Email</th>
  14.  
  15. <th>Name</th>
  16.  
  17. <th>Billing Address</th>
  18.  
  19. <th>Total Orders</th>
  20.  
  21. <th>Total spent</th>
  22.  
  23. <th>Avatar</th>
  24.  
  25. <th>Actions</th>
  26.  
  27. </tr>
  28.  
  29. </thead>
  30.  
  31. <tbody>
  32.  
  33. <?php
  34.  
  35. foreach($customers as $customer){
  36.  
  37.  
  38.  
  39. echo "<tr><td>" . $customer["email"]."</td>
  40.  
  41. <td>" . $customer["first_name"].$customer["last_name"]."</td>
  42.  
  43. <td>" . $customer["billing"]["address_1"]."</td>
  44.  
  45. <td>" . $customer["orders_count"]."</td>
  46.  
  47. <td>" . $customer["total_spent"]."</td>
  48.  
  49. <td><img height='50px' width='50px' src='".$customer["avatar_url"]."'></td>
  50.  
  51. <td><a class='open-AddBookDialog btn btn-primary' data-target='#myModal' data-id=".$customer['id']." data-toggle='modal'>Update</a>
  52.  
  53. <a class='open-deleteDialog btn btn-danger' data-target='#myModal1' data-id=".$customer['id']." data-toggle='modal'>Delete</a></td></tr>";
  54.  
  55. }
  56.  
  57.  
  58.  
  59. ?>
  60.  
  61. </tbody>
  62.  
  63. </table>
  64.  
  65. </div>
  66.  
  67. </div>

This is how the customer list will be displayed:

customers list

I will not cover the CRUD functions for customers in this tutorial.

Get All the Products of the Store

All the products on the store can be retrieved using the following GET call:

  1. $products = $woocommerce->get('products');

Here is the table that will show the details of the products:

  1. <div class="container">
  2.  
  3. <h2 class="sub-header">Products List</h2>
  4.  
  5. <div class='table-responsive'>
  6.  
  7. <table id='myTable' class='table table-striped table-bordered'>
  8.  
  9. <thead>
  10.  
  11. <tr>
  12.  
  13. <th>SKU</th>
  14.  
  15. <th>Name</th>
  16.  
  17. <th>Status</th>
  18.  
  19. <th>Price</th>
  20.  
  21. <th>Total Sales</th>
  22.  
  23. <th>Picture</th>
  24.  
  25. </tr>
  26.  
  27. </thead>
  28.  
  29. <tbody>
  30.  
  31. <?php
  32.  
  33. foreach($products as $product){
  34.  
  35.  
  36.  
  37. echo "<tr><td>" . $product["sku"]."</td>
  38.  
  39. <td>" . $product["name"]."</td>
  40.  
  41. <td>" . $product["status"]."</td>
  42.  
  43. <td>" . $product["price"]."</td>
  44.  
  45. <td>" . $product["total_sales"]."</td>
  46.  
  47. <td><img height='50px' width='50px' src='".$product["images"][0]["src"]."'></td></tr>";
  48.  
  49. }
  50.  
  51.  
  52.  
  53. ?>
  54.  
  55. </tbody>
  56.  
  57. </table>
  58.  
  59. </div>
  60.  
  61. </div>

The product list will be displayed as follows:

products list

At this point, the dashboard will look like:

dashboard demo

Conclusion

Woocommerce API has lots of options that simplify working with product variation, attributes, categories, taxes, coupons, etc. In this tutorial, I have tried to create a basic dashboard that manipulates and highlight orders, customers, and products. This WooCommerce custom dashboard can help you take a quick look at how the store is performing at the moment, and quickly process the orders.

Q: What is WooCommerce Rest API?

WooCommerce REST API is a tool that allows users to read and write various default WooCommerce features like products, orders, coupons, and checkout. To enable the API key, go to WooCommerce → Settings → Advanced → REST API.

Q: How do I use WooCommerce REST API?

WooCommerce allows users to enable Rest API by generating API Key.

  • Go to WordPress Dashboard → WooCommerce → Settings → Advance
  • Click on API Section and generate the key.
  • Define the scope of Rest API under the description field, select the users to access API functions, and assign read/write permission.
  • Click on Generate API Key

Pablo Guides