惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
C
Cisco Blogs
The Hacker News
The Hacker News
T
Threatpost
S
Schneier on Security
K
Kaspersky official blog
Spread Privacy
Spread Privacy
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
NISL@THU
NISL@THU
量子位
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
Security Latest
Security Latest
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
News and Events Feed by Topic
爱范儿
爱范儿
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Cisco Talos Blog
Cisco Talos Blog
GbyAI
GbyAI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
T
Tenable Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
Forbes - Security
Forbes - Security
博客园 - 三生石上(FineUI控件)
C
Cyber Attacks, Cyber Crime and Cyber Security
N
News and Events Feed by Topic
V
V2EX
Webroot Blog
Webroot Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
Scott Helme
Scott Helme
Simon Willison's Weblog
Simon Willison's Weblog
L
LangChain Blog
W
WeLiveSecurity
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Build a WordPress Plugin Licensing System from Scratch (Without Freemius)
Canopus agency · 2026-06-17 · via DEV Community

If you're shipping a commercial WordPress plugin, sooner or later you'll need a licensing system. Something that lets paying customers activate the plugin on their site, locks it to that domain, and stops people from sharing the same key across fifty sites.

The default answer in the WordPress world is Freemius or EDD Software Licensing. They're great. They're also a revenue share, a third-party dependency, and a black box you don't control.

When we built RideCab WP, a commercial WooCommerce taxi booking plugin, we decided to build our own. Here's the architecture, the code, and the gotchas we hit along the way.

What a Licensing System Actually Needs to Do

Before writing any code, get clear on the requirements. A real plugin licensing system needs to:

  1. Generate unique license keys when someone buys
  2. Let the customer activate the key on their site
  3. Bind that key to one (or N) domains
  4. Validate the key periodically so revoked or expired keys stop working
  5. Handle deactivation when a customer moves to a new domain
  6. Fail gracefully — never lock a paying customer out because your license server hiccuped
  7. Optionally: deliver plugin updates only to valid license holders

We'll cover 1 through 6 in this post. Update delivery is a separate beast and I'll write it up next.

The Architecture

The system has two halves that live in two different places.

The license server runs on your own infrastructure — for us, it's a WordPress must-use plugin (mu-plugin) on the same WordPress install that powers our marketing site. It:

  • Stores license keys in a custom database table
  • Exposes a small REST API for activate, deactivate, and validate calls
  • Provides an admin dashboard to view, create, and revoke keys

The client is a PHP class shipped inside the commercial plugin (RideCab WP, in our case). It:

  • Adds a license settings page to the plugin
  • Calls home on activation
  • Caches the validation result
  • Re-validates quietly in the background

Two pieces, talking over HTTPS, with the customer's domain as the binding key.

Step 1: The License Server — Database Schema

On the server side, the simplest workable schema is one table:

\`php
global $wpdb;
$table = $wpdb->prefix . 'plugin_licenses';

$sql = "CREATE TABLE $table (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
license_key VARCHAR(64) NOT NULL,
customer_email VARCHAR(191) NOT NULL,
product_slug VARCHAR(64) NOT NULL,
status ENUM('active','revoked','expired') DEFAULT 'active',
activations LONGTEXT NULL,
max_activations TINYINT UNSIGNED DEFAULT 1,
expires_at DATETIME NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY license_key (license_key)
) {$wpdb->get_charset_collate()};";

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
`\

The activations column is a JSON-encoded array of { domain, activated_at } pairs. For more than a few products this should probably be a separate table — but for most plugin authors, JSON in one column is plenty.

Step 2: Generating License Keys

Keep them short enough to be typed if needed, long enough to be unguessable. A common pattern is four blocks of uppercase hex:

\php
function generate_license_key() {
$blocks = [];
for ( $i = 0; $i < 4; $i++ ) {
$blocks[] = strtoupper( bin2hex( random_bytes( 4 ) ) );
}
return implode( '-', $blocks );
// Example: 9F3A2B71-C8D4E5F6-1A2B3C4D-5E6F7081
}
\
\

