""" 企业微信通讯录同步到JNPF平台 用法: python3 aibridge/sync_wework.py """ import requests from typing import List, Dict, Optional from aibridge import JNPFClient, JNPFConfig class WeWorkAPI: """企业微信通讯录API""" def __init__(self, corp_id: str, corp_secret: str): self.corp_id = corp_id self.corp_secret = corp_secret self.base_url = "https://qyapi.weixin.qq.com" self._access_token: Optional[str] = None def _get_access_token(self) -> str: """获取access_token""" url = f"{self.base_url}/cgi-bin/gettoken" params = {"corpid": self.corp_id, "corpsecret": self.corp_secret} resp = requests.get(url, params=params, timeout=30) data = resp.json() if data.get("errcode") != 0: raise Exception(f"获取access_token失败: {data}") self._access_token = data["access_token"] return self._access_token def get_department_list(self) -> List[Dict]: """获取部门列表""" token = self._get_access_token() url = f"{self.base_url}/cgi-bin/department/list" params = {"access_token": token} resp = requests.get(url, params=params, timeout=30) data = resp.json() if data.get("errcode") != 0: raise Exception(f"获取部门列表失败: {data}") return data.get("department", []) def get_user_list_by_department(self, department_id: int, fetch_child: bool = True) -> List[Dict]: """获取部门成员详情""" token = self._get_access_token() url = f"{self.base_url}/cgi-bin/user/list" params = { "access_token": token, "department_id": department_id, "fetch_child": 1 if fetch_child else 0 } resp = requests.get(url, params=params, timeout=30) data = resp.json() if data.get("errcode") != 0: raise Exception(f"获取成员列表失败: {data}") return data.get("userlist", []) def sync_wework_to_jnpf(): """同步企业微信通讯录到JNPF""" # 企业微信配置 CORP_ID = "wwac71328171b889cb" CORP_SECRET = "XrhGV2ZF8mzjOzkTjvh2ep3tdf_GLK19SxnxNRzWB3E" # JNPF配置 config = JNPFConfig(app_code="jyzs") # 你的app_code client = JNPFClient.from_config(config) client.auth.login(config.account, config.backend_aes96_password) # 1. 获取企业微信数据 print("正在连接企业微信...") wework = WeWorkAPI(CORP_ID, CORP_SECRET) print("获取部门列表...") departments = wework.get_department_list() print(f" 共 {len(departments)} 个部门") print("获取成员列表...") all_users = [] for dept in departments: users = wework.get_user_list_by_department(dept["id"]) all_users.extend(users) print(f" 部门 {dept['name']} ({dept['id']}): {len(users)} 人") print(f" 共 {len(all_users)} 个成员") # 2. 写入JNPF print("\n正在写入JNPF...") # TODO: 调用JNPF API 创建部门和用户 # 部门接口: POST /api/visual/Department # 用户接口: POST /api/visual/User for dept in departments: print(f" 部门: {dept['name']} (id={dept['id']}, parentid={dept['parentid']})") for user in all_users: print(f" 用户: {user.get('name')} | {user.get('mobile')} | {user.get('email')} | dept={user.get('department')}") print("\n同步完成!") if __name__ == "__main__": sync_wework_to_jnpf()