服务器插件开发手册

思博 2026-03-21 30 阅读 109 分钟

目录

  1. 概述
  2. 目录结构
  3. 插件基础结构
  4. 核心函数详解
  5. 配置字段类型
  6. 参数说明
  7. 模板开发
  8. 开发示例
  9. 最佳实践

目录结构

所有服务器插件统一存放在 public\plugins\host 目录下。

完整目录结构

public/
└── plugins/
    └── host/                          # 服务器插件根目录
        ├── aliyun/                    # 阿里云插件
        │   ├── aliyun.php             # 插件主文件
        │   └── templates/             # 模板目录
        │       ├── overview.html
        │       ├── manage.html
        │       └── console.html
        │
        ├── tencentcloud/              # 腾讯云插件
        │   ├── tencentcloud.php
        │   └── templates/
        │       └── ...
        │
        ├── huaweicloud/               # 华为云插件
        │   ├── huaweicloud.php
        │   └── templates/
        │       └── ...
        │
        ├── aws/                       # AWS插件
        │   ├── aws.php
        │   └── templates/
        │       └── ...
        │
        └── default/                   # 默认示例插件
            ├── default.php
            └── templates/
                ├── 1.html
                └── 2.html

插件目录命名规范

项目规范示例
目录名小写字母+数字,与插件标识一致aliyun, tencentcloud
主文件名与目录名一致aliyun.php
模板目录必须命名为 templatestemplates/
模板文件.html 后缀overview.html

最小插件结构

public\plugins\host\{插件标识}/
├── {插件标识}.php          # 必填,插件主程序
└── templates/               # 可选,模板目录
    └── ...                  # 模板文件

概述

本系统采用 PHP + ThinkPHP 框架开发,服务器插件用于对接第三方服务器/云服务商 API,实现虚拟主机、云服务器等产品的自动化管理。

插件命名规范

  • 插件文件名格式:{插件标识}.php
  • 插件标识只能包含英文字母、数字和下划线
  • 所有函数必须以 插件标识_ 为前缀

插件基础结构

public\plugins\host\{插件标识}\{插件标识}.php 文件中编写:

<?php


use think\Db;


// ========== 1. 插件信息 ==========
function 插件标识_MetaData() {
    return [
        "DisplayName" => "插件显示名称",
        "APIVersion"  => "1.0.0",
        "HelpDoc"     => "https://文档链接"
    ];
}


// ========== 2. 连接测试 ==========
function 插件标识_TestLink($params) {
    return ["code" => "1", "msg" => "连接成功"];
}


// ========== 3. 配置字段定义 ==========
function 插件标识_AdminConfigOptions() { /* 服务器配置 */ }
function 插件标识_ConfigOptions() { /* 产品配置 */ }
function 插件标识_HostConfigOptions() { /* 业务配置 */ }


// ========== 4. 控制面板 ==========
function 插件标识_ClientArea($params) { /* 定义菜单 */ }
function 插件标识_ClientAreaOutput($params, $key) { /* 页面输出 */ }


// ========== 5. 生命周期函数 ==========
function 插件标识_CreateAccount($params) { /* 开通 */ }
function 插件标识_SuspendAccount($params) { /* 暂停 */ }
function 插件标识_UnsuspendAccount($params) { /* 解除暂停 */ }
function 插件标识_TerminateAccount($params) { /* 终止/删除 */ }
function 插件标识_Renew($params) { /* 续费 */ }
function 插件标识_ChangePackage($params) { /* 升降级 */ }


// ========== 6. 自定义按钮 ==========
function 插件标识_AdminButton() { /* 后台按钮 */ }
function 插件标识_ClientButton() { /* 前台按钮 */ }
function 插件标识_按钮标识($params) { /* 按钮执行逻辑 */ }


// ========== 7. 计划任务 ==========
function 插件标识_ProductCron() { /* 商品侧计划任务 */ }
function 插件标识_HostCron() { /* 业务侧计划任务 */ }

