通过API接口管理企业微信通讯录案例

1.开始前需要登录企业微信管理员后台,开启通讯录同步,同时添加企业可信IP地址,记录下Secret信息和企业ID,后面的程序会用到这两个参数。

2.下面是用python写的创建企业微信账号的具体案例。

复制代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业微信通讯录 API:创建成员(单个账号)示例
官方文档:https://developer.work.weixin.qq.com/document/path/90195
"""
import os
import sys
import json
import time
import requests
from typing import Dict, Any
# ========= 1. 配置区 =========
# ⚠️ 请替换成自己企业的真实信息
CORP_ID = "wwassssssssssssssss"               # 企业ID
CONTACT_SYNC_SECRET = "Y4ffffffff_UDf_fffffffffffzWY4"  # "通讯录同步"专用 Secret
# 要创建的成员信息(字段含义见官方文档)
NEW_USER = {
    "userid": "I00555",          # 账号:必须唯一,建议用小写英文/数字 
    "name": "张三",
    "alias": "San Zhang",          # 可选
    "mobile": "+86 13800001234",   # mobile 与 email 二者必填其一
    "department": [1],             # 所在部门ID,根部门为1
    "position": "产品经理",
    "gender": "1",                 # 1男 2女 0未知
    "email": "zhangsan@example.com"
}
# ========= 2. 工具函数 =========
def get_access_token(corp_id: str, secret: str) -> str:
    """获取 access_token(有效期 7200s,建议本地缓存)"""
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    params = {"corpid": corp_id, "corpsecret": secret}
    resp = requests.get(url, params=params, timeout=10)
    data = resp.json()
    if data.get("errcode") != 0:
        raise RuntimeError(f"获取token失败 → {data}")
    return data["access_token"]
def create_user(token: str, user: Dict[str, Any]) -> Dict[str, Any]:
    """创建成员"""
    url = f"https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token={token}"
    resp = requests.post(url, json=user, timeout=10)
    return resp.json()
# ========= 3. 主流程 =========
def main():
    try:
        print("[Step 1] 获取 access_token ...")
        token = get_access_token(CORP_ID, CONTACT_SYNC_SECRET)
        print("✅ token 获取成功,前10位:", token[:10])
        print("[Step 2] 创建成员 ...")
        ret = create_user(token, NEW_USER)
        if ret.get("errcode") == 0:
            print("✅ 创建成功,userid =", NEW_USER["userid"])
        else:
            print("❌ 创建失败,返回:", ret)
            # 常见错误码快速提示
            if ret.get("errcode") == 60121:
                print("提示:部门ID不存在,请检查 department 字段")
            elif ret.get("errcode") == 60102:
                print("提示:手机号已被其他成员占用")
            elif ret.get("errcode") == 48009:
                print("提示:无权限,请确认使用了「通讯录同步」专用 Secret,且 IP 已在白名单")
            sys.exit(1)
    except Exception as e:
        print("发生异常:", e)
        sys.exit(1)
# ========= 4. 运行 =========
if __name__ == "__main__":
    main()

3.下面是用python写的删除企业微信账号的具体案例。

python 复制代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业微信 API 删除成员(单个账号)
官方文档:https://developer.work.weixin.qq.com/document/path/90198
"""
import os
import sys
import json
import requests
from typing import Dict
# ========== 1. 配置区(请替换成你的真实信息) ==========
CORP_ID = "wwffffffffffffff03"                       # 企业 ID
CONTACT_SYNC_SECRET = "Y4dddddddddddddddddddddsssssY4"   # "通讯录同步"专用 Secret
USER_ID_TO_DELETE = "I00555"                       # 要删除的成员 userid
# ========== 2. 工具函数 ==========
def get_access_token(corp_id: str, secret: str) -> str:
    """获取 access_token(有效期 7200 s,建议本地缓存)"""
    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
    params = {"corpid": corp_id, "corpsecret": secret}
    resp = requests.get(url, params=params, timeout=10)
    data = resp.json()
    if data.get("errcode") != 0:
        raise RuntimeError(f"获取 token 失败 → {data}")
    return data["access_token"]
def delete_user(token: str, userid: str) -> Dict:
    """删除单个成员"""
    url = f"https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token={token}&userid={userid}"
    resp = requests.get(url, timeout=10)
    return resp.json()
# ========== 3. 主流程 ==========
def main():
    try:
        print("[Step 1] 获取 access_token ...")
        token = get_access_token(CORP_ID, CONTACT_SYNC_SECRET)
        print("✅ token 获取成功,前 10 位:", token[:10])
        print(f"[Step 2] 删除成员(userid={USER_ID_TO_DELETE})...")
        ret = delete_user(token, USER_ID_TO_DELETE)
        if ret.get("errcode") == 0:
            print("✅ 删除成功")
        else:
            print("❌ 删除失败,返回:", ret)
            # 常见错误码提示
            if ret.get("errcode") == 60111:      # 官方错误码
                print("提示:成员 userid 不存在")
            elif ret.get("errcode") == 48009:
                print("提示:无权限,请确认:\n"
                      "  1) 使用了『通讯录同步』专用 Secret\n"
                      "  2) 当前出口 IP 已加入企业微信后台白名单")
            sys.exit(1)
    except Exception as e:
        print("发生异常:", e)
        sys.exit(1)
# ========== 4. 运行 ==========
if __name__ == "__main__":
    main()
相关推荐
云服务器租用费用21 小时前
保姆级教程:2026年OpenClaw(原Clawdbot)零门槛部署+企业微信接入步骤
企业微信
2501_941982051 天前
别再手动发群消息了!企业微信外部群自动化推送的架构设计与实现
运维·自动化·企业微信
vx-bot5556661 天前
企业微信接口在可观测性平台中的深度集成实践
企业微信
vx-bot5556663 天前
企业微信接口在数据工程与分析场景中的架构应用
架构·企业微信
2501_941982053 天前
AI + 企微:使用 Python 接入 DeepSeek/GPT 实现外部群自动技术答疑
人工智能·python·企业微信
梦想的旅途23 天前
Java/Python/Go 实现企微外部群自动化消息推送
运维·自动化·企业微信
天空属于哈夫克33 天前
Go 语言实战:构建一个企微外部群“技术贴收藏夹”小程序后端
小程序·golang·企业微信
梦想的旅途23 天前
如何优雅地实现企微外部群消息自动化(Java/Python/Go 多语言版)
java·自动化·企业微信
2501_941982054 天前
突破官限:企微外部群“主动推送”引擎的精准定位与消息链实现
企业微信
2501_941982054 天前
企微自动化开发:安全与效率的平衡术
数据库·mysql·企业微信