首页 / 应用软件 / 手把手教程,在WordPress中集成网站第三方服务API统一监控面板

手把手教程,在WordPress中集成网站第三方服务API统一监控面板

手把手教程:在WordPress中集成网站第三方服务API统一监控面板

引言:为什么需要API统一监控面板?

在当今的互联网环境中,网站通常依赖于多个第三方服务API来增强功能、提升用户体验或实现特定业务需求。从支付网关、社交媒体集成、邮件服务到数据分析工具,这些API服务构成了现代网站的核心支撑体系。然而,随着集成服务的增多,管理这些API的状态、监控其性能和可用性变得越来越复杂。

想象一下这样的场景:您的电商网站集成了支付宝、微信支付、物流查询、库存管理、邮件通知等十几种API服务。当某个服务出现故障时,您可能需要逐一检查每个服务的状态,这不仅耗时耗力,而且可能延误问题的解决时间,直接影响用户体验和业务收入。

本教程将手把手教您如何在WordPress中创建一个统一的第三方服务API监控面板,通过代码二次开发实现常用互联网小工具功能,让您能够在一个界面中实时监控所有集成的API服务状态,快速定位问题,提高网站运维效率。

第一部分:准备工作与环境配置

1.1 确定监控需求与目标API

在开始开发之前,首先需要明确您要监控哪些第三方服务API。常见的监控目标包括:

  • 支付网关:支付宝、微信支付、PayPal等
  • 社交媒体:微信、微博、Facebook、Twitter等API
  • 邮件服务:SMTP服务、SendGrid、MailChimp等
  • 云存储:阿里云OSS、腾讯云COS、AWS S3等
  • 地图服务:百度地图、高德地图、Google Maps等
  • 短信服务:阿里云短信、腾讯云短信等
  • 数据分析:Google Analytics、百度统计等

列出所有需要监控的API后,记录每个API的以下信息:

  • API端点URL
  • 认证方式(API密钥、OAuth等)
  • 健康检查方法(专用健康检查端点或模拟实际请求)
  • 预期响应时间和格式

1.2 创建WordPress插件框架

我们将创建一个独立的WordPress插件来实现API监控功能,这样可以确保代码的独立性和可维护性。

  1. 在WordPress的wp-content/plugins/目录下创建新文件夹api-monitor-dashboard
  2. 在该文件夹中创建主插件文件api-monitor-dashboard.php,并添加以下基础代码:
