- sync_wework: 企业微信通讯录同步模块 - wework_server: 企业微信回调服务(Flask) - appconfig/config_wiki: wiki应用配置 - exceptions: 增强异常处理 Co-Authored-By: Claude Opus 4.7 <[email protected]>
145 lines
4.5 KiB
Python
145 lines
4.5 KiB
Python
"""
|
|
企业微信回调服务
|
|
提供 /api/ssw/wework/sync 接收企业微信事件推送
|
|
|
|
启动:
|
|
cd $ccWorkDir && python3 -m aibridge.wework_server
|
|
|
|
企业微信回调配置:
|
|
URL: https://oadfec13000ad18dm.mayishangshu.cn:82/api/ssw/wework/sync
|
|
Token: Bwu5YSzfNCHUu
|
|
EncodingAESKey: bk5ypj4lFDMp1lgTVdxT6QozJ5rFyU6SCRiz88SbTaX
|
|
"""
|
|
|
|
import base64
|
|
import hashlib
|
|
import random
|
|
import string
|
|
import struct
|
|
import time
|
|
from flask import Flask, request, jsonify
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
# 企业微信回调配置
|
|
WECHAT_TOKEN = "Bwu5YSzfNCHUu"
|
|
WECHAT_ENCODING_AES_KEY = "bk5ypj4lFDMp1lgTVdxT6QozJ5rFyU6SCRiz88SbTaX"
|
|
WECHAT_CORP_ID = "wwac71328171b889cb"
|
|
WECHAT_CORP_SECRET = "XrhGV2ZF8mzjOzkTjvh2ep3tdf_GLK19SxnxNRzWB3E"
|
|
|
|
|
|
def calculate_signature(token: str, timestamp: str, nonce: str, encrypt_str: str) -> str:
|
|
"""计算企业微信签名"""
|
|
sort_str = ".".join(sorted([token, timestamp, nonce, encrypt_str]))
|
|
return hashlib.sha1(sort_str.encode()).hexdigest()
|
|
|
|
|
|
def decrypt_aes(encrypted: str, aes_key: str) -> str:
|
|
"""AES解密 AESKey是43位的b64编码,补位后变成32字节"""
|
|
import crypto
|
|
from Crypto.Cipher import AES
|
|
|
|
def calculate_AESKey(aes_key: str) -> bytes:
|
|
module = __import__('crypto')
|
|
from crypto.Cipher import AES
|
|
return base64.b64decode(aes_key + "=")
|
|
|
|
def PKCS7_decode(text: bytes) -> bytes:
|
|
"""PKCS7解码"""
|
|
pad_len = ord(bytes([text[-1]]))
|
|
if pad_len > 32 or pad_len < 1:
|
|
return text
|
|
return text[:-pad_len]
|
|
|
|
aes_key_bytes = calculate_AESKey(aes_key)
|
|
cipher = AES.new(aes_key_bytes, AES.MODE_CBC, aes_key_bytes[:16])
|
|
decrypted = cipher.decrypt(base64.b64decode(encrypted))
|
|
result = PKCS7_decode(decrypted)
|
|
# 去掉前16字节的随机串
|
|
msg_len = struct.unpack(">I", result[16:20])[0]
|
|
msg_content = result[20:20+msg_len]
|
|
return msg_content.decode("utf-8")
|
|
|
|
|
|
def encrypt_aes(text: str, aes_key: str) -> str:
|
|
"""AES加密"""
|
|
import crypto
|
|
from crypto.Cipher import AES
|
|
|
|
def calculate_AESKey(aes_key: str) -> bytes:
|
|
return base64.b64decode(aes_key + "=")
|
|
|
|
def PKCS7_encode(text: bytes) -> bytes:
|
|
"""PKCS7编码"""
|
|
block_size = 32
|
|
pad_len = block_size - len(text) % block_size
|
|
return text + bytes([pad_len] * pad_len)
|
|
|
|
aes_key_bytes = calculate_AESKey(aes_key)
|
|
# 随机16字节 + 4字节长度 + 内容 + corpId
|
|
random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=16)).encode("utf-8")
|
|
msg_len = struct.pack(">I", len(text))
|
|
msg_content = text.encode("utf-8") + WECHAT_CORP_ID.encode("utf-8")
|
|
plaintext = random_str + msg_len + msg_content
|
|
plaintext = PKCS7_encode(plaintext)
|
|
cipher = AES.new(aes_key_bytes, AES.MODE_CBC, aes_key_bytes[:16])
|
|
encrypted = base64.b64encode(cipher.encrypt(plaintext))
|
|
return encrypted.decode("utf-8")
|
|
|
|
|
|
def verify_callback(query: dict, post_data: str) -> str:
|
|
"""验证企业微信回调URL"""
|
|
msg_signature = query.get("msg_signature", "")
|
|
timestamp = query.get("timestamp", "")
|
|
nonce = query.get("nonce", "")
|
|
echostr = query.get("echostr", "")
|
|
|
|
# 解密echostr
|
|
decrypted = decrypt_aes(echostr, WECHAT_ENCODING_AES_KEY)
|
|
|
|
# 计算签名验证
|
|
signature = calculate_signature(WECHAT_TOKEN, timestamp, nonce, decrypted)
|
|
if signature != msg_signature:
|
|
return ""
|
|
|
|
return decrypted
|
|
|
|
|
|
@app.route("/api/ssw/wework/sync", methods=["GET", "POST"])
|
|
def wework_sync():
|
|
"""企业微信回调接口"""
|
|
if request.method == "GET":
|
|
# URL验证
|
|
query = request.args
|
|
echo = query.get("echostr", "")
|
|
|
|
result = verify_callback(query, "")
|
|
if result:
|
|
return result
|
|
return ""
|
|
|
|
else:
|
|
# POST - 接收事件
|
|
try:
|
|
post_data = request.data.decode("utf-8")
|
|
print(f"[WeWork] 收到POST: {post_data[:200]}")
|
|
|
|
return jsonify({"errcode": 0, "errmsg": "ok"})
|
|
except Exception as e:
|
|
print(f"[WeWork] 处理异常: {e}")
|
|
return jsonify({"errcode": 0, "errmsg": "ok"})
|
|
|
|
|
|
@app.route("/health", methods=["GET"])
|
|
def health():
|
|
"""健康检查"""
|
|
return jsonify({"status": "ok"})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("启动企业微信回调服务...")
|
|
print(f"监听: 0.0.0.0:3000")
|
|
print(f"回调URL: https://oadfec13000ad18dm.mayishangshu.cn:82/api/ssw/wework/sync")
|
|
app.run(host="0.0.0.0", port=3000, debug=False) |