Python检测微信小程序封禁状态(2025年最新版)

介绍

本教程提供2025年最新版的Python代码,用于检测微信小程序是否被封禁。通过调用微信官方API接口,可以获取小程序状态信息,返回结果中code为1表示小程序正常,为0表示小程序被封禁,并包含详细的封禁原因。

Python代码

import requests
import time
from typing import Dict, List, Optional

class WeChatMiniProgramChecker:
    """
    微信小程序封禁状态检测工具(2025年最新版)
    功能特点:
    - 支持单小程序和批量检测
    - 自动重试机制(默认3次)
    - 结果缓存(默认1小时)
    - 详细的错误处理
    - 支持AppID格式验证
    - 支持代理配置
    """
    
    VERSION = "2025.07"
    STATUS_NORMAL = 1
    STATUS_BANNED = 0
    STATUS_ERROR = -1
    
    def __init__(self, max_retries: int = 3, cache_time: int = 3600, proxy: Optional[str] = None):
        """
        初始化检测器
        :param max_retries: 最大重试次数
        :param cache_time: 结果缓存时间(秒)
        :param proxy: 代理设置,如 "http://127.0.0.1:8080"
        """
        self.api_url = "https://api.wxapi.work/xcx/checkxcx.php"
        self.headers = {
            'User-Agent': f'WeChatMiniProgramChecker/{self.VERSION}',
            'Accept': 'application/json',
            'X-Requested-With': 'Python'
        }
        self.timeout = 10
        self.max_retries = max_retries
        self.cache = {}
        self.cache_time = cache_time
        self.proxy = {'http': proxy, 'https': proxy} if proxy else None
    
    def check_miniprogram(self, appid: str, force_check: bool = False) -> Dict:
        """
        检测小程序状态
        :param appid: 小程序AppID
        :param force_check: 是否强制刷新缓存
        :return: 标准化检测结果
        """
        # 验证AppID格式
        if not self._validate_appid(appid):
            return self._format_error_result(
                appid, 
                "无效的AppID格式,必须以wx开头且长度为18位"
            )
        
        # 检查缓存
        cache_key = appid.lower()
        if not force_check and cache_key in self.cache:
            cached_result = self.cache[cache_key]
            if time.time() - cached_result['timestamp'] < self.cache_time:
                return cached_result['result']
        
        # 执行检测
        result = self._do_check_with_retry(appid)
        
        # 缓存结果
        self.cache[cache_key] = {
            'result': result,
            'timestamp': time.time()
        }
        
        return result
    
    def batch_check(self, appids: List[str], interval: float = 0.5) -> Dict[str, Dict]:
        """
        批量检测小程序状态
        :param appids: 小程序AppID列表
        :param interval: 请求间隔时间(秒)
        :return: 字典形式的结果 {appid: 结果}
        """
        results = {}
        for appid in appids:
            results[appid] = self.check_miniprogram(appid)
            time.sleep(interval)  # 避免请求过于频繁
        return results
    
    def _do_check_with_retry(self, appid: str) -> Dict:
        """带重试机制的检测"""
        for attempt in range(self.max_retries):
            try:
                response = requests.get(
                    f"{self.api_url}?appid={appid}",
                    headers=self.headers,
                    timeout=self.timeout,
                    proxies=self.proxy
                )
                response.raise_for_status()
                return self._parse_response(response.json(), appid)
                
            except requests.exceptions.Timeout:
                if attempt == self.max_retries - 1:
                    return self._format_error_result(appid, "请求超时")
                time.sleep(1)
                
            except requests.exceptions.RequestException as e:
                if attempt == self.max_retries - 1:
                    return self._format_error_result(appid, f"API请求失败: {str(e)}")
                time.sleep(1)
    
    def _parse_response(self, api_response: Dict, original_appid: str) -> Dict:
        """解析API响应"""
        if not isinstance(api_response, dict):
            return self._format_error_result(original_appid, "无效的API响应格式")
        
        # 获取状态码并确保为整数
        status_code = api_response.get("code", self.STATUS_BANNED)
        try:
            status_code = int(status_code)
        except (TypeError, ValueError):
            status_code = self.STATUS_BANNED
        
        return {
            "code": status_code,
            "appid": api_response.get("appid", original_appid),
            "status": api_response.get("status", "未知状态"),
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        }
    
    def _validate_appid(self, appid: str) -> bool:
        """验证AppID格式"""
        return (appid and 
                appid.startswith('wx') and 
                len(appid) == 18 and
                all(c.isalnum() for c in appid))
    
    def _format_error_result(self, appid: str, error_msg: str) -> Dict:
        """格式化错误结果"""
        return {
            "code": self.STATUS_ERROR,
            "appid": appid,
            "status": error_msg,
            "error": True,
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
        }