<?php
/**
 * Plugin Name: API统一监控面板
 * Plugin URI: https://yourwebsite.com/
 * Description: 在WordPress中集成第三方服务API统一监控面板
 * Version: 1.0.0
 * Author: 您的名字
 * License: GPL v2 or later
 * Text Domain: api-monitor-dashboard
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('AMD_VERSION', '1.0.0');
define('AMD_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('AMD_PLUGIN_URL', plugin_dir_url(__FILE__));

// 初始化插件
require_once AMD_PLUGIN_DIR . 'includes/class-api-monitor-core.php';

function amd_init() {
    $api_monitor = new API_Monitor_Core();
    $api_monitor->init();
}
add_action('plugins_loaded', 'amd_init');

1.3 创建数据库表结构

为了存储API监控的历史数据和配置,我们需要创建数据库表。在插件初始化时检查并创建必要的表结构。

includes/class-api-monitor-core.php中添加数据库创建方法:

class API_Monitor_Core {
    
    public function init() {
        // 注册激活钩子
        register_activation_hook(__FILE__, array($this, 'activate_plugin'));
        
        // 注册管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        
        // 加载必要资源
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
    }
    
    public function activate_plugin() {
        $this->create_database_tables();
        $this->insert_default_data();
    }
    
    private function create_database_tables() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'api_monitor_services';
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            service_name varchar(100) NOT NULL,
            api_endpoint varchar(500) NOT NULL,
            api_type varchar(50) NOT NULL,
            auth_method varchar(50) DEFAULT 'api_key',
            api_key varchar(500) DEFAULT '',
            check_interval int DEFAULT 300,
            last_check datetime DEFAULT '0000-00-00 00:00:00',
            last_status varchar(20) DEFAULT 'unknown',
            last_response_time float DEFAULT 0,
            uptime_percentage float DEFAULT 100,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            is_active tinyint(1) DEFAULT 1,
            PRIMARY KEY (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // 创建监控日志表
        $log_table_name = $wpdb->prefix . 'api_monitor_logs';
        
        $sql_log = "CREATE TABLE IF NOT EXISTS $log_table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            service_id mediumint(9) NOT NULL,
            check_time datetime DEFAULT CURRENT_TIMESTAMP,
            status varchar(20) NOT NULL,
            response_time float NOT NULL,
            response_code int DEFAULT 0,
            error_message text,
            PRIMARY KEY (id),
            KEY service_id (service_id),
            KEY check_time (check_time)
        ) $charset_collate;";
        
        dbDelta($sql_log);
    }
    
    private function insert_default_data() {
        // 可以在这里插入一些默认的API服务配置
    }
}

第二部分:构建API监控核心功能

2.1 设计API服务检查器

API监控的核心是能够定期检查各个服务的状态。我们将创建一个服务检查器类,负责执行API健康检查。

创建includes/class-api-checker.php

class API_Checker {
    
    private $wpdb;
    private $services_table;
    private $logs_table;
    
    public function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->services_table = $wpdb->prefix . 'api_monitor_services';
        $this->logs_table = $wpdb->prefix . 'api_monitor_logs';
    }
    
    /**
     * 检查所有活跃的API服务
     */
    public function check_all_services() {
        $services = $this->get_active_services();
        
        foreach ($services as $service) {
            $this->check_single_service($service);
        }
        
        return count($services);
    }
    
    /**
     * 获取所有活跃的服务
     */
    private function get_active_services() {
        return $this->wpdb->get_results(
            "SELECT * FROM {$this->services_table} WHERE is_active = 1"
        );
    }
    
    /**
     * 检查单个API服务
     */
    private function check_single_service($service) {
        $start_time = microtime(true);
        $status = 'unknown';
        $response_code = 0;
        $error_message = '';
        
        try {
            // 根据API类型选择不同的检查方法
            switch ($service->api_type) {
                case 'http_get':
                    $result = $this->check_http_get($service);
                    break;
                case 'http_post':
                    $result = $this->check_http_post($service);
                    break;
                case 'oauth':
                    $result = $this->check_oauth_service($service);
                    break;
                default:
                    $result = $this->check_http_get($service);
            }
            
            $status = $result['status'];
            $response_code = $result['response_code'];
            $error_message = $result['error_message'] ?? '';
            
        } catch (Exception $e) {
            $status = 'error';
            $error_message = $e->getMessage();
        }
        
        $response_time = round((microtime(true) - $start_time) * 1000, 2); // 转换为毫秒
        
        // 记录检查结果
        $this->log_check_result($service->id, $status, $response_time, $response_code, $error_message);
        
        // 更新服务状态
        $this->update_service_status($service->id, $status, $response_time);
        
        return array(
            'service_id' => $service->id,
            'service_name' => $service->service_name,
            'status' => $status,
            'response_time' => $response_time,
            'response_code' => $response_code,
            'error_message' => $error_message
        );
    }
    
    /**
     * HTTP GET方式检查
     */
    private function check_http_get($service) {
        $args = array(
            'timeout' => 10,
            'headers' => $this->prepare_headers($service)
        );
        
        $response = wp_remote_get($service->api_endpoint, $args);
        
        return $this->process_http_response($response);
    }
    
    /**
     * HTTP POST方式检查
     */
    private function check_http_post($service) {
        $args = array(
            'timeout' => 10,
            'headers' => $this->prepare_headers($service),
            'body' => $this->prepare_body($service)
        );
        
        $response = wp_remote_post($service->api_endpoint, $args);
        
        return $this->process_http_response($response);
    }
    
    /**
     * 准备请求头
     */
    private function prepare_headers($service) {
        $headers = array();
        
        // 根据认证方式添加相应的请求头
        switch ($service->auth_method) {
            case 'api_key':
                if (!empty($service->api_key)) {
                    $headers['Authorization'] = 'Bearer ' . $service->api_key;
                }
                break;
            case 'basic_auth':
                // 处理基本认证
                break;
            case 'oauth':
                // 处理OAuth认证
                break;
        }
        
        $headers['User-Agent'] = 'WordPress API Monitor/1.0';
        
        return $headers;
    }
    
    /**
     * 处理HTTP响应
     */
    private function process_http_response($response) {
        if (is_wp_error($response)) {
            return array(
                'status' => 'error',
                'response_code' => 0,
                'error_message' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        
        if ($response_code >= 200 && $response_code < 300) {
            $status = 'healthy';
        } elseif ($response_code >= 400 && $response_code < 500) {
            $status = 'warning';
        } else {
            $status = 'error';
        }
        
        return array(
            'status' => $status,
            'response_code' => $response_code
        );
    }
    
    /**
     * 记录检查结果到数据库
     */
    private function log_check_result($service_id, $status, $response_time, $response_code, $error_message) {
        $this->wpdb->insert(
            $this->logs_table,
            array(
                'service_id' => $service_id,
                'status' => $status,
                'response_time' => $response_time,
                'response_code' => $response_code,
                'error_message' => $error_message
            ),
            array('%d', '%s', '%f', '%d', '%s')
        );
    }
    
    /**
     * 更新服务状态
     */
    private function update_service_status($service_id, $status, $response_time) {
        // 计算正常运行时间百分比
        $uptime_percentage = $this->calculate_uptime_percentage($service_id);
        
        $this->wpdb->update(
            $this->services_table,
            array(
                'last_check' => current_time('mysql'),
                'last_status' => $status,
                'last_response_time' => $response_time,
                'uptime_percentage' => $uptime_percentage
            ),
            array('id' => $service_id),
            array('%s', '%s', '%f', '%f'),
            array('%d')
        );
    }
    
    /**
     * 计算正常运行时间百分比
     */
    private function calculate_uptime_percentage($service_id) {
        $total_checks = $this->wpdb->get_var(
            $this->wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->logs_table} WHERE service_id = %d AND check_time > DATE_SUB(NOW(), INTERVAL 7 DAY)",
                $service_id
            )
        );
        
        if ($total_checks == 0) {
            return 100;
        }
        
        $healthy_checks = $this->wpdb->get_var(
            $this->wpdb->prepare(
                "SELECT COUNT(*) FROM {$this->logs_table} WHERE service_id = %d AND status = 'healthy' AND check_time > DATE_SUB(NOW(), INTERVAL 7 DAY)",
                $service_id
            )
        );
        
        return round(($healthy_checks / $total_checks) * 100, 2);
    }
}

