This commit is contained in:
aaron 2025-03-03 00:26:04 +08:00
parent 8c432a606b
commit 8472d79279
2 changed files with 32 additions and 5 deletions

View File

@ -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:

View File

@ -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)}")