zoukankan      html  css  js  c++  java
  • .NET 钉钉接口同步钉钉框架,通讯录

    定义变量

            string DingAppkey = "dingdul5161354SDF5131";//钉钉  应用的唯一标识key
            string DingAppsecret = "zU6w54Wg21DieRC3SSDF15SDFDSF15SDF1DS415S4DF8A791SD4";//钉钉  应用的密钥
            public static string dingAccessToken = ""; //钉钉接口调用凭证

    获取钉钉接口调用凭证access_token

            #region 获取钉钉接口调用凭证:access_token
            /// <summary>
            /// 获取钉钉接口调用凭证:access_token
            /// </summary>
            /// <returns></returns>
            public string GetDingAccessToken()
            {
                string access_token = string.Empty;
                try
                {
                    string accessToken = string.Empty;
                    DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                    OapiGettokenRequest request = new OapiGettokenRequest();
                    request.Appkey = DingAppkey;//钉钉  应用的唯一标识key
                    request.Appsecret = DingAppsecret;//钉钉  应用的密钥
                    request.SetHttpMethod("GET");
                    OapiGettokenResponse response = client.Execute(request);
                    access_token = response.AccessToken;
                }
                catch (Exception ex)
                {
    
    
                }
                return access_token;
            }
            #endregion

    获取简单钉钉部门列表

            #region 获取简单钉钉部门列表
            /// <summary>
            /// 获取简单钉钉部门列表
            /// </summary>
            /// <returns></returns>
            public List<DepartmentDomain> GetDingAlldepartmentList()
            {
                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
                OapiDepartmentListRequest request = new OapiDepartmentListRequest();
                request.Id = "1";
                request.SetHttpMethod("GET");
                OapiDepartmentListResponse response = client.Execute(request, dingAccessToken);
                return response.Department;
            }
            #endregion

    获取钉钉全部通讯录人员

    #region 定时器---获取钉钉全部通讯录人员
    
            void ToPandian(object sender, System.Timers.ElapsedEventArgs e)
            {
                //if (true)//每月一号执行 false true
                if (DateTime.Now.Day == 1)//每月一号执行
                {
                    dingAccessToken = GetDingAccessToken();//获取钉钉接口调用凭证
                    List<OapiUserListbypageResponse.UserlistDomain> dingUserList = new List<OapiUserListbypageResponse.UserlistDomain>(); //所有用户
                    List<DepartmentDomain> dingDptList = GetDingAlldepartmentList();//获取所有部门 
                                                                                    //ResultInfo resultInfo = new ResultInfo() { State = false };
                    try
                    {
                        string cacheKey = "F7C16F00-6A13-4063-8019-CEA4E51A5AF2";
                        var dingdingUserCache = Common.GetCache(cacheKey);//读取用户缓存
                        if (dingdingUserCache == null)//没有缓存记录
                        {
                            //遍历部门获取所有通讯录人员
                            foreach (var item in dingDptList)
                            {
                                List<OapiUserListbypageResponse.UserlistDomain> tempUserList = new List<OapiUserListbypageResponse.UserlistDomain>();
                                IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/listbypage");
                                OapiUserListbypageRequest req = new OapiUserListbypageRequest();
                                req.DepartmentId = item.Id;
                                req.Offset = 0;
                                req.Size = 100;
                                req.SetHttpMethod("GET");
                                OapiUserListbypageResponse rsp = client.Execute(req, dingAccessToken);
                                tempUserList = rsp.Userlist;
                                if (rsp.Errcode != 0)//请求不成功
                                {
                                    throw new Exception("网速有点慢E");
                                }
                                if (tempUserList != null)
                                {
                                    dingUserList.AddRange(tempUserList);
                                }
    
                                Thread.Sleep(5);
                            }
                            if (dingUserList.Count > 0)
                            {
                                Common.SetCache(cacheKey, dingUserList, DateTime.Now.AddMinutes(300), TimeSpan.Zero);//存储钉钉用户到缓存(每5小时更新一次)
                            }
                            else
                            {
                                HttpRuntime.Cache.Remove(cacheKey);//清除缓存
                                throw new Exception("网速有点慢N001");
                            }
                        }
                        else
                        {
                            dingUserList = (List<OapiUserListbypageResponse.UserlistDomain>)dingdingUserCache;
                            if (dingUserList.Count == 0)
                            {
                                throw new Exception("网速有点慢N002");
                            }
                        }
                        //resultInfo.State = true;//Jobnumber钉钉里的工号
                        string Data = "[" + JsonHelper.ObjectToJSON(dingDptList) + "," + JsonHelper.ObjectToJSON(dingUserList) + "]";
                        //List<OapiUserListbypageResponse.UserlistDomain> listuser30 = null;
    
                        /*钉钉上的部门
                        [XmlElement("autoAddUser")]
                        [XmlElement("createDeptGroup")]
                        [XmlElement("id")]//部门id
                        [XmlElement("name")]//部门名称
                        [XmlElement("parentid")]//父部门id,根部门为1
                        [XmlElement("sourceIdentifier")]//部门标识字段,开发者可用该字段来唯一标识一个部门,并与钉钉外部通讯录里的部门做映射
                         */
    
                        /*钉钉上的员工信息
                         * https://ding-doc.dingtalk.com/doc#/serverapi2/ege851/AaRQe
                        [XmlElement("unionid")]//szyC6A4aYGDbD2KiS5Y9f6QiEIE//员工在当前开发者企业账号范围内的唯一标识,系统生成,固定值,不会改变
                        [XmlElement("tel")]
                        [XmlElement("remark")]
                        [XmlElement("position")]//经营管理部副主任//职位信息
                        [XmlElement("orgEmail")]
                        [XmlElement("order")]//17634072162316213525//表示人员在此部门中的排序
                        [XmlElement("name")]//赵倩华//成员名称
                        [XmlElement("mobile")]//13781503303//手机号
                        [XmlElement("jobnumber")]//011//工号
                        [XmlElement("userid")]//6717155435458170//员工在当前企业内的唯一标识
                        [XmlElement("isHide")]//false
                        [XmlElement("isLeader")]//false//是否是部门的主管
                        [XmlElement("isBoss")]//true//是否为企业的老板
                        [XmlElement("isAdmin")]//true//是否是企业的管理员
                        [XmlElement("hiredDate")]
                        [XmlElement("extattr")]
                        [XmlElement("email")]
                        [XmlElement("dingId")]
                        [XmlElement("department")]//150926607//成员所属部门id列表
                        [XmlElement("avatar")]//http://********.com/***.jpg//头像url
                        [XmlElement("active")]//true//表示该用户是否激活了钉钉
                        [XmlElement("workPlace")]
    
                         */
    
                        StringBuilder sbDeptUpdate = new StringBuilder();
                        sbDeptUpdate.Append(string.Format(" update MyUser_Department set isDel=0  ; "));//先全部更改为已删除状态
                        for (int i = 0; i < dingDptList.Count; i++)
                        {
                            MyUser_DepartmentModel model = MyUser_DepartmentBLL.SelectModel(" and departmentID='" + dingDptList[i].Id + "' ");
                            if (model == null)
                            {
                                sbDeptUpdate.Append(string.Format(" insert into MyUser_Department (departmentID,departmentName,parentid) values ('{0}','{1}','{2}') ; ", dingDptList[i].Id.ToString(), dingDptList[i].Name, dingDptList[i].Parentid.ToString()));
                            }
                            else
                            {
                                //如果数据库有就更新
                                sbDeptUpdate.Append(string.Format(" update MyUser_Department set departmentName='{0}',parentid='{1}' where departmentID='{2}' ; ", dingDptList[i].Name, dingDptList[i].Parentid.ToString(), dingDptList[i].Id.ToString()));
                            }
                        }
    
    
                        StringBuilder sbUserUpdate = new StringBuilder();
                        sbDeptUpdate.Append(string.Format(" update MyUser_Yuyue set isDel=0  ; "));//先全部更改为已删除状态
                        for (int i = 0; i < dingUserList.Count; i++)
                        {
                            sbUserUpdate.Append(string.Format(" update MyUser_Yuyue set dingdingUserid='{0}' where userName='{1}' ; ", dingUserList[i].Userid, dingUserList[i].Name));//初始化时候先用姓名同步一下钉钉ID,以后不执行
                            if (!string.IsNullOrEmpty(dingUserList[i].Jobnumber))//如果有工号才同步
                            {
                                MyUserModel model = MyUserBLL.SelectModel(" and userID='" + dingUserList[i].Jobnumber + "' ");
                                if (model == null)
                                {
                                    sbDeptUpdate.Append(string.Format(" insert into MyUser_Yuyue (userID,userName,mobile,department,avatar,dingdingUserid,isDel,unionid) values ('{0}','{1}','{2}','{3}','{4}','{5}',1,'{6}') ; ", dingUserList[i].Jobnumber, dingUserList[i].Name, dingUserList[i].Mobile, dingUserList[i].Department, dingUserList[i].Avatar, dingUserList[i].Userid, dingUserList[i].Unionid));
    
                                }
                                else
                                {
                                    //Common.CreateWebLog("更新语句", string.Format(" update MyUser_Yuyue set userName='{0}',mobile='{1}',department='{2}',avatar='{3}',isDel=1,unionid='{5}',dingdingUserid='{6}' where userID='{4}' ; ", dingUserList[i].Name, dingUserList[i].Mobile, dingUserList[i].Department.Replace("[", "").Replace("]", ""), dingUserList[i].Avatar, dingUserList[i].Jobnumber, dingUserList[i].Unionid, dingUserList[i].Userid));
                                    //如果数据库有就更新
                                    sbUserUpdate.Append(string.Format(" update MyUser_Yuyue set userName='{0}',mobile='{1}',department='{2}',avatar='{3}',isDel=1,unionid='{5}',dingdingUserid='{6}' where userID='{4}' ; ", dingUserList[i].Name, dingUserList[i].Mobile, dingUserList[i].Department.ToString().Replace("[", "").Replace("]", ""), dingUserList[i].Avatar, dingUserList[i].Jobnumber, dingUserList[i].Unionid, dingUserList[i].Userid));
                                }
                            }
    
                        }
                        SqlHelper.ExecuteNonQuery(sbDeptUpdate.ToString() + sbUserUpdate.ToString(), CommandType.Text);
    
                    }
                    catch (Exception ex)
                    {
                        Common.CreateWebLog("同步钉钉信息异常182", ex.ToString());
                    }
                }
    
            }
            #endregion
  • 相关阅读:
    GitLab-添加SSH Key亲历教程
    java-数组Array的应用总结
    Java-方法的重载和重写
    JSON-相关的工具收藏分享
    java-无重复的排列组合小技能
    Charles安装与使用
    深拷贝浅拷贝
    文件操作
    列表生成式
    非空即真,非零即真
  • 原文地址:https://www.cnblogs.com/wybshyy/p/13783607.html
Copyright © 2011-2022 走看看