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寫的刪除企業微信賬號的具體案例。
#!/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()