Create a statistical report application for the WooCommerce store
14 mins read

Create a statistical report application for the WooCommerce store

woocommerce-reporting-application

The WooCommerce plugin of WordPress allows you to efficiently create and manage e-commerce platforms, and provides built-in notification functions to remind you of new or completed orders, low inventory levels, and successful payments. These features are very important, but in-depth understanding of the valuable data collected by WooCommerce is very limited.

These limitations are features of traditional plugins that run in the WordPress environment. On the other hand, the scalability of hosted applications (based on external server network operations) is much stronger.

By integrating with the WooCommerce API and utilizing external resources, hosted applications can provide advanced reporting, custom alerts, and detailed understanding of e-commerce transactions.

In this guide, you will learn how to create an application for the WooCommerce store that utilizes comprehensive transaction data to generate email alerts, surpassing the functionality of standard plugins.

Existing reporting and notification functions

WooCommerce’s built-in alerts and status updates help with basic store management, but may not meet all business needs. Therefore, many users have turned to using third-party plugins to enhance their notification and reporting capabilities.

The most popular plugins include:

  • WooCommerce Admin – Provides an intuitive dashboard that includes key store metrics and reports.
  • WooCommerce PDF Invoices and Packing Slips – Customizable invoice and packing list templates, automatically sent to customers via email, and providing records of generated invoices and packing lists.
  • WooCommerce Google Analytics Integration – Use Google Analytics tools to generate detailed reports on customer demographics and traffic sources.

Through these plugins, WooCommerce can provide reporting and alert options, including order summaries, low inventory alerts, inventory management, and in-depth analysis through integration with tools such as Google Analytics.

Limitations of the current reporting system

The current reporting system, although beneficial, has limited functionality and some limitations, such as:

  • Customization: Universal reporting tools and plugins limit your company’s ability to gain in-depth and specific insights from data. You may need specialized metrics, unique visualizations, integration with proprietary analysis tools, or data filters that some common reporting tools and plugins cannot provide.
  • Scalability: Existing reporting systems may face scalability issues when dealing with large datasets. Slow performance and data processing bottlenecks can hinder efficient data analysis, leading to delays in decision-making and response time.
  • Relying on WordPress: Due to integration with WordPress limiting independence, customization, and scalability, you may face limitations related to server resources, plugin compatibility, and security vulnerabilities. This integration may also hinder enterprises from adopting more advanced technologies and solutions.

In contrast, customized reporting applications can provide detailed transaction and customer information. You can use this data to predict market trends and optimize your products accordingly.

In addition, you can quickly expand your custom reporting application to adapt to the constantly growing amount of data, ensuring seamless operations as your business grows.

Advanced Reporting Application

The advanced reporting application envisioned in this guide has the following features:

  • When customers place new orders, detailed transaction reminders will be sent to the store owner via email. The application also has a dashboard that displays all orders and their detailed information.
  • Inventory updates will display store inventory details on the dashboard. Here, you can easily track the inventory level of each product.
  • The total sales report allows you to analyze revenue trends over a period of time.

Unlike general plugins or default WooCommerce notification and alert systems, this application provides detailed and customizable alerts about remaining inventory and total sales.

Hosting this application also has the following advantages:

  • Scalability: Independent hosting can minimize data processing bottlenecks, ensuring that you can expand your business without resource constraints.
  • Customization: Independent hosting allows you to customize how collected data is used, such as by integrating third-party services (such as predictive analysis engines) and implementing unique data visualization technologies to better meet your company’s requirements and goals.
  • Autonomy: Removing your application from the WordPress environment allows you to overcome limitations such as limited server resources and potential conflicts between various plugins.

How to develop an advanced reporting application

In this section, let’s build a reporting application using Node.js, WooCommerce REST API, and webhooks to retrieve store data.

Requirement:

  • A locally running WooCommerce store with one or more products set up.
  • A free Mailgun account for sending emails.
  • Node.js and ngrok have been installed.
  • The initiation template for the project.
  • Code editor.

 

Configure Startup Template

Follow these steps to configure the startup template:

