咨询热线:15911225507
龙霄
登录
首页-所有文章-WordPress英文-正文

Hardening WordPress Custom REST API Security and Automating WeChat Article Formatting

龙霄龙霄
WordPress英文
6天前
0
0
17

Overview

In a Headless WordPress architecture, custom REST API endpoints serve as the critical bridge between your CMS and external systems. However, production environments often present two key challenges: API authentication compatibility across diverse server configurations, and strict content formatting requirements imposed by third-party platforms like WeChat Official Accounts. This article shares how Salong Network optimized both pain points in the Longxiao Theme project.

1. Hardening Custom REST API Security

In earlier versions, we defined the API key using define('HERMES_AI_PUBLISH_API_KEY', 'xxx') and validated requests by comparing constants in the authentication callback. This approach revealed two issues in real deployments:

1.1 Silent Constant Overrides

WordPress's define() is idempotent — if the same constant name is defined elsewhere first, your plugin's definition is silently ignored. On Salong Network's servers, theme or framework code might define a constant with the same name, rendering the plugin's preset key invalid. The fix uses a defined() guard with a more unique constant name:

if (!defined('HERMES_PUBLISH_SECRET')) {
    define('HERMES_PUBLISH_SECRET', 'hermes-ai-publish-key-2026');
}

An even more robust approach is to hardcode the key directly in the authentication comparison, completely eliminating constant resolution ambiguity:

return !empty($key) && $key === 'hermes-ai-publish-key-2026';

1.2 Multi-Level Header Fallback Chain

Nginx, CDNs, or security plugins may normalize custom HTTP headers (e.g., converting to lowercase) or even strip them entirely. To ensure compatibility, the authentication logic needs a multi-level header fallback chain:

$key = $request->get_header('X-Hermes-Key');        // WP normalized
if (empty($key)) $key = $request->get_header('x-hermes-key'); // all lowercase
if (empty($key)) $key = $_SERVER['HTTP_X_HERMES_KEY'] ?? '';  // raw header
if (empty($key)) $key = $request->get_param('key');           // query param

This chain covers WP REST API normalization, Nginx lowercase conversion, and the extreme case of stripped headers falling back to query string passing.

1.3 The Value of a Debug Endpoint

When debugging API authentication issues in production, adding an unauthenticated /debug endpoint can save hours of troubleshooting. It returns the raw request headers and the current resolved constant value:

register_rest_route('hermes/v1', '/debug', [
    'methods'  => 'GET',
    'callback' => function ($request) {
        return rest_ensure_response([
            'headers'     => $request->get_headers(),
            'param_key'   => $request->get_param('key'),
            'defined_key' => defined('HERMES_PUBLISH_SECRET') 
                ? HERMES_PUBLISH_SECRET : 'NOT_DEFINED',
        ]);
    },
    'permission_callback' => '__return_true',
]);

With this endpoint, you can quickly verify whether request headers are reaching WordPress correctly, whether the constant has been overridden, and at which exact step authentication is failing.

2. Automating WeChat Article Formatting

Salong Network's Longxiao Theme integrates WeChat Official Account draft synchronization. When a post is published in the WordPress backend, its content must be automatically pushed to the WeChat draft inbox. The core challenge: WeChat's platform has extremely limited HTML support.

2.1 Extracting Typography Settings from Theme Config

The traditional approach hardcodes a fixed set of font sizes and line heights. But Longxiao Theme provides rich theme options that let users customize heading and body font sizes. The improved solution dynamically reads the style_general option from theme configuration:

$styleGeneral = (array) salong_theme_options('style_general');
// Extract fontSize and lineHeight for h1-h6
foreach (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as $tag) {
    $size   = $styleGeneral[$tag]['width'] ?? '';
    $height = $styleGeneral[$tag]['height'] ?? '';
    $h[$tag] = [
        'size'   => $size ? $size . 'px' : '',
        'height' => $height ? $height . 'px' : '',
    ];
}
// Body text prioritizes mobile font size config
$bodySize = $styleGeneral['post_content_mobile']['width'] 
    ?? $styleGeneral['body']['width'] 
    ?? '16px';

The benefit: WeChat formatting automatically follows the theme settings, eliminating the need to maintain a separate style configuration.

2.2 HTML Content Sanitization Pipeline

WeChat does not support <iframe>, <video>, <audio>, <embed>, <script>, <style>, or <link> tags. Additionally, the Gutenberg editor inserts numerous block-level HTML comments (e.g., <!-- wp:paragraph -->) into the output. The sanitization pipeline:

// 1. Remove unsupported tags
$html = preg_replace('/<iframeb[^>]*>.*</iframe>/is', '', $html);
$html = preg_replace('/<videob[^>]*>.*</video>/is', '', $html);
$html = preg_replace('/<audiob[^>]*>.*</audio>/is', '', $html);
$html = preg_replace('/<embedb[^>]*>/i', '', $html);
$html = preg_replace('/<scriptb[^>]*>.*</script>/is', '', $html);
$html = preg_replace('/<styleb[^>]*>.*</style>/is', '', $html);
$html = preg_replace('/<linkb[^>]*>/i', '', $html);

// 2. Remove Gutenberg block comments
$html = preg_replace('/<!--s*/?wp:.*?-->s*/s', '', $html);

// 3. Inject inline styles for paragraphs and images
$html = preg_replace('/<p(?![^>]*bstyle=)([^>]*)>/i', 
    '<p style="margin:0 0 16px;"$1>', $html);
$html = preg_replace('/<img(?![^>]*bstyle=)([^>]*)>/i', 
    '<img style="max-width:100%;height:auto;"$1>', $html);

2.3 Automatic Author Info Population

The new version also adds automatic author information retrieval from WordPress user profiles:

$author_id   = (string) get_the_author_meta('ID', $post_id);
$author_data = User::data($author_id);
$article['author'] = $author_data['name'] ?? '';

It also preserves an extension point for "direct publish" mode, laying the groundwork for future auto-publishing to WeChat (rather than only saving drafts).

3. Key Takeaways

This optimization round is guided by two core principles: defensive programming and configuration-driven design.

On the API security front: never assume a single authentication method will work across all environments. Use multi-level fallbacks, debug endpoints, and hardcoded fallback strategies to ensure service robustness. On the content formatting front: return typography control to the theme configuration system, avoiding the maintenance burden of hardcoded values.

These practices apply equally to other WordPress-to-third-party integration scenarios — whether connecting to WeChat Mini Programs, Feishu Docs, or WeCom, authentication compatibility and content adaptation are engineering concerns that demand serious attention.

标签:
本文原创,作者:龙霄,其版权均为龙霄所有。如需转载,请注明出处:https://lx.yfdxs.com/7315.html
龙霄

龙霄

Lv1Rec2
以 Nuxt.js 之力,焕新 WordPress 体验
197.63W1214.22W1.07W
加载中…
分享:
1
WordPress 自定义 REST API 安全加固与微信公众号排版自动化实践
WordPress 自定义 REST API 安全加固与微信公众号排版自动化实践上一篇
Nuxt 3 项目中集成 AI API 实现智能内容生成与多语言翻译下一篇
Nuxt 3 项目中集成 AI API 实现智能内容生成与多语言翻译
相关文章
总数:0
龙霄
没有相关内容
评论表单游客 您好,欢迎参与讨论。
加载中…
评论列表
总数:0
龙霄
没有相关内容