2.2 实现定时检查功能

为了定期检查API状态,我们需要使用WordPress的定时任务功能。在class-api-monitor-core.php中添加定时任务管理:

// 在API_Monitor_Core类中添加以下方法

public function init() {
    // ... 其他初始化代码
    
    // 初始化定时任务
    add_action('amd_check_apis_event', array($this, 'run_api_checks'));
    
    // 注册停用插件时的清理操作
    register_deactivation_hook(__FILE__, array($this, 'deactivate_plugin'));
}

public function schedule_events() {
    if (!wp_next_scheduled('amd_check_apis_event')) {
        wp_schedule_event(time(), 'five_minutes', 'amd_check_apis_event');
    }
}

public function deactivate_plugin() {
    // 清除定时任务
    wp_clear_scheduled_hook('amd_check_apis_event');
}

public function run_api_checks() {
    require_once AMD_PLUGIN_DIR . 'includes/class-api-checker.php';
    $checker = new API_Checker();
    $checked_count = $checker->check_all_services();
    
    // 记录检查日志
    error_log("API监控:已检查 {$checked_count} 个服务");
}

// 添加自定义时间间隔
public function add_cron_interval($schedules) {
    $schedules['five_minutes'] = array(
        'interval' => 300,
        'display' => __('每5分钟', 'api-monitor-dashboard')
    );
    
    $schedules['thirty_minutes'] = array(
        'interval' => 1800,
        'display' => __('每30分钟', 'api-monitor-dashboard')
    );
    
    return $schedules;
}

