site_domain = $_SERVER['HTTP_HOST'] ?? '';
// 初始化钩子
add_action('admin_init', [$this, 'verify_license']);
add_action('plugins_loaded', [$this, 'load_core_logic']);
}
/**
* 验证授权有效性
* @return bool
*/
public function verify_license() {
// 先读缓存,减少API请求
$license_status = get_transient($this->license_cache_key);
if ($license_status !== false) {
return $license_status === 'valid';
}
// 本地存储的授权码(实际生产环境建议存在wp_options加密存储)
$license_key = get_option('my_plugin_license_key', '');
if (empty($license_key)) {
$this->set_license_status(false);
return false;
}
// 请求授权服务端验证
$response = wp_remote_post($this->license_api, [
'body' => [
'license_key' => $license_key,
'domain' => $this->site_domain,
'plugin_version' => MY_PLUGIN_VERSION
],
'timeout' => 10
]);
if (is_wp_error($response)) {
$this->set_license_status(false);
return false;
}
$body = json_decode(wp_remote_retrieve_body($response), true);
$is_valid = !empty($body['valid']) && $body['domain'] === $this->site_domain;
// 缓存授权状态24小时
$this->set_license_status($is_valid, 24 * HOUR_IN_SECONDS);
return $is_valid;
}
/**
* 加载核心加密逻辑
*/
public function load_core_logic() {
if (!$this->verify_license()) {
// 授权失效提示,实际可做更友好的提示
add_action('admin_notices', function() {
echo '插件授权无效,请购买正版授权后使用。
';
});
return;
}
// 校验核心文件完整性,防止被篡改
if (!$this->verify_file_integrity()) {
add_action('admin_notices', function() {
echo '插件核心文件被篡改,请重新安装官方版本。
';
});
return;
}
// 加载加密后的核心文件(实际生产环境建议用ioncube等加密工具加密此文件)
require_once $this->encrypted_core_file;
}
/**
* 设置授权状态缓存
*/
private function set_license_status(bool $status, int $expire = 0) {
set_transient($this->license_cache_key, $status ? 'valid' : 'invalid', $expire);
}
/**
* 校验核心文件哈希,防止被篡改
* @return bool
*/
private function verify_file_integrity(): bool {
$original_hash = '这里放核心文件发布时的SHA256哈希值';
if (!file_exists($this->encrypted_core_file)) {
return false;
}
return hash_file('sha256', $this->encrypted_core_file) === $original_hash;
}
}
// 初始化保护类
new WP_Plugin_Protector();
然后这个代码是可运行的,只要替换对应的API地址如需更完整的 PHP 代码保护与在线加密服务,可访问 https://article.vvxyz.com 了解更多。