random_bytes() is cryptographically secure. Don't use rand() or uniqid() for license keys — they're predictable.

Hook key generation into your order completion flow. If you're using WooCommerce on the server side to sell the plugin, that's woocommerce_order_status_completed.

Step 3: The REST API

Three endpoints are enough. Register them on rest_api_init:

\php
add_action( 'rest_api_init', function() {
register_rest_route( 'license/v1', '/activate', [
'methods' => 'POST',
'callback' => 'license_activate',
'permission_callback' => '__return_true',
] );
register_rest_route( 'license/v1', '/deactivate', [
'methods' => 'POST',
'callback' => 'license_deactivate',
'permission_callback' => '__return_true',
] );
register_rest_route( 'license/v1', '/validate', [
'methods' => 'POST',
'callback' => 'license_validate',
'permission_callback' => '__return_true',
] );
} );
\
\

The activate handler is the most important one:

\`php
function license_activate( WP_REST_Request $req ) {
$key = sanitize_text_field( $req->get_param( 'license_key' ) );
$domain = sanitize_text_field( $req->get_param( 'domain' ) );

if ( ! $key || ! $domain ) {
    return new WP_REST_Response( [ 'success' => false, 'message' => 'Missing parameters' ], 400 );
}

global $wpdb;
$table   = $wpdb->prefix . 'plugin_licenses';
$license = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE license_key = %s", $key ) );

if ( ! $license ) {
    return new WP_REST_Response( [ 'success' => false, 'message' => 'Invalid license key' ], 404 );
}
if ( 'active' !== $license->status ) {
    return new WP_REST_Response( [ 'success' => false, 'message' => 'License is ' . $license->status ], 403 );
}
if ( $license->expires_at && strtotime( $license->expires_at ) < time() ) {
    return new WP_REST_Response( [ 'success' => false, 'message' => 'License expired' ], 403 );
}

$activations = json_decode( $license->activations, true ) ?: [];
$existing    = array_filter( $activations, fn( $a ) => $a['domain'] === $domain );

if ( ! $existing && count( $activations ) >= (int) $license->max_activations ) {
    return new WP_REST_Response( [ 'success' => false, 'message' => 'Activation limit reached' ], 403 );
}

if ( ! $existing ) {
    $activations[] = [ 'domain' => $domain, 'activated_at' => current_time( 'mysql' ) ];
    $wpdb->update( $table, [ 'activations' => wp_json_encode( $activations ) ], [ 'id' => $license->id ] );
}

return new WP_REST_Response( [
    'success'    => true,
    'expires_at' => $license->expires_at,
], 200 );

}
`\

The validate and deactivate handlers follow the same pattern: look up the license, check status, update activations as needed.

Step 4: The Client Class

This lives inside the commercial plugin. It's what calls the server.

\`php
class Plugin_License_Client {

const OPTION_KEY   = 'my_plugin_license_key';
const TRANSIENT    = 'my_plugin_license_valid';
const API_BASE     = 'https://yourdomain.com/wp-json/license/v1';
const CACHE_PERIOD = WEEK_IN_SECONDS;

public function is_valid() {
    $cached = get_transient( self::TRANSIENT );
    if ( false !== $cached ) {
        return (bool) $cached;
    }
    $valid = $this->remote_validate();
    set_transient( self::TRANSIENT, $valid ? 1 : 0, self::CACHE_PERIOD );
    return $valid;
}

public function activate( $license_key ) {
    $response = wp_remote_post( self::API_BASE . '/activate', [
        'timeout' => 15,
        'body'    => [
            'license_key' => $license_key,
            'domain'      => $this->current_domain(),
        ],
    ] );
    if ( is_wp_error( $response ) ) {
        return [ 'success' => false, 'message' => 'Could not reach license server' ];
    }
    $body = json_decode( wp_remote_retrieve_body( $response ), true );
    if ( ! empty( $body['success'] ) ) {
        update_option( self::OPTION_KEY, $license_key );
        set_transient( self::TRANSIENT, 1, self::CACHE_PERIOD );
    }
    return $body;
}

private function remote_validate() {
    $key = get_option( self::OPTION_KEY );
    if ( ! $key ) {
        return false;
    }
    $response = wp_remote_post( self::API_BASE . '/validate', [
        'timeout' => 10,
        'body'    => [
            'license_key' => $key,
            'domain'      => $this->current_domain(),
        ],
    ] );
    if ( is_wp_error( $response ) ) {
        // Fail open: don't punish customers for our server being down.
        return true;
    }
    $body = json_decode( wp_remote_retrieve_body( $response ), true );
    return ! empty( $body['success'] );
}

private function current_domain() {
    return wp_parse_url( home_url(), PHP_URL_HOST );
}

}
`\