def main():
    """主函数"""
    # 初始化检测器(可配置代理)
    checker = WeChatMiniProgramChecker(
        max_retries=3,
        cache_time=3600,
        proxy=None  # 例如: "http://127.0.0.1:8080"
    )
    
    # 测试案例
    test_cases = [
        {"appid": "wx81894c6dbb81c2e2", "desc": "已知被封禁的小程序"},
        {"appid": "wx123456789abcdefg", "desc": "假设正常的小程序"},
        {"appid": "invalid_appid", "desc": "无效AppID"},
        {"appid": "", "desc": "空AppID"},
        {"appid": "wx123", "desc": "长度不足的AppID"}
    ]
    
    print(f"微信小程序封禁状态检测报告({time.strftime('%Y年%m月')})")
    print("=" * 90)
    print("{:<25} {:<10} {:<15} {:<40}".format(
        "AppID", "状态", "代码", "详细信息"))
    print("-" * 90)
    
    # 单小程序检测示例
    for case in test_cases:
        result = checker.check_miniprogram(case["appid"])
        
        # 状态描述
        status_desc = {
            checker.STATUS_NORMAL: "正常",
            checker.STATUS_BANNED: "封禁",
            checker.STATUS_ERROR: "错误"
        }.get(result["code"], "未知")
        
        print("{:<25} {:<10} {:<15} {:<40}".format(
            case["appid"] or "[空AppID]",
            status_desc,
            result["code"],
            result["status"]
        ))
        time.sleep(0.5)
    
    # 批量检测示例
    print("\n批量检测示例:")
    appids_to_check = ["wx123456789abcdefg", "wx987654321abcdefg", "wxabcdef123456789"]
    batch_results = checker.batch_check(appids_to_check)
    
    for appid, result in batch_results.items():
        status_desc = "正常" if result["code"] == 1 else "封禁" if result["code"] == 0 else "错误"
        print(f"{appid}: {status_desc} - {result['status']}")

if __name__ == "__main__":
    main()

使用方法

  1. 安装依赖库:

    pip install requests
  2. 基本使用:

    from wechat_miniprogram_checker import WeChatMiniProgramChecker
    
    checker = WeChatMiniProgramChecker()
    result = checker.check_miniprogram("wx81894c6dbb81c2e2")
    print(result)
  3. 批量检测:

    appids = ["wx123456789abcdefg", "wx987654321abcdefg"]
    results = checker.batch_check(appids)
  4. 使用代理:

    checker = WeChatMiniProgramChecker(proxy="http://127.0.0.1:8080")
  5. 运行结果示例:

    {
      "code": 0,
      "appid": "wx81894c6dbb81c2e2",
      "status": "已被封禁,封禁原因:存在绕开、规避或对抗平台审核监管的行为",
      "timestamp": "2025-07-16 15:30:00"
    }

    {
      "code": 1,
      "appid": "wx123456789abcdefg",
      "status": "小程序状态正常",
      "timestamp": "2025-07-16 15:31:00"
    }

2025年更新说明

  1. 采用最新的微信小程序检测API端点
  2. 增强AppID格式验证(必须wx开头、18位长度、仅含字母数字)
  3. 优化API响应解析逻辑
  4. 改进错误处理机制
  5. 添加更详细的控制台输出格式
  6. 支持状态码常量(STATUS_NORMAL/STATUS_BANNED/STATUS_ERROR)

返回结果说明

  • code:
    • 1 表示小程序正常
    • 0 表示小程序被封禁
    • -1 表示检测异常
  • appid: 检测的小程序AppID
  • status: 详细的状态信息或封禁原因
  • timestamp: 检测时间戳

注意事项

  1. 必须提供有效的微信小程序AppID(wx开头,18位)
  2. 微信API有严格的频率限制,建议间隔0.5秒以上
  3. 大量检测建议使用批量模式并添加适当延迟
  4. 本工具仅限合法用途使用

高级功能

  1. 强制刷新缓存:

    result = checker.check_miniprogram(appid, force_check=True)
  2. 自定义缓存时间:

    checker = WeChatMiniProgramChecker(cache_time=1800)  # 30分钟缓存
  3. 结果筛选:

    banned_apps = [r for r in results.values() if r["code"] == 0]
  4. 结果导出:

    import json
    with open("miniprogram_status.json", "w") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)
  5. 从文件导入AppID列表:

    with open("appids.txt") as f:
        appids = [line.strip() for line in f if line.strip()]
    results = checker.batch_check(appids)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值