第三部分:创建监控管理界面

3.1 设计管理菜单和主面板

现在我们需要创建一个用户友好的管理界面来显示API监控状态。首先在WordPress后台添加菜单项:

// 在API_Monitor_Core类中添加

public function add_admin_menu() {
    add_menu_page(
        'API监控面板',
        'API监控',
        'manage_options',
        'api-monitor-dashboard',
        array($this, 'render_dashboard_page'),
        'dashicons-dashboard',
        30
    );
    
    add_submenu_page(
        'api-monitor-dashboard',
        'API服务管理',
        '服务管理',
        'manage_options',
        'api-monitor-services',
        array($this, 'render_services_page')
    );
    
    add_submenu_page(
        'api-monitor-dashboard',
        '监控日志',
        '监控日志',
        'manage_options',
        'api-monitor-logs',
        array($this, 'render_logs_page')
    );
    
    add_submenu_page(
        'api-monitor-dashboard',
        '设置',
        '设置',
        'manage_options',
        'api-monitor-settings',
        array($this, 'render_settings_page')
    );
}

3.2 创建仪表板页面

创建templates/dashboard.php文件,用于显示API监控主面板:

<div class="wrap">
    <h1 class="wp-heading-inline">API监控面板</h1>
    
    <div class="amd-dashboard">
        <!-- 概览统计 -->
        <div class="amd-overview-stats">
            <div class="amd-stat-card">
                <h3>总服务数</h3>
                <div class="amd-stat-value"><?php echo $total_services; ?></div>
            </div>
            <div class="amd-stat-card">
                <h3>正常运行</h3>
                <div class="amd-stat-value amd-stat-healthy"><?php echo $healthy_services; ?></div>
            </div>
            <div class="amd-stat-card">
                <h3>警告</h3>
                <div class="amd-stat-value amd-stat-warning"><?php echo $warning_services; ?></div>
            </div>
            <div class="amd-stat-card">
                <h3>异常</h3>
                <div class="amd-stat-value amd-stat-error"><?php echo $error_services; ?></div>
            </div>
            <div class="amd-stat-card">
                <h3>平均响应时间</h3>
                <div class="amd-stat-value"><?php echo $avg_response_time; ?>ms</div>
            </div>
        </div>
        
        <!-- API服务状态表格 -->
        <div class="amd-services-table">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>服务名称</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>最后检查</th>
                        <th>响应时间</th>

<th>操作</th>

                </tr>
            </thead>
            <tbody>
                <?php foreach ($services as $service): ?>
                <tr>
                    <td>
                        <strong><?php echo esc_html($service->service_name); ?></strong><br>
                        <small><?php echo esc_html($service->api_endpoint); ?></small>
                    </td>
                    <td><?php echo esc_html($this->get_api_type_label($service->api_type)); ?></td>
                    <td>
                        <?php echo $this->get_status_badge($service->last_status); ?>
                    </td>
                    <td>
                        <?php 
                        if ($service->last_check != '0000-00-00 00:00:00') {
                            echo human_time_diff(strtotime($service->last_check), current_time('timestamp')) . '前';
                        } else {
                            echo '从未检查';
                        }
                        ?>
                    </td>
                    <td>
                        <?php 
                        $response_time_class = '';
                        if ($service->last_response_time > 1000) {
                            $response_time_class = 'amd-response-slow';
                        } elseif ($service->last_response_time > 500) {
                            $response_time_class = 'amd-response-medium';
                        } else {
                            $response_time_class = 'amd-response-fast';
                        }
                        ?>
                        <span class="<?php echo $response_time_class; ?>">
                            <?php echo number_format($service->last_response_time, 2); ?>ms
                        </span>
                    </td>
                    <td>
                        <div class="amd-uptime-bar">
                            <div class="amd-uptime-fill" style="width: <?php echo $service->uptime_percentage; ?>%"></div>
                            <span class="amd-uptime-text"><?php echo $service->uptime_percentage; ?>%</span>
                        </div>
                    </td>
                    <td>
                        <button class="button button-small amd-check-now" data-service-id="<?php echo $service->id; ?>">
                            立即检查
                        </button>
                        <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=edit&id=' . $service->id); ?>" class="button button-small">
                            编辑
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <!-- 响应时间趋势图 -->
    <div class="amd-chart-container">
        <h3>最近24小时响应时间趋势</h3>
        <canvas id="amd-response-time-chart" width="800" height="200"></canvas>
    </div>
    
    <!-- 状态分布图 -->
    <div class="amd-status-distribution">
        <h3>服务状态分布</h3>
        <div class="amd-status-chart-container">
            <canvas id="amd-status-chart" width="400" height="400"></canvas>
        </div>
    </div>
