|
| 1 | +#!/usr/bin/env python3.10 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# author: NearlyHeadlessJack |
| 4 | +# email: wang@rjack.cn |
| 5 | +# datetime: 2025/1/19 21:48 |
| 6 | +# ide: PyCharm |
| 7 | +# file: wtest.py |
| 8 | +import yaml |
| 9 | +import sys |
| 10 | +from weauth.tencent_server.wx_server import WxConnection |
| 11 | +from weauth.listener import WechatTestListener as Listener |
| 12 | +from gevent import pywsgi |
| 13 | +from gevent import ssl |
| 14 | + |
| 15 | + |
| 16 | +def wtest() -> None: |
| 17 | + print('-正在测试微信服务器连接') |
| 18 | + try: |
| 19 | + with open('config.yaml', 'r', encoding='utf-8') as f: |
| 20 | + result = yaml.load(f.read(), Loader=yaml.FullLoader) |
| 21 | + print('-已读取配置文件') |
| 22 | + except FileNotFoundError: |
| 23 | + print('-未找到配置文件config.yaml!') |
| 24 | + sys.exit(0) |
| 25 | + |
| 26 | + config = result |
| 27 | + url = config['url'] |
| 28 | + # 测试微信服务器连接 |
| 29 | + print('-正在检验AppID与AppSecret是否正确') |
| 30 | + if test_wechat_server(app_id=config['appID'], app_secret=config['AppSecret']) == -1: |
| 31 | + sys.exit(0) |
| 32 | + |
| 33 | + print("-正在启动监听......\n") |
| 34 | + listener = Listener(wx_user_name=config['WxUserName'], url=config['url']) |
| 35 | + |
| 36 | + if config['ssl'] == 1: |
| 37 | + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 38 | + try: |
| 39 | + ssl_context.load_cert_chain(certfile=config['ssl_cer'], keyfile=config['ssl_key']) |
| 40 | + except FileNotFoundError: |
| 41 | + print('-未找到ssl证书文件!') |
| 42 | + sys.exit(0) |
| 43 | + server = pywsgi.WSGIServer(('0.0.0.0', 443), listener.wx_service, |
| 44 | + ssl_context=ssl_context) |
| 45 | + print(f"-开始在 https://0.0.0.0{url} 进行监听") |
| 46 | + print('-您可以向公众号发送消息进行测试') |
| 47 | + server.serve_forever() |
| 48 | + else: |
| 49 | + # 核心监听程序运行 |
| 50 | + server = pywsgi.WSGIServer(('0.0.0.0', 80), listener.wx_service) |
| 51 | + print(f"-开始在 http://0.0.0.0{url} 进行监听") |
| 52 | + print('-您可以向公众号发送消息进行测试') |
| 53 | + server.serve_forever() |
| 54 | + |
| 55 | + |
| 56 | +def test_wechat_server(app_id, app_secret): |
| 57 | + code1, code2 = WxConnection.get_access_token(app_id, app_secret) |
| 58 | + if code1 == -2: |
| 59 | + print("-连接微信服务器网络错误,无法连接!") |
| 60 | + # sys.exit(2) |
| 61 | + return -1 |
| 62 | + elif code1 == -1: |
| 63 | + print("-连接微信服务器时请求错误,错误码: " + str(code2)) |
| 64 | + # sys.exit(3) |
| 65 | + return -1 |
| 66 | + |
| 67 | + elif code1 == 0: |
| 68 | + print("-检验通过") |
| 69 | + return code2 |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + wtest() |
0 commit comments