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()