From 8472d79279ebb33ba9a848cb8c5e477d3dac1f54 Mon Sep 17 00:00:00 2001 From: aaron <> Date: Mon, 3 Mar 2025 00:26:04 +0800 Subject: [PATCH] updaet --- app/api/endpoints/wecom.py | 10 +++++++--- app/core/wecomclient.py | 27 +++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/app/api/endpoints/wecom.py b/app/api/endpoints/wecom.py index a6bf4cb..4783872 100644 --- a/app/api/endpoints/wecom.py +++ b/app/api/endpoints/wecom.py @@ -123,9 +123,13 @@ async def wechat_corp_callback( chat_id = msg_root.find('ChatId').text change_type = msg_root.find('ChangeType').text - # if change_type == 'add_member': - # # 获取群聊成员 - + # 处理进群事件 + if change_type == 'add_member': + userid = msg_root.find('UserId').text + unionid = await wecom_client.get_unionid_from_userid(userid) + print(f"根据userid获取unionid结果: {unionid}") + + return Response(content="success", media_type="text/plain") except Exception as e: diff --git a/app/core/wecomclient.py b/app/core/wecomclient.py index 932cdc4..104e89a 100644 --- a/app/core/wecomclient.py +++ b/app/core/wecomclient.py @@ -70,20 +70,43 @@ class WecomClient: except Exception as e: logging.error(f"code2session异常: {str(e)}") return None + + async def get_unionid_from_userid(self, userid: str) -> Optional[str]: + """根据userid获取unionid""" + try: + access_token = await self.get_access_token() + if not access_token: + raise Exception("获取access_token失败") + + url = f"https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get" + params = { + "access_token": access_token, + "external_userid": userid + } + + async with aiohttp.ClientSession() as session: + async with session.get(url, params=params) as response: + result = await response.json() + + return result.get("unionid") + except Exception as e: + logging.error(f"get_unionid_from_userid异常: {str(e)}") + return None async def unionid_to_external_userid(self, unionid: str, openid: str) -> Optional[str]: """根据unionid获取external_userid""" try: - url = f"https://qyapi.weixin.qq.com/cgi-bin/corpgroup/unionid_to_external_userid?access_token={await self.get_access_token()}" + url = f"https://qyapi.weixin.qq.com/cgi-bin/idconvert/unionid_to_external_userid?access_token={await self.get_access_token()}" params = { "unionid": unionid, "openid": openid, - "corpid": self.corp_id + "subject_type": 1 } async with aiohttp.ClientSession() as session: async with session.post(url, json=params) as response: result = await response.json() + return result except Exception as e: logging.error(f"unionid_to_external_userid异常: {str(e)}")