核心函数详解

1. 插件信息 (MetaData)

定义插件的基本信息,用于后台展示。

function default_MetaData() {
    return [
        "DisplayName" => "默认插件",      // 插件显示名称
        "APIVersion"  => "1.0.1",         // API版本号
        "HelpDoc"     => "https://www.example.com/"  // 帮助文档链接
    ];
}

在后台服务器配置页面测试与第三方 API 的连接。

function default_TestLink($params) {
    // $params 包含服务器配置信息
    $server = $params['server'];
    
    // 尝试连接第三方 API
    // ... 连接逻辑 ...
    
    // 返回格式
    return [
        "code" => "1",           // 1=成功, 0=失败
        "msg"  => "连接成功"     // 提示信息
    ];
}

3. 配置字段

3.1 服务器配置 (AdminConfigOptions)

后台添加服务器时显示的配置字段。

function default_AdminConfigOptions() {
    return [
        [
            "name"    => "api_key",           // 字段标识
            "title"   => "API密钥",            // 显示标题
            "type"    => "input",             // 字段类型
            "prompt"  => "请输入API密钥",       // 提示信息
            "value"   => ""                   // 默认值
        ],
        [
            "name"    => "region",
            "title"   => "默认区域",
            "type"    => "select",
            "prompt"  => "选择服务器区域",
            "value"   => "cn-hangzhou",
            "options" => [
                'cn-hangzhou' => '华东1(杭州)',
                'cn-beijing'  => '华北2(北京)',
                'cn-shenzhen' => '华南1(深圳)'
            ]
        ],
    ];
}

3.2 产品配置 (ConfigOptions)

添加产品时显示的配置字段。

function default_ConfigOptions() {
    return [
        [
            "name"    => "os_type",
            "title"   => "操作系统",
            "type"    => "select",
            "prompt"  => "选择默认操作系统",
            "value"   => "centos8',
            "option"  => ["centos7", "centos8", "ubuntu20", "windows2019"]
        ],
        [
            "name"    => "bandwidth",
            "title"   => "带宽(Mbps)",
            "type"    => "number",
            "prompt"  => "请输入带宽大小",
            "value"   => "10"
        ],
    ];
}

3.3 业务配置 (HostConfigOptions)

用户购买后,针对单个业务的配置字段。

function default_HostConfigOptions() {
    return [
        [
            "name"    => "instance_id",
            "title"   => "实例ID",
            "type"    => "input",
            "prompt"  => "第三方平台的实例ID",
            "value"   => ""
        ],
        [
            "name"    => "auto_backup",
            "title"   => "自动备份",
            "type"    => "switch",
            "prompt"  => "是否开启自动备份",
            "value"   => "1"  // 1=开启, 0=关闭
        ],
    ];
}

4. 控制面板

4.1 定义菜单 (ClientArea)

定义用户控制面板中显示的菜单项。

function default_ClientArea($params) {
    return [
        "overview" => [
            "name" => "概览"           // 菜单显示名称
        ],
        "manage" => [
            "name" => "实例管理"
        ],
        "logs" => [
            "name" => "操作日志"
        ],
    ];
}

4.2 页面输出 (ClientAreaOutput)

根据菜单 key 返回对应的模板和数据。

function default_ClientAreaOutput($params, $key) {
    if ($key == "overview") {
        // 获取实例信息
        $instance = getInstanceInfo($params);
        
        return [
            "template" => "templates/overview.html",  // 模板路径
            "vars"     => [                           // 传递给模板的变量
                'instance' => $instance,
                'status'   => $instance['status'],
                'ip'       => $params['host']['dedicatedip'],
            ]
        ];
    }
    
    if ($key == "manage") {
        return [
            "template" => "templates/manage.html",
            "vars"     => [
                'host'    => $params['host'],
                'actions' => ['start', 'stop', 'reboot']
            ]
        ];
    }
}

