introduce
As anyone who uses blog Park knows, blog Park provides a powerful customization function for users to customize their blogs. Many of them have added a “Visit Statistics” component to the sidebar that displays statistics for blogs, mainly visits by country, as shown below:
However, the “access statistics” component is mostly provided by flagcounter, amazingcounters, and so on. Therefore, the service is not good enough in terms of stability and transmission speed. How to solve the problem that the service experience provided by foreign service providers is not good enough and there are no similar services available directly in China? The answer is to build one.
The principle of analysis
First of all, let’s analyze the core functions of the access statistics function. There are three: data collection, IP address to physical address and data acquisition. Flagcounter, for example, provides a block of HTML code that looks like this:
The detailed code is as follows:
<a href="https://info.flagcounter.com/LGdk" ><img src="https://s11.flagcounter.com/count2/LGdk/bg_FFFFFF/txt_000000/border_CCCCCC/columns_2/maxflags_10/viewers_0/labels_0 /pageviews_0/flags_0/percent_0/" alt="Flag Counter" border="0" /> </a>Copy the code
The core part is the tag, the link in the SRC attribute is used to collect data and obtain data, and the function of transferring IP address to physical address is realized on the server side.
The project design
Through the above principle analysis, we mainly need to do data collection, IP address to physical address and data acquisition these three functions. There are two scenarios that can be implemented:
- Do it yourself: The functionality is fully customizable, but it takes more time
- Use existing services for some functions and implement the rest by yourself: Functions are limited by service providers, but functions are stable and save time
As for scheme 2, there are many free website statistics services available to individuals in China, such as Baidu Statistics, Umeng, 360 Analysis, etc., which provide data collection and transfer from IP address to physical address, with good stability and fast transmission speed. In terms of data capture, this is something we have to develop ourselves. Statistics services usually provide apis that we can wrap data into HTML code and dynamically load it into a blog.
In order to save time, we choose plan 2, baidu statistics as the statistical service, to set up the system.
For the integration of Baidu Statistics in the blog garden, you can refer to: Using Baidu statistics in the blog garden
The specific implementation
Create a project on baidu Developer platform
The use of Baidu statistics API involves Baidu developers, who need to register developers and then create a project:
Baidu Developer
Need to set “Authorization callback page “:
Integrate baidu statistics API
It includes two steps:
- Grant the baidu statistics service to the project created in the previous step: use the CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI of the project created in the previous step
- Call statistics API: personal use is Baidu account, Baidu business account
Baidu statistics Nav API
Baidu statistics provides “by country” and “by province” two indicators to obtain the geographical distribution of visits, which can be selected by preference.
The data returned
First add the following code block to the HTML code box of the blog garden. After obtaining the data, we format the data into AN HTML code block, return it to the front end, and dynamically insert it into the sidebar.
<script> let url = 'https://counter.toyfun.cn/api/counters/b035d53423sds317248696c2c0b/analytics'; fetch(url).then(res => { if (res.ok) { res.text().then(txt => { let element = document.getElementById('sideBarMain'); var div = document.createElement('div'); div.className = 'newsItem'; div.innerHTML = txt; element.insertBefore(div, element.childNodes[0]); }); }}); </script>Copy the code
Project instance
Technology stack
- Front-end page: HTML+CSS+JavaScript+Pug template engine
- Back end: Express framework
- Storage: SQLite
The key code
- Integration of Baidu statistics API:
async function getTokenByCode(code, clientId, clientSecret, redirectUri) {}
async function refreshToken(refreshToken, clientId, clientSecret) {}
async function getSites(accessToken) {}
async function getAnalytics(accessToken, params = {}) {}
Copy the code
- Database connections and operations
async function getDB() { if (! db) { await new Promise((res, rej) => { db = new sqlite3.Database(filename, error => { ... }); }); } return db; } async function run(sql, params) { let db = await getDB(); return new Promise((res, rej) => { db.run(sql, params, (error, result) => { ... }); }); }Copy the code
- Interface routing
router.get('/counters/:id/analytics', async (req, res) => {
// ...
// get analytics
let paramsForAnalytics = {
site_id,
...
};
let result = await baiduAnalyticsService.getAnalytics(
accessToken,
paramsForAnalytics
);
let data=parseResult(result);
// render html template
let locals = { total, data };;
let html = await htmlTemplateService.render('analytics', locals);
res.send(html);
});
Copy the code
Project results
Project website: counter.toyfun.cn/
The final effect is as follows:
Now it’s a simple table, but you can make it look pretty, add a country map (see FlagCounter), and offer a variety of display styles (visit trends, stay times, device types, etc.).
conclusion
This paper introduces the principle of the visit statistics of the blog park, and provides a concrete scheme design and implementation, the core functions are three: data collection, IP address to physical address and data acquisition. If you are interested, you can write your own, or you can use the off-the-shelf products provided in this article.