59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
import xml.etree.cElementTree as ET
|
|
from typing import Optional
|
|
|
|
from app.wechat.crypto import WXBizMsgCrypt
|
|
from app.config import settings
|
|
|
|
|
|
class WeChatMessageHandler:
|
|
def __init__(self):
|
|
self.wxcpt = WXBizMsgCrypt(
|
|
sToken=settings.wechat_token,
|
|
sEncodingAESKey=settings.wechat_encoding_aes_key,
|
|
sReceiveId=settings.wechat_corp_id,
|
|
)
|
|
|
|
def verify_url(
|
|
self, msg_signature: str, timestamp: str, nonce: str, echostr: str
|
|
) -> Optional[str]:
|
|
ret, sEchoStr = self.wxcpt.VerifyURL(
|
|
msg_signature, timestamp, nonce, echostr
|
|
)
|
|
if ret == 0:
|
|
return (
|
|
sEchoStr.decode("utf-8")
|
|
if isinstance(sEchoStr, bytes)
|
|
else sEchoStr
|
|
)
|
|
return None
|
|
|
|
def decrypt_message(
|
|
self,
|
|
post_data: str,
|
|
msg_signature: str,
|
|
timestamp: str,
|
|
nonce: str,
|
|
) -> Optional[ET.Element]:
|
|
ret, xml_content = self.wxcpt.DecryptMsg(
|
|
post_data, msg_signature, timestamp, nonce
|
|
)
|
|
if ret != 0:
|
|
return None
|
|
return ET.fromstring(xml_content)
|
|
|
|
def encrypt_response(
|
|
self, response_xml: str, nonce: str, timestamp: str
|
|
) -> Optional[str]:
|
|
ret, encrypted = self.wxcpt.EncryptMsg(response_xml, nonce, timestamp)
|
|
if ret == 0:
|
|
return encrypted
|
|
return None
|
|
|
|
def handle_event(
|
|
self, event: str, event_key: Optional[str], from_user: str
|
|
) -> Optional[str]:
|
|
return None
|
|
|
|
def handle_text(self, content: str, from_user: str) -> Optional[str]:
|
|
return None
|