The WooCommerce plugin for WordPress allows you to efficiently create and manage eCommerce platforms and provides built-in notifications that alert you to new or completed orders, low inventory levels, and successful payments. These features are important, but there is very little insight into the valuable data that WooCommerce collects.
These limitations are characteristic of traditional plugins that run in a WordPress environment. By integrating with the WooCommerce API and using external resources, the hosted application can provide advanced reporting, customized alerts, and detailed insight into eCommerce transactions.
![图片[1]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908243732.jpg)
Existing reporting and notification features
WooCommerce's built-in alerts and status updates help with basic store management, but may not fulfill all business needs. As a result, many users turn to third-party plugins to enhance notification and reporting capabilities.
Some of the most popular plugins include:
- WooCommerce Admin - Provides an intuitive dashboard with key store metrics and reports.
- WooCommerce PDF Invoices and Packing Slips - Invoice and packing list templates can be customized and automatically emailed to customers with a record of invoices and packing lists that have been generated.
- WooCommerce Google Analytics Integration - Use the Google Analytics tool to generate detailed reports on customer demographics and traffic sources.
With these plugins, WooCommerce offers reporting and alerting options including order summaries, low stock alerts, inventory management, and deeper analytics through integrations with tools like Google Analytics.
![图片[2]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908265331.jpg)
Limitations of the current reporting system
The current reporting system, while beneficial, has limited functionality and introduces a number of limitations:
- customizable: Generic reporting tools and plug-ins limit the ability to gain deep and specific insights from data. There is a need for specialized metrics, unique visualizations, integration with proprietary analytical tools, or data filters that some generic reporting tools and plug-ins cannot provide.
- Scalability: Existing reporting systems may face scalability issues when dealing with large data sets. Slow performance and data processing bottlenecks can hinder efficient data analysis, leading to delays in decision-making and response times.
- Dependency on WordPress:Because integration with WordPress limits independence, customization, and scalability, one may face limitations related to server resources, plugin compatibility, and security vulnerabilities. This integration may also prevent organizations from adopting more advanced technologies and solutions.
Advanced reporting applications
The advanced reporting application envisioned in this guide has the following features:
- When a customer places a new order, a detailed transaction alert is sent to the store owner via email. The app also has a dashboard that shows all orders and their details.
- Inventory updates will show store inventory details on the dashboard. From here, it is easy to keep track of stock levels for each product.
- The Total Sales report allows for the analysis of revenue trends over time.
Unlike generic plugins or the default WooCommerce notification and alert system, the app provides detailed and customizable alerts about remaining inventory and total sales.
![图片[3]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908274353.jpg)
How to Develop Advanced Reporting Applications
In this section, let's use Node.js and theWooCommerce REST API respond in singingWebhookBuild a reporting application together to retrieve store data.
Request:
- A locally-run WooCommerce store containing one or more groups of products.
- Free for sending emailsMailgun account The
- Node.js installed respond in singingngrok The
- project-basedGetting Started TemplatesThe
- Code Editor.
Configuring the Getting Started Template
Follow the steps below to configure the Getting Started template:
- Make a note of your Mailgun API key and sandbox domain and paste their values with the corresponding variables into the.envin the file. For the
MAILGUN_SENDER_EMAIL
variable that provides the email used to create the Mailgun account as the value. - In the WordPress admin dashboard, select theWooCommerce >set up >high level > REST APIThe
![图片[4]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050907383486.png)
- click (using a mouse or other pointing device)Add Key Create API keys to authenticate requests from the application.
- show (a ticket)Key details section and provide instructions and users, selectRead/Write Permissions, and then clickGenerating API KeysThe
![图片[5]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050907392513.png)
- Ensure that copying from the results pageconsumer key respond in singingConsumer Keys as it is impossible to see them again.
- show (a ticket).env file and assign the values copied in the previous step to the respective variables. The store URL that provides the variables
WOOCOMMERCE_STORE_URL
(Similar tohttp://localhost/mystore/index.php
). - Install all project dependencies by executing the following command in the terminal:
npm i express @woocommerce/woocommerce-rest-api dotenv ejs mailgun.js
npm i -D nodemon
The roles of these dependencies are as follows:
express
: A Node.js framework for creating APIs.@woocommerce/woocommerce-rest-api
: WooCommerce REST API for WooCommerceMake a network call.dotenv
: from .envfile to load environment variables .ejs
: Create JavaScript templates.mailgun.js
: Use Mailgun to send e-mail.nodemon
: Automatically restarts the server when a file change is detected.
Realization of application functions
The starting template contains the templates used to render the viewThe code for the Embedded JavaScript (EJS) template in the folder . This way, you can focus on the server logic that gets the necessary data from the WooCommerce API and passes it to the EJS template for display on the user interface (UI).
To realize the functionality of the application, perform the following steps:
- Create a file in the root folder of the project calledserver.jsfile. This file serves as the entry point to the Express server.
- Paste the following code in 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.
consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY, consumerSecret: process.env.
consumerSecret: process.env.WOOCOMMERCE_SECRET_KEY, consumerSecret: process.env.
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); }); }) .catch((error) => {
});
})
app.listen(port, () => {
console.log(`App listening on port ${port}`)
})
The code above uses Express.js to create a web server. First you need to import the required packages and configure the WooCommerce client to work with theWooCommerce REST APIinteraction and set the application to use EJS templates.
First, define a/
endpoint for checking that the application is running correctly. Then, define a/products
A route to retrieve all products from the WooCommerce store. If successful, this route willinventory
Use the acquired data presentation template.
Note that the code will alsocurrentPage
The templates for all routes are passed to the templates, which helps to identify the active page on the dashboard.
- Run command
npm run dev
furthermorehttp://localhost:3000/products
Open in your browser to view the results:
![图片[6]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050907564218.png)
The Store Inventory page displays all the products in the store and their details. This information helps track available products and manage inventory accordingly.
- To process the sales report, add the following route to 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 Reporting API. The API call containsperiod
Parameters with a value ofmonth
This parameter specifies the sales report for the current month. After a successful request, the code renders the sales EJS template using the fetched data.
- Navigate in your browser to
http://localhost:3000/sales
View Results:
![图片[7]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908063127.png)
This page displays a comprehensive gross sales report to help analyze monthly revenue trends.
Implementation of order management
- Add the following routes to theserver.js Documentation.
// 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 the orders in the WooCommerce store and render the order template using the fetched data.
- Navigate in your browser to
http://localhost:3000/orders
View Results. This page displays order management information:
![图片[8]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908103972.png)
Customize alerts for consolidated transaction reports
To implement the ability to send you customized email alerts when a customer orders on your website, follow the steps below:
- Open a terminal window and run
ngrok http 3000
to establish a tunnel for the web server connection. This command generates an HTTPS link that WooCommerce can use to send webhook data. Copy the generated forwarding link. - Add the following route 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 `,
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 to process incoming data from a WooCommerce web hook triggered when a customer creates a new order. If the incoming data contains an id attribute (indicating that the order is valid), it uses the Mailgun API to send an email notification to the specified email address.
Emails include various order details such as customer name, email, total amount, status, payment method, and a list of purchased items.
Code Usage The newOrderEMail() function defined in the utils/new-order-email.js file writes the email, which returns a custom email template. After the data is processed and the email is sent, the server responds with a status code of 200, indicating that the webhook was successfully received and the corresponding message ("Webhook successfully received").
- Add the following statement to import
newOrderEmail()
function:
const { newOrderEmail } = require('. /utils/new-order-email');
- Run command
npm run start
to start the server. - In the WordPress admin dashboard, select theWooCommerce >set up >high level > WebhooksThe
![图片[9]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908150076.png)
- click (using a mouse or other pointing device)Add the Webhook and add theWebhook DataThe following information is provided in the form:
- name (of a thing): New Order Alerts
- state of affairs: Active
- thematic: Order Created
- Delivery URL: Paste the ngrok forwarding URL you copied in step 1. make sure to attach the
/woocommerce-webhook/new-order
to the URL. which is the newly defined endpoint for receiving Webhook loads.
- transgression(Secret): Leave blank. Defaults to the consumer secret of the current API user. This secret generates a hash of the delivered web hook in the request header. The receiver can use this secret to verify the authenticity of the incoming data. If the signature matches the expected value, it confirms that the data was sent by WooCommerce, providing trust and security.
- API Version: WP REST API Integration v3.
![图片[10]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908164087.png)
- click (using a mouse or other pointing device)Save webhookThe
- Visit the store and place your order. Should see an email as shown below:
![图片[11]-给 WooCommerce 商店创建高级报告应用程序-光子波动网 | 专业WordPress修复服务,全球范围,快速响应](https://www.361sale.com/wp-content/uploads/2024/05/2024050908173764.png)
summarize
Created an advanced reporting application that updates remaining inventory levels and provides comprehensive gross sales reports. It also provides detailed transaction alerts that give you real-time visibility into specific transactions, including product details, quantities and customer information, so you can proactively manage inventory and understand sales trends and revenue patterns.
Link to this article:https://www.361sale.com/en/9550The article is copyrighted and must be reproduced with attribution.
No comments