5. 生命周期函数

5.1 开通 (CreateAccount)

用户支付成功后调用,用于在第三方平台创建资源。

function default_CreateAccount($params) {
    $server = $params['server'];           // 服务器信息
    $product = $params['product'];         // 产品信息
    $host = $params['host'];               // 业务信息
    $server_meta = $params['server_meta']; // 服务器配置字段值
    $configoptions = $params['configoptions']; // 产品配置字段值
    $host_meta = $params['host_meta'];     // 业务配置字段值
    
    try {
        // 调用第三方 API 创建实例
        $result = createInstance([
            'hostname' => $host['domain'],
            'username' => $host['username'],
            'password' => $host['password'],
            'os'       => $configoptions['os_type'],
            'region'   => $server_meta['region'],
        ]);
        
        if ($result['success']) {
            // 保存实例ID到业务元数据
            $model = new \app\admin\model\HostMeta();
            $model->ensureProductLevelField(
                $host['id'],
                'instance_id',
                $result['instance_id'],
                '实例ID',
                '第三方平台实例标识'
            );
            
            return ["code" => "1", "msg" => "开通成功"];
        } else {
            return ["code" => "0", "msg" => $result['error']];
        }
    } catch (Exception $e) {
        return ["code" => "0", "msg" => "开通失败:" . $e->getMessage()];
    }
}

5.2 暂停 (SuspendAccount)

暂停业务时调用。

function default_SuspendAccount($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if (empty($instance_id)) {
        return ["code" => "0", "msg" => "实例ID不存在"];
    }
    
    // 调用 API 暂停/关机
    $result = suspendInstance($instance_id);
    
    if ($result['success']) {
        return ["code" => "1", "msg" => "暂停成功"];
    } else {
        return ["code" => "0", "msg" => $result['error']];
    }
}

5.3 解除暂停 (UnsuspendAccount)

恢复业务时调用。

function default_UnsuspendAccount($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    // 调用 API 启动实例
    $result = startInstance($instance_id);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "开启成功" : $result['error']
    ];
}

5.4 终止/删除 (TerminateAccount)

删除业务时调用,应清理第三方平台资源。

function default_TerminateAccount($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if (empty($instance_id)) {
        return ["code" => "1", "msg" => "实例不存在,直接删除"];
    }
    
    // 调用 API 删除实例
    $result = deleteInstance($instance_id);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "删除成功" : $result['error']
    ];
}

5.5 续费 (Renew)

业务续费时调用。

function default_Renew($params) {
    // $params['cycle'] 续费周期:1M=1个月, 1H=1小时, 1D=1天
    $cycle = $params['cycle'];
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    // 调用 API 续费
    $result = renewInstance($instance_id, $cycle);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "续费成功" : $result['error']
    ];
}

5.6 升降级 (ChangePackage)

修改产品配置时调用。

function default_ChangePackage($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    $new_config = $params['configoptions'];  // 新的配置
    
    // 调用 API 修改配置
    $result = changePackage($instance_id, $new_config);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "升降级成功" : $result['error']
    ];
}

6. 自定义按钮

6.1 后台按钮 (AdminButton)

function default_AdminButton() {
    return [
        'ResetPassword' => '重置密码',
        'ReinstallOS'   => '重装系统',
        'VNC'           => 'VNC控制台',
    ];
}


// 重置密码按钮执行
function default_ResetPassword($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    $new_password = generatePassword();  // 生成新密码
    
    $result = resetPassword($instance_id, $new_password);
    
    if ($result['success']) {
        // 更新本地密码
        Db::name('host')->where('id', $params['host']['id'])->update([
            'password' => encrypt($new_password)
        ]);
        
        return ["code" => "1", "msg" => "重置成功,新密码:" . $new_password];
    } else {
        return ["code" => "0", "msg" => $result['error']];
    }
}