</div>

</div>


### 3.3 创建服务管理页面

创建`templates/services.php`,用于管理API服务配置:

<div class="wrap">

<h1 class="wp-heading-inline">API服务管理</h1>
<a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=add'); ?>" class="page-title-action">添加新服务</a>

<?php if ($action == 'list'): ?>

<div class="tablenav top">
    <div class="alignleft actions">
        <select name="bulk-action">
            <option value="-1">批量操作</option>
            <option value="activate">启用</option>
            <option value="deactivate">停用</option>
            <option value="delete">删除</option>
        </select>
        <input type="submit" class="button action" value="应用">
    </div>
    <div class="tablenav-pages">
        <span class="displaying-num"><?php echo $total_items; ?>个项目</span>
    </div>
</div>

<table class="wp-list-table widefat fixed striped">
    <thead>
        <tr>
            <td class="manage-column column-cb check-column">
                <input type="checkbox">
            </td>
            <th>服务名称</th>
            <th>API端点</th>
            <th>类型</th>
            <th>状态</th>
            <th>检查间隔</th>
            <th>最后检查</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($services as $service): ?>
        <tr>
            <th scope="row" class="check-column">
                <input type="checkbox" name="service_ids[]" value="<?php echo $service->id; ?>">
            </th>
            <td>
                <strong>
                    <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=edit&id=' . $service->id); ?>">
                        <?php echo esc_html($service->service_name); ?>
                    </a>
                </strong>
            </td>
            <td><?php echo esc_html($this->truncate_string($service->api_endpoint, 50)); ?></td>
            <td><?php echo esc_html($service->api_type); ?></td>
            <td>
                <?php if ($service->is_active): ?>
                    <span class="amd-status-active">已启用</span>
                <?php else: ?>
                    <span class="amd-status-inactive">已停用</span>
                <?php endif; ?>
            </td>
            <td><?php echo $this->format_interval($service->check_interval); ?></td>
            <td>
                <?php 
                if ($service->last_check != '0000-00-00 00:00:00') {
                    echo date('Y-m-d H:i:s', strtotime($service->last_check));
                } else {
                    echo '从未检查';
                }
                ?>
            </td>
            <td>
                <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=edit&id=' . $service->id); ?>">编辑</a> |
                <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=delete&id=' . $service->id); ?>" onclick="return confirm('确定要删除这个服务吗?')">删除</a> |
                <?php if ($service->is_active): ?>
                    <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=deactivate&id=' . $service->id); ?>">停用</a>
                <?php else: ?>
                    <a href="<?php echo admin_url('admin.php?page=api-monitor-services&action=activate&id=' . $service->id); ?>">启用</a>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php elseif ($action == 'add' || $action == 'edit'): ?>