Notice the // Fail open comment in remote_validate(). This is the single most important design decision in the whole system.

Step 5: Fail Open, Not Closed

When your license server is unreachable — and it will be unreachable sometimes, because the internet is the internet — what should happen?

Fail closed: the plugin disables itself until it can re-validate. Customers see a broken site. They email you. Your reputation craters.

Fail open: the plugin keeps working. A small percentage of bad actors might get a few extra hours of unlicensed use. So what.

Always fail open. Your paying customers are the ones you have to protect, and they're the ones who suffer most when validation calls fail. Pirates will pirate either way.

A reasonable middle ground: cache the last successful validation for a week. If the server is unreachable, keep working off the cache for up to 30 days. After 30 days of no successful validation, show a non-blocking admin notice. Never disable the plugin outright.

Step 6: The Settings Page

Customers need a place to enter their key. A minimal settings page does the job:

\`php
add_action( 'admin_menu', function() {
add_options_page(
'My Plugin License',
'My Plugin License',
'manage_options',
'my-plugin-license',
'render_license_page'
);
} );

function render_license_page() {
$client = new Plugin_License_Client();

if ( isset( $_POST['license_key'] ) && check_admin_referer( 'my_plugin_license' ) ) {
    $result = $client->activate( sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) );
    echo '<div class="notice notice-' . ( $result['success'] ? 'success' : 'error' ) . '"><p>'
        . esc_html( $result['message'] ?? 'License activated.' ) . '</p></div>';
}

$current = get_option( Plugin_License_Client::OPTION_KEY );
?>
<div class="wrap">
    <h1>License</h1>
    <form method="post">
        <?php wp_nonce_field( 'my_plugin_license' ); ?>
        <input type="text" name="license_key" value="<?php echo esc_attr( $current ); ?>" class="regular-text" />
        <?php submit_button( 'Activate License' ); ?>
    </form>
</div>
<?php

}
`\

In production you'll want better UX — show the activation status, the bound domain, a deactivate button. But this is the minimal viable settings page.

Common Mistakes to Avoid

A few things I've seen go wrong, both in our system and in others:

  • Validating on every page load. Kills performance, multiplies failure modes. Cache it.
  • Hardcoding the license server URL with http://. Use HTTPS. Always.
  • Storing license keys in plain options without sanitization. Treat them like passwords on input.
  • Not handling the staging/dev case. Customers will test on staging.theirsite.com. Decide whether you grant a free extra activation for *.dev, *.local, staging.*, or whether you fail and document the workaround. Either is fine; just decide before you ship.
  • No way for customers to deactivate themselves. They will switch domains. They will rebuild sites. Give them a self-service deactivate button.
  • Logging full license keys server-side. If your server is ever compromised, those logs become a treasure map. Log the last 4 characters only.

What's Next

This system covers everything except update delivery — letting valid license holders pull plugin updates from your server instead of WordPress.org. That's its own write-up because it involves WordPress's pre_set_site_transient_update_plugins filter and serving zipped plugin packages from your server. I'll cover it in a follow-up.

If you want to see this system running in production, it's what powers licensing for RideCab WP, our commercial WooCommerce taxi booking plugin. Same architecture as above, with a few extra layers for domain wildcards and team licenses.

Questions on any part of this? Drop them in the comments — happy to go deeper on the API design, the caching strategy, or the failure modes.