6.2 前台按钮 (ClientButton)

function default_ClientButton() {
    return [
        'Reboot'      => '重启服务器',
        'GetVNC'      => 'VNC连接',
        'ReinstallOS' => '重装系统',
    ];
}


// 重启按钮执行
function default_Reboot($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    $result = rebootInstance($instance_id);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "重启指令已发送" : $result['error']
    ];
}

6.3 后台产品侧按钮 (ProductButton)

function default_ProductButton() {
    return [
        'ResetPassword' => '重置密码',
        'ReinstallOS'   => '重装系统',
        'VNC'           => 'VNC控制台',
    ];
}


// 重置密码按钮执行
function default_ResetPassword($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    $new_password = generatePassword();  // 生成新密码
    
    $result = resetPassword($instance_id, $new_password);
    
    if ($result['success']) {
        // 更新本地密码
        Db::name('host')->where('id', $params['host']['id'])->update([
            'password' => encrypt($new_password)
        ]);
        
        return ["code" => "1", "msg" => "重置成功,新密码:" . $new_password];
    } else {
        return ["code" => "0", "msg" => $result['error']];
    }
}

7. 计划任务

7.1 商品侧计划任务 (ProductCron)

针对某个商品的所有业务执行。

function default_ProductCron() {
    // 获取该商品下的所有活跃业务
    $hosts = Db::name('host')
        ->where('product_id', $params['product']['id'])
        ->where('status', 'Active')
        ->select();
    
    foreach ($hosts as $host) {
        // 同步状态、流量等信息
        syncInstanceStatus($host);
    }
    
    return ["code" => "1", "msg" => "同步完成"];
}

7.2 业务侧计划任务 (HostCron)

针对单个业务执行。

function default_HostCron() {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if (empty($instance_id)) {
        return ["code" => "0", "msg" => "实例ID不存在"];
    }
    
    // 同步流量使用情况
    $traffic = getTrafficUsage($instance_id);
    
    // 保存到业务元数据
    $model = new \app\admin\model\HostMeta();
    $model->ensureProductLevelField(
        $params['host']['id'],
        'traffic_used',
        $traffic['used'],
        '已用流量',
        '本月已用流量(GB)'
    );
    
    return ["code" => "1", "msg" => "流量同步完成"];
}

配置字段类型

类型说明适用场景
input单行文本输入API密钥、用户名、实例ID等
textarea多行文本输入备注、证书内容、多行配置
number数字输入端口号、带宽、内存大小等
select下拉单选区域选择、操作系统、套餐类型

字段属性说明

[
    "name"     => "字段标识",      // 必填,唯一标识
    "title"    => "显示标题",      // 必填,后台显示名称
    "type"     => "input",        // 必填,字段类型
    "prompt"   => "提示信息",      // 选填,输入提示
    "value"    => "默认值",        // 选填,默认值
    
    // select 类型特有
    "options"  => [               // 键值对形式(推荐)
        'key1' => '显示值1',
        'key2' => '显示值2'
    ],
    "option"   => ["值1", "值2"]   // 索引数组形式
]

参数说明

$params 结构详解