<form method="post" action="">
    <?php wp_nonce_field('amd_save_service', 'amd_service_nonce'); ?>
    
    <table class="form-table">
        <tr>
            <th scope="row"><label for="service_name">服务名称</label></th>
            <td>
                <input type="text" id="service_name" name="service_name" value="<?php echo esc_attr($service_data['service_name'] ?? ''); ?>" class="regular-text" required>
                <p class="description">显示在监控面板中的服务名称</p>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="api_endpoint">API端点</label></th>
            <td>
                <input type="url" id="api_endpoint" name="api_endpoint" value="<?php echo esc_attr($service_data['api_endpoint'] ?? ''); ?>" class="regular-text" required>
                <p class="description">API的完整URL地址</p>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="api_type">API类型</label></th>
            <td>
                <select id="api_type" name="api_type" class="regular-text">
                    <option value="http_get" <?php selected($service_data['api_type'] ?? '', 'http_get'); ?>>HTTP GET</option>
                    <option value="http_post" <?php selected($service_data['api_type'] ?? '', 'http_post'); ?>>HTTP POST</option>
                    <option value="oauth" <?php selected($service_data['api_type'] ?? '', 'oauth'); ?>>OAuth</option>
                    <option value="websocket" <?php selected($service_data['api_type'] ?? '', 'websocket'); ?>>WebSocket</option>
                    <option value="custom" <?php selected($service_data['api_type'] ?? '', 'custom'); ?>>自定义</option>
                </select>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="auth_method">认证方式</label></th>
            <td>
                <select id="auth_method" name="auth_method" class="regular-text">
                    <option value="none" <?php selected($service_data['auth_method'] ?? '', 'none'); ?>>无需认证</option>
                    <option value="api_key" <?php selected($service_data['auth_method'] ?? '', 'api_key'); ?>>API密钥</option>
                    <option value="basic_auth" <?php selected($service_data['auth_method'] ?? '', 'basic_auth'); ?>>基本认证</option>
                    <option value="oauth" <?php selected($service_data['auth_method'] ?? '', 'oauth'); ?>>OAuth 2.0</option>
                </select>
            </td>
        </tr>
        
        <tr class="auth-field" id="api_key_field">
            <th scope="row"><label for="api_key">API密钥</label></th>
            <td>
                <input type="password" id="api_key" name="api_key" value="<?php echo esc_attr($service_data['api_key'] ?? ''); ?>" class="regular-text">
                <button type="button" class="button button-small toggle-password">显示/隐藏</button>
                <p class="description">API访问密钥,将安全存储</p>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="check_interval">检查间隔</label></th>
            <td>
                <select id="check_interval" name="check_interval" class="regular-text">
                    <option value="60" <?php selected($service_data['check_interval'] ?? 300, 60); ?>>1分钟</option>
                    <option value="300" <?php selected($service_data['check_interval'] ?? 300, 300); ?>>5分钟</option>
                    <option value="900" <?php selected($service_data['check_interval'] ?? 300, 900); ?>>15分钟</option>
                    <option value="1800" <?php selected($service_data['check_interval'] ?? 300, 1800); ?>>30分钟</option>
                    <option value="3600" <?php selected($service_data['check_interval'] ?? 300, 3600); ?>>1小时</option>
                </select>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="expected_response">预期响应</label></th>
            <td>
                <textarea id="expected_response" name="expected_response" rows="3" class="large-text"><?php echo esc_textarea($service_data['expected_response'] ?? ''); ?></textarea>
                <p class="description">可选的预期响应内容(用于验证API返回正确数据)</p>
            </td>
        </tr>
        
        <tr>
            <th scope="row"><label for="is_active">状态</label></th>
            <td>
                <label>
                    <input type="checkbox" id="is_active" name="is_active" value="1" <?php checked($service_data['is_active'] ?? 1, 1); ?>>
                    启用此服务的监控
                </label>
            </td>
        </tr>
    </table>
    
    <p class="submit">
        <input type="submit" name="submit" class="button button-primary" value="保存服务">
        <a href="<?php echo admin_url('admin.php?page=api-monitor-services'); ?>" class="button">取消</a>
    </p>
</form>

<?php endif; ?>

</div>


## 第四部分:增强功能与互联网小工具集成

### 4.1 实现实时通知功能

为了让管理员及时了解API状态变化,我们需要实现通知功能。创建`includes/class-notification-manager.php`:

