Kamixitong/docs/EXAMPLES.md
2025-11-11 21:39:12 +08:00

570 lines
16 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 使用示例
本文档提供了KaMiXiTong软件授权管理系统的详细使用示例。
## 目录
1. [后台管理系统使用](#后台管理系统使用)
2. [Python验证器集成](#python验证器集成)
3. [API接口调用示例](#api接口调用示例)
4. [常见场景解决方案](#常见场景解决方案)
## 后台管理系统使用
### 1. 登录系统
首次访问系统时,使用默认管理员账号:
- 用户名: `admin`
- 密码: `admin123`
```python
# 启动系统
python run.py
# 访问地址
http://localhost:5000
```
### 2. 创建产品
```python
# 示例: 创建一个名为"记事本Pro"的产品
import requests
# 登录获取token (简化示例)
login_data = {
"username": "admin",
"password": "admin123"
}
# 创建产品
product_data = {
"product_name": "记事本Pro",
"description": "高级文本编辑器,支持多种格式和插件"
}
response = requests.post(
"http://localhost:5000/api/v1/products",
json=product_data,
headers={"Authorization": "Bearer your_token"}
)
if response.status_code == 200:
result = response.json()
product_id = result["data"]["product_id"]
print(f"产品创建成功ID: {product_id}")
```
### 3. 批量生成卡密
```python
# 生成100个为期1年的正式卡密
import requests
license_data = {
"product_id": "PROD_ABC12345", # 从上一步获得
"count": 100,
"type": 1, # 1=正式, 0=试用
"valid_days": 365,
"prefix": "NOTEPAD_", # 可选前缀
"length": 32
}
response = requests.post(
"http://localhost:5000/api/v1/licenses",
json=license_data,
headers={"Authorization": "Bearer your_token"}
)
if response.status_code == 200:
result = response.json()
licenses = result["data"]["licenses"]
print(f"成功生成 {len(licenses)} 个卡密")
# 保存到文件
with open("licenses.txt", "w") as f:
for license_info in licenses:
f.write(f"{license_info['license_key']}\n")
```
### 4. 发布软件版本
```python
# 发布新版本
version_data = {
"product_id": "PROD_ABC12345",
"version_num": "2.1.0",
"update_log": "新增功能:\n1. 支持Markdown语法\n2. 改进性能\n3. 修复已知问题",
"download_url": "https://example.com/downloads/notepad-pro-2.1.0.exe",
"force_update": 0, # 0=不强制, 1=强制更新
"min_license_version": "1.0.0" # 最低兼容版本
}
response = requests.post(
"http://localhost:5000/api/v1/versions",
json=version_data,
headers={"Authorization": "Bearer your_token"}
)
if response.status_code == 200:
result = response.json()
print(f"版本创建成功: {result['data']['version_num']}")
# 发布版本
version_id = result["data"]["version_id"]
response = requests.post(
f"http://localhost:5000/api/v1/versions/{version_id}/publish",
headers={"Authorization": "Bearer your_token"}
)
```
## Python验证器集成
### 1. 基础集成示例
```python
# main.py - 您的主程序
from auth_validator import AuthValidator
import sys
def check_license():
"""检查授权"""
validator = AuthValidator(
software_id="PROD_ABC12345", # 您的软件ID
api_url="http://your-domain.com/api/v1",
gui_mode=True # 显示图形界面输入框
)
return validator.validate()
def main():
"""主程序"""
print("正在验证授权...")
if not check_license():
print("授权验证失败,程序退出")
sys.exit(1)
print("授权验证通过,启动程序...")
# 您的程序逻辑
print("欢迎使用记事本Pro!")
# ... 您的程序代码 ...
if __name__ == "__main__":
main()
```
### 2. 高级集成示例
```python
# advanced_app.py - 高级集成示例
from auth_validator import AuthValidator
import logging
import sys
import json
class AdvancedValidator:
"""高级验证器"""
def __init__(self, config_file="config.json"):
self.config = self.load_config(config_file)
self.validator = AuthValidator(
software_id=self.config["software_id"],
api_url=self.config["api_url"],
secret_key=self.config.get("secret_key"),
cache_days=self.config.get("cache_days", 7),
gui_mode=self.config.get("gui_mode", True)
)
self.setup_logging()
def load_config(self, config_file):
"""加载配置文件"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
# 创建默认配置
default_config = {
"software_id": "YOUR_SOFTWARE_ID",
"api_url": "http://localhost:5000/api/v1",
"gui_mode": True,
"cache_days": 7
}
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(default_config, f, indent=2, ensure_ascii=False)
return default_config
def setup_logging(self):
"""设置日志"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('app.log', encoding='utf-8'),
logging.StreamHandler()
]
)
def verify_license(self):
"""验证授权"""
try:
logging.info("开始授权验证")
if not self.validator.validate():
logging.error("授权验证失败")
return False
# 获取授权详情
software_info = self.validator.get_software_info()
if software_info:
logging.info(f"软件信息: {software_info}")
logging.info("授权验证成功")
return True
except Exception as e:
logging.error(f"授权验证异常: {e}")
return False
def check_updates(self):
"""检查更新"""
try:
software_info = self.validator.get_software_info()
if software_info and software_info.get('need_update'):
new_version = software_info.get('new_version')
download_url = software_info.get('download_url')
print(f"\n发现新版本: {new_version}")
print(f"下载地址: {download_url}")
if software_info.get('force_update'):
print("此版本为强制更新,请升级后重新启动程序")
return False
# 询问用户是否立即更新
choice = input("是否立即下载更新? (y/n): ").lower()
if choice == 'y':
import webbrowser
webbrowser.open(download_url)
return False
return True
except Exception as e:
logging.warning(f"检查更新失败: {e}")
return True
def main():
"""主程序"""
# 初始化验证器
verifier = AdvancedValidator()
# 验证授权
if not verifier.verify_license():
input("按任意键退出...")
sys.exit(1)
# 检查更新
if not verifier.check_updates():
input("按任意键退出...")
sys.exit(1)
# 启动主程序
print("=" * 50)
print(" 记事本Pro v2.1.0")
print("=" * 50)
print("1. 新建文件")
print("2. 打开文件")
print("3. 关于")
print("4. 退出")
while True:
choice = input("\n请选择操作 (1-4): ")
if choice == '1':
print("新建文件功能...")
elif choice == '2':
print("打开文件功能...")
elif choice == '3':
print("记事本Pro - 高级文本编辑器")
print(f"授权状态: 已激活")
print(f"版本: 2.1.0")
elif choice == '4':
print("感谢使用,再见!")
break
else:
print("无效选择,请重试")
if __name__ == "__main__":
main()
```
## API接口调用示例
### 1. 卡密验证
```python
import requests
import time
import hashlib
def generate_signature(data, secret_key):
"""生成验证签名"""
combined = f"{data['software_id']}{data['license_key']}{data['machine_code']}{data['timestamp']}"
return hashlib.sha256(combined + secret_key).hexdigest()
def verify_license_api(license_key, machine_code, software_id):
"""通过API验证卡密"""
secret_key = "your-secret-key"
api_url = "http://localhost:5000/api/v1/auth/verify"
# 准备请求数据
data = {
"software_id": software_id,
"license_key": license_key,
"machine_code": machine_code,
"timestamp": int(time.time())
}
# 生成签名
data["signature"] = generate_signature(data, secret_key)
# 发送请求
response = requests.post(api_url, json=data)
if response.status_code == 200:
result = response.json()
if result["success"]:
auth_info = result["data"]
print(f"验证成功! 类型: {auth_info['type_name']}")
print(f"有效期至: {auth_info['expire_time'] or '永久'}")
return True
print(f"验证失败: {result.get('message', '未知错误')}")
return False
# 使用示例
license_key = "NOTEPAD_ABC1234567890DEF"
machine_code = "A1B2C3D4E5F678901234567890ABCDEF"
software_id = "PROD_ABC12345"
verify_license_api(license_key, machine_code, software_id)
```
### 2. 批量操作示例
```python
# 批量查询卡密状态
def batch_check_licenses(license_keys, software_id):
"""批量查询卡密状态"""
api_url = "http://localhost:5000/api/v1/licenses"
results = []
for license_key in license_keys:
params = {
"keyword": license_key,
"product_id": software_id
}
response = requests.get(api_url, params=params)
if response.status_code == 200:
result = response.json()
if result["success"] and result["data"]["licenses"]:
license_info = result["data"]["licenses"][0]
results.append({
"license_key": license_key,
"status": license_info["status_name"],
"activate_time": license_info["activate_time"],
"expire_time": license_info["expire_time"]
})
else:
results.append({
"license_key": license_key,
"status": "不存在",
"activate_time": None,
"expire_time": None
})
return results
# 使用示例
license_keys = [
"NOTEPAD_ABC1234567890DEF",
"NOTEPAD_XYZ9876543210ABC",
"NOTEPAD_DEF5678901234GHI"
]
results = batch_check_licenses(license_keys, "PROD_ABC12345")
for result in results:
print(f"{result['license_key']}: {result['status']}")
```
## 常见场景解决方案
### 1. 试用授权场景
```python
# trial_manager.py - 试用管理
from auth_validator import AuthValidator
import time
class TrialManager:
"""试用授权管理"""
def __init__(self, software_id):
self.software_id = software_id
self.validator = AuthValidator(software_id=software_id)
def request_trial(self):
"""申请试用授权"""
print("正在申请试用授权...")
# 这里可以调用API生成试用卡密
# 或者让用户联系管理员
trial_code = input("请输入试用卡密: ").strip()
if self.validator._validate_license_format(trial_code):
return trial_code
return None
def start_trial(self):
"""开始试用"""
trial_code = self.request_trial()
if not trial_code:
return False
# 尝试验证试用卡密
success, message, auth_info = self.validator._online_verify(trial_code)
if success and auth_info and auth_info.get('type') == 0:
days_left = auth_info.get('remaining_days', 0)
print(f"试用激活成功!剩余 {days_left} 天")
return True
else:
print(f"试用激活失败: {message}")
return False
```
### 2. 离线授权场景
```python
# offline_manager.py - 离线授权管理
from auth_validator import AuthValidator, AuthCache
import json
import os
class OfflineManager:
"""离线授权管理"""
def __init__(self, software_id):
self.software_id = software_id
self.cache = AuthCache()
self.license_file = "offline_license.json"
def generate_offline_license(self, license_key, machine_code, expire_days):
"""生成离线授权文件"""
offline_data = {
"software_id": self.software_id,
"license_key": license_key,
"machine_code": machine_code,
"issue_time": time.time(),
"expire_days": expire_days,
"signature": "offline_signature" # 实际应用中需要数字签名
}
with open(self.license_file, 'w') as f:
json.dump(offline_data, f, indent=2)
print(f"离线授权文件已生成: {self.license_file}")
def verify_offline_license(self):
"""验证离线授权"""
if not os.path.exists(self.license_file):
return False, "未找到离线授权文件"
try:
with open(self.license_file, 'r') as f:
offline_data = json.load(f)
# 检查软件ID
if offline_data["software_id"] != self.software_id:
return False, "授权文件不匹配当前软件"
# 检查机器码
current_machine_code = MachineCodeGenerator.generate()
if offline_data["machine_code"] != current_machine_code:
return False, "授权文件不匹配当前设备"
# 检查过期时间
issue_time = offline_data["issue_time"]
expire_days = offline_data["expire_days"]
if time.time() - issue_time > expire_days * 24 * 3600:
return False, "离线授权已过期"
return True, "离线授权验证成功"
except Exception as e:
return False, f"授权文件损坏: {e}"
```
### 3. 多产品授权场景
```python
# multi_product_manager.py - 多产品授权管理
from auth_validator import AuthValidator
class MultiProductManager:
"""多产品授权管理"""
def __init__(self):
self.products = {}
self.validators = {}
def add_product(self, product_id, product_name, api_url):
"""添加产品"""
self.products[product_id] = product_name
self.validators[product_id] = AuthValidator(
software_id=product_id,
api_url=api_url
)
def verify_all_products(self):
"""验证所有产品授权"""
results = {}
for product_id, validator in self.validators.items():
success = validator.validate()
results[product_id] = {
"name": self.products[product_id],
"success": success
}
return results
def get_product_status(self, product_id):
"""获取产品授权状态"""
if product_id not in self.validators:
return None
auth_info = self.validators[product_id].cache.get_auth_info(product_id)
return auth_info
# 使用示例
manager = MultiProductManager()
manager.add_product("PROD_NOTEPAD", "记事本Pro", "http://api.example.com/v1")
manager.add_product("PROD_CALC", "计算器Pro", "http://api.example.com/v1")
# 验证所有产品
results = manager.verify_all_products()
for product_id, result in results.items():
status = "✅ 已授权" if result["success"] else "❌ 未授权"
print(f"{result['name']}: {status}")
```
这些示例涵盖了KaMiXiTong系统的各种使用场景您可以根据实际需求进行调整和扩展。