$params = [
    // 业务信息
    'host' => [
        'id'            => 57,              // 业务ID
        'user_id'       => 1,               // 用户ID
        'order_id'      => 191,             // 订单ID
        'domain'        => 'example.com',   // 主机名/域名
        'username'      => 'user123',       // 用户名
        'password'      => 'password',      // 密码
        'status'        => 'Active',        // 状态
        'dedicatedip'   => '192.168.1.1',   // 独立IP
        'port'          => '22',            // 端口
        'assignedips'   => '',              // 分配的IP列表
        'ns1'           => '',              // NS1
        'ns2'           => '',              // NS2
        'nextduedate'   => '2026-02-14',    // 到期时间
    ],
    
    // 产品信息
    'product' => [
        'id'            => 15,              // 产品ID
        'product_name'  => '云服务器',       // 产品名称
        'server_id'     => 5,               // 服务器ID
        'custom_fields' => null,            // 自定义字段
    ],
    
    // 服务器信息(API连接信息)
    'server' => [
        'id'       => 5,                    // 服务器ID
        'name'     => '阿里云',              // 服务器名称
        'host'     => 'api.aliyun.com',     // API地址
        'ip'       => '',                   // IP地址
        'security' => '',                   // 安全凭证
        'port'     => '',                   // 端口
        'ssl'      => '1',                  // 是否使用SSL
        'user'     => 'access_key',         // 用户名/AccessKey
        'password' => 'secret_key',         // 密码/SecretKey
    ],
    
    // 服务器配置字段值(AdminConfigOptions定义)
    'server_meta' => [
        'api_key'  => 'xxx',
        'region'   => 'cn-hangzhou',
    ],
    
    // 产品配置字段值(ConfigOptions定义)
    'configoptions' => [
        'os_type'   => 'centos8',
        'bandwidth' => '10',
    ],
    
    // 业务配置字段值(HostConfigOptions定义)
    'host_meta' => [
        'instance_id' => 'i-xxx',
        'auto_backup' => '1',
    ],
];

模板开发

模板文件位置

模板文件存放在插件目录下的 templates 文件夹中。

public\plugins\host\插件标识/
├── 插件标识.php
└── templates/
    ├── overview.html    # 概览页面
    ├── manage.html      # 管理页面
    └── logs.html        # 日志页面

模板路径引用

ClientAreaOutput 函数中引用模板时,使用相对路径:

function aliyun_ClientAreaOutput($params, $key) {
    if ($key == "overview") {
        return [
            "template" => "templates/overview.html",  // 相对插件根目录
            "vars"     => [...]
        ];
    }
}

模板语法

系统使用 ThinkPHP 模板引擎。

<!-- 输出变量 -->
{$vars.instance_id}
{$vars.status}


<!-- 条件判断 -->
{if $vars.status == 'running'}
    <span class="badge badge-success">运行中</span>
{elseif $vars.status == 'stopped'}
    <span class="badge badge-danger">已停止</span>
{else}
    <span class="badge badge-warning">{$vars.status}</span>
{/if}


<!-- 循环 -->
{volist name="vars.logs" id="log"}
    <tr>
        <td>{$log.time}</td>
        <td>{$log.action}</td>
        <td>{$log.result}</td>
    </tr>
{/volist}


<!-- PHP代码 -->
{php}
    print_r($vars);
    // 或者进行数据处理
{/php}

模板示例

<!-- templates/overview.html -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">服务器概览</h3>
    </div>
    <div class="card-body">
        <table class="table table-bordered">
            <tr>
                <td width="150">实例ID</td>
                <td>{$vars.instance_id}</td>
            </tr>
            <tr>
                <td>状态</td>
                <td>
                    {if $vars.status == 'running'}
                        <span class="text-success">● 运行中</span>
                    {else/}
                        <span class="text-danger">● 已停止</span>
                    {/if}
                </td>
            </tr>
            <tr>
                <td>IP地址</td>
                <td>{$vars.ip}</td>
            </tr>
            <tr>
                <td>操作系统</td>
                <td>{$vars.os}</td>
            </tr>
        </table>
    </div>
</div>

开发示例

完整插件示例:简易云服务器

假设插件标识为 cloud,则目录结构为:

public\plugins\host\cloud/
├── cloud.php
└── templates/
    ├── overview.html
    └── console.html

cloud.php 完整代码:

<?php


use think\Db;


// ========== 基础信息 ==========
function cloud_MetaData() {
    return [
        "DisplayName" => "简易云服务器",
        "APIVersion"  => "1.0.0",
        "HelpDoc"     => "https://docs.example.com"
    ];
}


