WordPress 插件如何安全调用 OpenAI-compatible

前言

随着大模型的普及,许多 WordPress 插件需要集成 AI 功能。OpenAI 提供的 API 接口已成为事实上的标准,许多第三方服务(如 Azure OpenAI、LocalAI、Moonshot 等)都提供了兼容接口。本文将指导初学者如何在 WordPress 插件中安全、稳定地调用这些接口。

步骤一:安全存储 API Key

绝对不要将 API Key 直接写在插件代码中,否则一旦代码泄露,密钥即泄露。推荐使用 WordPress 数据库的 wp_options 表来存储。

在插件设置页面保存 Key:

// 保存 API Key
update_option( 'my_plugin_api_key', sanitize_text_field( $_POST['api_key'] ) );

在调用时读取 Key:

$api_key = get_option( 'my_plugin_api_key' );
if ( empty( $api_key ) ) {
    return new WP_Error( 'no_key', '请先配置 API Key' );
}

步骤二:使用 wp_remote_post 发起请求

WordPress 提供了 WP_Http 类(封装在 wp_remote_post 等函数中)来处理 HTTP 请求,这比直接使用 cURL 更安全且兼容性更好。

以下是一个封装好的调用函数示例:

function my_plugin_call_openai_compatible( $prompt, $model = 'gpt-3.5-turbo' ) {
    $api_key = get_option( 'my_plugin_api_key' );
    $api_url = 'https://api.openai.com/v1/chat/completions'; // 可替换为兼容接口地址

    $body = array(
        'model' => $model,
        'messages' => array(
            array(
                'role' => 'user',
                'content' => $prompt
            )
        ),
        'temperature' => 0.7
    );

    $response = wp_remote_post( $api_url, array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
        ),
        'body'        => wp_json_encode( $body ),
        'timeout'     => 45, // AI 接口响应较慢,建议增加超时时间
        'data_format' => 'body',
    ) );

    // 错误处理与响应解析见下一步骤
    return $response;
}

步骤三:处理响应与错误

HTTP 请求可能会失败,或者 API 返回错误信息。必须对返回结果进行检查。

// 接上一步骤
if ( is_wp_error( $response ) ) {
    // WordPress 层面的错误(如网络超时)
    return '请求失败: ' . $response->get_error_message();
}

$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body, true );

if ( json_last_error() !== JSON_ERROR_NONE ) {
    return '数据解析失败';
}

if ( isset( $data['error'] ) ) {
    // API 层面的错误(如 Key 无效、余额不足)
    return 'API 错误: ' . $data['error']['message'];
}

// 获取回复内容
return $data['choices'][0]['message']['content'] ?? '';

常见坑与排查方式

1. 超时问题

AI 生成内容通常需要几秒钟。WordPress 默认 HTTP 超时时间可能只有 5 秒。务必在 wp_remote_post 参数中设置 'timeout' => 45 或更长。

2. 混淆 Content-Type

必须设置 Content-Type: application/json。如果遗漏,API 将无法解析请求体,返回 400 错误。

3. 调试困难

不要直接在前端输出 API 的原始报错,这会暴露接口细节。建议使用 error_log 记录日志:

error_log( print_r( $response, true ) );

4. 代理与 SSL

如果你的服务器无法直接访问 OpenAI(国内常见情况),你需要配置代理或使用中转服务。如果是自签名的 SSL 证书(本地开发),可能需要暂时关闭 SSL 验证(仅开发环境!):'sslverify' => false

总结

通过 wp_remote_post 结合 wp_options,我们可以构建一个既安全又标准的 AI 调用模块。记得做好错误捕获,避免因 API 故障导致网站崩溃。

温馨提示:本文最后更新于2026-03-10 13:07:03,某些文章具有时效性,若有错误或已失效,请在下方 留言或联系
© 版权声明
THE END
喜欢就支持一下吧
点赞14赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容