1. Take note of your Mailgun API key and sandbox fields, and paste their values along with the corresponding variables into the.env file. Please provide the email used to create the Mailgun account as the value for the MAILGUN_SENDER-EMAIL variable.

2.On the WordPress management dashboard, select WooCommerce>Settings>Advanced>REST API.

woo-app-rest-api
woo-app-rest-api

The WooCommerce advanced tab displays the REST API section.

3. Click on Add key to create an API key to verify requests from the application.

4. Open the Key Details section and provide a description and user, select Read/Write permission, and then click on Generate API Key.

woo-app-api-key-details
woo-app-api-key-details

The WooCommerce advanced tab displays API key details.

5. Ensure to copy the Consumer key and Consumer secret from the generated page, as you will not be able to see them again.

6. Open the. env file and assign the values copied in the previous step to their respective variables. Provide the store URL for the WOOCOMMERCE-STORE.URL variable (similar to http://localhost/mystore/index.php ).

7. Execute the following command on the terminal to install all project dependencies:

npm i express @woocommerce/woocommerce-rest-api dotenv ejs mailgun.js
npm i -D nodemon

 

The functions of these dependency relationships are as follows:

  • Express: The Node.js framework used to create APIs.
  • @WooCommerce/WooCommerce test API: Make network calls to the WooCommerce REST API.
  • Dotenv: Load environment variables from the. env file.
  • Ejs: Create a JavaScript template.
  • Mailgun. js: Use Mailgun to send emails.
  • Nodemon: Automatically restart the server when file changes are detected.

Implement application functionality

The startup template contains the code for embedded JavaScript (EJS) templates in the views folder. In this way, you can focus on the server logic, which is to retrieve the necessary data from the WooCommerce API and pass it to the EJS template for display in the user interface (UI).

To implement the functionality of the application, please follow the following steps:

1. Create a file named server.js in the root folder of the project. This file is the entrance to the Express server.

2. Paste the following code into the server.js file:

const express = require('express')
const WooCommerceRestApi = require("@woocommerce/woocommerce-rest-api").default;
require('dotenv').config();
const app = express()
const port = 3000
const WooCommerce = new WooCommerceRestApi({
url: process.env.WOOCOMMERCE_STORE_URL,
consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY,
consumerSecret: process.env.WOOCOMMERCE_SECRET_KEY,
version: "wc/v3"
});
app.set('view engine', 'ejs')
// endpoint to check if the application is up and running
app.get('/', (req, res) => {
res.send('The application is up and running!')
})
// retrieve all products in the store
app.get('/products', (req, res) => {
WooCommerce.get("products")
.then((response) => {
res.render('pages/inventory', {
products: response.data,
currentPage: req.originalUrl
});
})
.catch((error) => {
console.log(error.response.data);
});
})
app.listen(port, () => {
console.log(`App listening on port ${port}`)
})

The above code uses Express.js to create a network server. Firstly, you need to import the required software packages, configure the WooCommerce client to interact with the WooCommerce REST API, and set the application to use EJS templates.

Firstly, define an endpoint to check if the application is running properly. Then, define a/products route to retrieve all products in the WooCommerce store.
If successful, the path will use the obtained data to render the inventory template.

Please note that the code also passes a currentPage to all routing templates, which helps identify the active pages on the dashboard.

3. Run the npm run dev command and open it in the browser http://localhost:3000/products View results:

woo-app-store-inventory
woo-app-store-inventory

Store inventory page containing detailed product information.

The store inventory page displays all products and their detailed information in the store. These pieces of information can help you track available products and manage inventory accordingly.

4.To process sales reports, please add the following routing in the server.js file:

// retrieve monthly sales report
app.get('/sales', (req, res) => {
WooCommerce.get("reports/sales", {
period: "month"
})
.then((response) => {
res.render('pages/sales', {
sales: response.data,
currentPage: req.originalUrl
})
})
.catch((error) => {
console.log(error.response.data);
});
})

This code defines a/sales endpoint for retrieving monthly sales reports from the WooCommerce sales report API. The API call includes the parameter period, which has a value of month, specifying the sales report for the current month. After the request is successful, the code will use the obtained data to render the sales EJS template.

5. In the browser, navigate to http://localhost:3000/sales View results:

woo-app-monthly-sales-report
woo-app-monthly-sales-report

Monthly sales report page.

This page displays a comprehensive sales total report, helping you analyze the monthly revenue trend of the enterprise.

Implement order management

1. Add the following routes to the server.js file.

// retrieve all orders
app.get('/orders', (req, res) => {
WooCommerce.get("orders")
.then((response) => {
res.render('pages/orders', {
orders: response.data,
currentPage: req.originalUrl
})
})
.catch((error) => {
console.log(error.response.data);
});
})

This code will retrieve all orders in the WooCommerce store and render the order template using the obtained data.

2. In the browser, navigate to http://localhost:3000/orders View the results. This page displays order management information:

woo-app-orders
woo-app-orders

The order page displays transaction details.

Customize alerts to provide comprehensive transaction reports

To achieve the function of sending customized email reminders to customers when they place orders on the website, please follow the following steps:

1. Open a terminal window and run ngrok HTTP 3000 to tunnel the network server connection. This command will generate an HTTPS link that WooCommerce can use to send webhook data. Copy the generated forwarding link.

2. Add the following routes to the server.js file:

app.post('/woocommerce-webhook/new-order', (req, res) => {
const data = req.body; // Received data from the WooCommerce webhook
console.log('New order:', data);
if(data?.id){
mg.messages.create(process.env.MAILGUN_SANDBOX_DOMAIN, {
from: `WooCommerce Store <${process.env.MAILGUN_SENDER_EMAIL}> `,
to: [process.env.MAILGUN_SENDER_EMAIL],
subject: "New Order Created",
html: newOrderEmail(data.order_key, `${data.billing.first_name} ${data.billing.last_name}`, data.billing.email, data.total, data.status, data.payment_method_title, data.line_items)
})
.then(msg => console.log(msg)) // logs response data
.catch(err => console.log(err)); // logs any error
}
res.status(200).send('Webhook received successfully'); // Send a response to WooCommerce
});

This code defines a route for handling the data passed in by the WooCommerce network hook triggered when a customer creates a new order. If the received data contains an ID attribute (indicating that the order is valid), it will use the Mailgun API to send email notifications to the specified email address.

Email includes various order details, such as customer name, email, total amount, status, payment method, and a list of purchased items.

The code uses the newOrderEMail() function defined in the utils/new order email.js file to write an email, which returns a custom email template. After processing the data and sending an email, the server will respond with a status code 200, indicating successful receipt of the network hook and corresponding message (“Received network hook successfully”).

3. Add the following statement to import the newOrderEmail() function:

Const {newOrderEmail}=require (‘./utils/new order email’);

4. Run the npm run start command to start the server.

5. On the WordPress management dashboard, select WooCommerce>Settings>Advanced>Webhooks.

woo-app-webhooks
woo-app-webhooks

The advanced page displays the Webhooks section.

6.  Click on Add webhook and provide the following information in the Webhook data table:

  • Name: New Order Alert
  • Status: Active
  • Topic: Order Created
  • Delivery URL: Paste the ngrok forwarding URL copied in step 1. Ensure to add/woocommerce webhook/new order to the URL. This is the newly defined endpoint for receiving webhook payloads.
  • Secret: Leave blank. The default is the consumer secret of the current API user. This secret will generate a hash value for the delivered network hook in the request header. The recipient can use this secret to verify the authenticity of incoming data. If the signature matches the expected value, it can be confirmed that the data was sent by WooCommerce, providing trust and security.
  • API Version: WP REST API Integration v3.
woo-app-webhook-form
woo-app-webhook-form

The advanced page displays a Webhook data table.

7. Click on Save webhook

8. Visit your store and place an order. You should see the following email:

woo-app-new-order-email
woo-app-new-order-email

Email reminders for new orders and inventory information.

Summary

With the flexibility of external hosting, you have created an advanced reporting application that can update remaining inventory levels and provide comprehensive sales total reports.

It also provides detailed transaction alerts, allowing you to stay informed of specific transactions in real-time, including product details, quantities, and customer information, so that you can actively manage inventory, understand sales trends, and revenue patterns.