function cloud_TestLink($params) {
    $server = $params['server'];
    // 测试 API 连接
    $response = httpRequest($server['host'] . '/api/test', [
        'access_key' => $server['user'],
        'secret_key' => $server['password']
    ]);
    
    if ($response['code'] == 200) {
        return ["code" => "1", "msg" => "连接成功"];
    }
    return ["code" => "0", "msg" => "连接失败:" . $response['msg']];
}


// ========== 配置字段 ==========
function cloud_AdminConfigOptions() {
    return [
        [
            "name"    => "api_endpoint",
            "title"   => "API地址",
            "type"    => "input",
            "prompt"  => "例如:https://api.example.com",
            "value"   => ""
        ],
        [
            "name"    => "default_region",
            "title"   => "默认区域",
            "type"    => "select",
            "prompt"  => "选择默认区域",
            "value"   => "zone-a",
            "options" => [
                'zone-a' => 'A区',
                'zone-b' => 'B区',
                'zone-c' => 'C区'
            ]
        ],
    ];
}


function cloud_ConfigOptions() {
    return [
        [
            "name"    => "cpu",
            "title"   => "CPU核心数",
            "type"    => "select",
            "prompt"  => "选择CPU配置",
            "value"   => "2",
            "option"  => ["1", "2", "4", "8"]
        ],
        [
            "name"    => "memory",
            "title"   => "内存(GB)",
            "type"    => "select",
            "prompt"  => "选择内存配置",
            "value"   => "4",
            "option"  => ["1", "2", "4", "8", "16"]
        ],
        [
            "name"    => "disk",
            "title"   => "磁盘(GB)",
            "type"    => "number",
            "prompt"  => "磁盘大小",
            "value"   => "50"
        ],
    ];
}


function cloud_HostConfigOptions() {
    return [
        [
            "name"    => "instance_id",
            "title"   => "实例ID",
            "type"    => "input",
            "prompt"  => "系统自动填充",
            "value"   => ""
        ],
    ];
}


// ========== 控制面板 ==========
function cloud_ClientArea($params) {
    return [
        "overview" => ["name" => "概览"],
        "console"  => ["name" => "控制台"],
    ];
}


function cloud_ClientAreaOutput($params, $key) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if ($key == "overview") {
        // 获取实例详情
        $detail = getInstanceDetail($params, $instance_id);
        
        return [
            "template" => "templates/cloud/overview.html",
            "vars"     => [
                'instance' => $detail,
                'host'     => $params['host']
            ]
        ];
    }
    
    if ($key == "console") {
        return [
            "template" => "templates/cloud/console.html",
            "vars"     => [
                'instance_id' => $instance_id
            ]
        ];
    }
}


// ========== 生命周期 ==========
function cloud_CreateAccount($params) {
    try {
        $result = createCloudServer($params);
        
        if ($result['success']) {
            // 保存实例ID
            $model = new \app\admin\model\HostMeta();
            $model->ensureProductLevelField(
                $params['host']['id'],
                'instance_id',
                $result['instance_id'],
                '实例ID',
                '云平台实例标识'
            );
            
            // 更新IP地址
            if (!empty($result['ip'])) {
                Db::name('host')->where('id', $params['host']['id'])->update([
                    'dedicatedip' => $result['ip']
                ]);
            }
            
            return ["code" => "1", "msg" => "开通成功"];
        }
        
        return ["code" => "0", "msg" => $result['error']];
    } catch (Exception $e) {
        return ["code" => "0", "msg" => "开通失败:" . $e->getMessage()];
    }
}


function cloud_SuspendAccount($params) {
    return controlInstance($params, 'stop');
}


function cloud_UnsuspendAccount($params) {
    return controlInstance($params, 'start');
}


function cloud_TerminateAccount($params) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if (empty($instance_id)) {
        return ["code" => "1", "msg" => "删除成功"];
    }
    
    $result = deleteCloudServer($params, $instance_id);
    
    return [
        "code" => $result['success'] ? "1" : "0",
        "msg"  => $result['success'] ? "删除成功" : $result['error']
    ];
}