class Notification_Manager {


private $notification_methods = array();

public function __construct() {
    // 初始化通知方法
    $this->notification_methods = array(
        'email' => array($this, 'send_email_notification'),
        'slack' => array($this, 'send_slack_notification'),
        'webhook' => array($this, 'send_webhook_notification'),
        'sms' => array($this, 'send_sms_notification')
    );
}

/**
 * 发送状态变化通知
 */
public function send_status_change_notification($service_id, $old_status, $new_status, $service_data) {
    $notification_settings = get_option('amd_notification_settings', array());
    
    // 检查是否需要发送通知
    if (!$this->should_send_notification($old_status, $new_status, $notification_settings)) {
        return;
    }
    
    // 准备通知内容
    $message = $this->prepare_notification_message($service_data, $old_status, $new_status);
    
    // 发送到所有启用的通知渠道
    foreach ($notification_settings['channels'] as $channel => $enabled) {
        if ($enabled && isset($this->notification_methods[$channel])) {
            call_user_func($this->notification_methods[$channel], $message, $service_data);
        }
    }
}

/**
 * 准备通知消息
 */
private function prepare_notification_message($service_data, $old_status, $new_status) {
    $site_name = get_bloginfo('name');
    $timestamp = current_time('mysql');
    
    $status_labels = array(
        'healthy' => '正常',
        'warning' => '警告',
        'error' => '异常',
        'unknown' => '未知'
    );
    
    $message = "【{$site_name} API监控通知】nn";
    $message .= "服务名称:{$service_data['service_name']}n";
    $message .= "API端点:{$service_data['api_endpoint']}n";
    $message .= "状态变化:{$status_labels[$old_status]} → {$status_labels[$new_status]}n";
    $message .= "发生时间:{$timestamp}n";
    
    if ($new_status == 'error' && !empty($service_data['error_message'])) {
        $message .= "错误信息:{$service_data['error_message']}n";
    }
    
    $message .= "n请及时处理。";
    
    return $message;
}

/**
 * 发送邮件通知
 */
private function send_email_notification($message, $service_data) {
    $settings = get_option('amd_notification_settings', array());
    $to = $settings['email_recipients'] ?? get_option('admin_email');
    
    $subject = "API监控告警:{$service_data['service_name']} 状态异常";
    
    wp_mail($to, $subject, $message);
}

/**
 * 发送Slack通知
 */
private function send_slack_notification($message, $service_data) {
    $settings = get_option('amd_notification_settings', array());
    
    if (empty($settings['slack_webhook_url'])) {
        return;
    }
    
    $payload = array(
        'text' => $message,
        'username' => 'API监控机器人',
        'icon_emoji' => ':warning:',
        'attachments' => array(
            array(
                'color' => $this->get_status_color($service_data['last_status']),
                'fields' => array(
                    array(
                        'title' => '服务名称',
                        'value' => $service_data['service_name'],
                        'short' => true
                    ),
                    array(
                        'title' => '当前状态',
                        'value' => $service_data['last_status'],
                        'short' => true
                    )
                )
            )
        )
    );
    
    $args = array(
        'body' => json_encode($payload),
        'headers' => array('Content-Type' => 'application/json'),
        'timeout' => 5
    );
    
    wp_remote_post($settings['slack_webhook_url'], $args);
}

/**
 * 获取状态对应的颜色
 */
private function get_status_color($status) {
    $colors = array(
        'healthy' => '#36a64f',
        'warning' => '#ffcc00',
        'error' => '#ff0000',
        'unknown' => '#cccccc'
    );
    
    return $colors[$status] ?? '#cccccc';
}

}


### 4.2 集成常用互联网小工具

#### 4.2.1 天气信息小工具

创建`includes/widgets/class-weather-widget.php`:

class Weather_Widget extends WP_Widget {


public function __construct() {
    parent::__construct(
        'amd_weather_widget',
        'API监控 - 天气信息',
        array('description' => '显示当前天气信息')
    );
}

public function widget($args, $instance) {
    $weather_data = $this->get_weather_data($instance['city']);
    
    echo $args['before_widget'];
    
    if (!empty($instance['title'])) {
        echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
    }
    
    if ($weather_data) {
        echo '<div class="amd
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5266.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部