function cloud_Renew($params) {
    // 续费逻辑
    return ["code" => "1", "msg" => "续费成功"];
}


function cloud_ChangePackage($params) {
    // 升降级逻辑
    return ["code" => "1", "msg" => "配置变更成功"];
}


// ========== 按钮 ==========
function cloud_AdminButton() {
    return [
        'ResetPassword' => '重置密码',
        'ReinstallOS'   => '重装系统',
    ];
}


function cloud_ClientButton() {
    return [
        'Reboot'   => '重启',
        'Shutdown' => '关机',
        'Start'    => '开机',
    ];
}


function cloud_Reboot($params) {
    return controlInstance($params, 'reboot');
}


function cloud_Shutdown($params) {
    return controlInstance($params, 'stop');
}


function cloud_Start($params) {
    return controlInstance($params, 'start');
}


// ========== 辅助函数 ==========
function controlInstance($params, $action) {
    $instance_id = $params['host_meta']['instance_id'] ?? '';
    
    if (empty($instance_id)) {
        return ["code" => "0", "msg" => "实例ID不存在"];
    }
    
    $server = $params['server'];
    $api_url = $params['server_meta']['api_endpoint'] ?? $server['host'];
    
    $response = httpRequest($api_url . '/api/instance/' . $action, [
        'access_key'  => $server['user'],
        'secret_key'  => $server['password'],
        'instance_id' => $instance_id
    ]);
    
    $action_names = [
        'start'  => '开机',
        'stop'   => '关机',
        'reboot' => '重启'
    ];
    
    if ($response['code'] == 200) {
        return ["code" => "1", "msg" => $action_names[$action] . "成功"];
    }
    return ["code" => "0", "msg" => $response['msg']];
}


function httpRequest($url, $data) {
    // HTTP请求实现
    // 实际开发中请使用系统的 HTTP 类或 curl
}

最佳实践

1. 错误处理

function default_CreateAccount($params) {
    try {
        // API 调用
        $result = apiCall();
        
        if (!$result) {
            return ["code" => "0", "msg" => "API返回空数据"];
        }
        
        return ["code" => "1", "msg" => "成功"];
        
    } catch (\Exception $e) {
        // 记录日志
        trace("开通失败:" . $e->getMessage(), 'error');
        
        return ["code" => "0", "msg" => "开通失败:" . $e->getMessage()];
    }
}

2. 数据验证

function default_CreateAccount($params) {
    // 验证必要字段
    if (empty($params['server']['user'])) {
        return ["code" => "0", "msg" => "服务器用户名未配置"];
    }
    
    if (empty($params['host']['domain'])) {
        return ["code" => "0", "msg" => "主机名不能为空"];
    }
    
    // 继续执行...
}

3. 元数据操作

// 保存数据到业务元数据
$model = new \app\admin\model\HostMeta();


// 简单保存
$model->ensureProductLevelField($host_id, 'key', 'value');


// 带描述的保存
$model->ensureProductLevelField(
    $host_id,           // 业务ID
    'traffic_used',     // 字段名
    '1024',             // 字段值
    '已用流量(GB)',      // 中文标题
    '本月已使用流量'      // 描述
);

4. 安全建议

  • 敏感信息(API密钥等)使用系统提供的加密存储
  • 所有 API 调用使用 HTTPS
  • 对用户输入进行过滤和验证
  • 密码等敏感字段不要明文记录在日志中

5. 调试技巧

// 使用系统日志
trace("调试信息", 'info');
trace("错误信息", 'error');


// 在模板中调试
{php}
print_r($vars);
{/php}

附录

返回码规范

code含义
1成功
0失败

状态常量

状态说明
Pending待开通
Active正常
Suspended已暂停
Terminated已终止

这篇文章对您有帮助吗?

阅读设置