调用钉钉的WebAPI接口实现与ERP数据的同步

一、调用钉钉的api接口实现与ERP中数据的对接,其中用到的主要技术有EFlinq序列化webAPI文件的基本操作。

哪里不懂的直接看代码,或者给我评论留言。

using Modell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using libraries;
using System.IO;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            AdwinErpEntities db = new AdwinErpEntities();
            
           
            int next_cursor = 0;
            int count = 0;


            ArrayList list = new ArrayList();
            ArrayList list1 = new ArrayList();
           
            //查询出所有的id的值
            var t_pALM_Employeeslist1 = from a in db.t_PALM_Employees
                                        select a.fEmpNo;
            t_pALM_Employeeslist1.ToArray();
            while (true)
            {
                //获取员工ID
                string result = queryonjob(next_cursor);
                //Console.Write(result);
                JavaScriptSerializer js = new JavaScriptSerializer();
                GetUserId getUserId = js.Deserialize<GetUserId>(result);
                list.AddRange(getUserId.result.data_list);
                next_cursor = getUserId.result.next_cursor;
                if (next_cursor == 0)
                {
                    break;
                }
                else
                {
                    continue;
                }
            }
            //一条一条遍历
            foreach (object li in list)
            {
                string resut = Employeelist(Convert.ToString(li));
                JavaScriptSerializer js1 = new JavaScriptSerializer();
                EmployeeList employeelist = js1.Deserialize<EmployeeList>(resut);
                try
                {
                    if ((employeelist.result[0].field_list[2].label.ToString()).StartsWith("ADW"))
                    {

                        //string[] s = employeelist.result[0].field_list[2].label.ToString().Split(' ');
                        //Console.WriteLine(s[1]);

                        list1.Add(employeelist.result[0].field_list[2].label.ToString());

                        string gonghao = employeelist.result[0].field_list[2].label.ToString();
                        var t_pALM_Employeeslist = from t in db.t_PALM_Employees
                                                   where t.fEmpNo == gonghao
                                                   select t;
                        t_PALM_Employees b = t_pALM_Employeeslist.FirstOrDefault();
                        if (b == null)
                        {
                            t_PALM_Employees c = new t_PALM_Employees();
                            c.fEmpNo = employeelist.result[0].field_list[2].label.ToString();    //工号
                            c.fEmpName = employeelist.result[0].field_list[0].label.ToString();   //姓名
                            c.fPhone = employeelist.result[0].field_list[1].label.ToString();    //手机号
                            c.fSex = "1";
                            c.fDeptID = 323;
                            c.fID = "111111111111111111";
                            c.fIfMarried = "0";
                            c.fLogInDate = Convert.ToDateTime(DateTime.Now.ToString());
                            c.fProbation = 30;
                            c.fIfNeedCont = "0";
                            c.fWorkMode = "2";
                            c.fIfCardFree = "0";
                            c.fIfFullAttBonus = "0";
                            c.fIfRecordHR = "1";
                            c.fIfRecordOTCost = "1";
                            c.fCFlag = "2";
                            c.fIfResign = "0";
                            c.fIfUse = "1";
                            c.fAssignRate = 1;
                            c.fIfPFM = "0";
                            c.fIfSupper = "0";
                            c.fAttendanceType = "1";
                            c.fLinkNo = "";
                            //db.t_PALM_Employees.Add(c);
                            //db.SaveChanges();
                           // Console.WriteLine("插入成功");
                            //count += 1;
                        }
                        else
                        {
                            string [] str = employeelist.result[0].field_list[1].label.ToString().Split('-');
                            b.fPhone = str[1];
                            b.fCFlag = "1";
                            //db.Entry<t_PALM_Employees>(b).State = System.Data.EntityState.Modified;
                            //db.SaveChanges();
                            //Console.WriteLine("更新成功");
                            //count += 1;
                        }
                    }
                    else
                    {
                        //Console.WriteLine();
                        continue;
                    }
                    
                }
                catch
                {
                    continue;
                }
            }

            foreach (object i in t_pALM_Employeeslist1)
            {
                if (list1.Contains(i))
                {
                    continue;
                }
                else
                {
                    string o = i.ToString();
                    var t_pALM_Employeeslist = from t in db.t_PALM_Employees
                                               where t.fEmpNo == o
                                               select t;
                    //t_pALM_Employeeslist = "2";
                    t_PALM_Employees d = t_pALM_Employeeslist.FirstOrDefault();
                    d.fIfUse="0";
                    d.fCFlag = "2";
                    db.Entry<t_PALM_Employees>(d).State = System.Data.EntityState.Modified;
                    
                    Console.WriteLine(i);
                    count += 1;
                }
            }
            db.SaveChanges();
            Console.WriteLine(count);
            Console.Read();
          


        }
        /// <summary>
        /// 获取单个员工的信息
        /// </summary>
        /// <returns></returns>
        public static string GetUser(string userid)
        {

            string access_token = fileStr();
            
            string personUrl = "https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}";
            //string userid = "274805565923472895";
            personUrl = string.Format(personUrl, access_token, userid);
            var result1 = GetAccessToken(personUrl);
            return result1;
        }
        /// <summary>
        /// 获取token
        /// </summary>
        public static string GainToken()
        {
            //Directory.CreateDirectory(@"D:\Token");
            string requestUrl = "https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}";

            string appkey = "dingke8bw3rjb";
            string appsecret = "gd1MGMSDwwkKE7qOky0fpFdS-9u9WY3dg3O2_pB6v1fdxlDiMNtbagi91N_gtCs5";

            requestUrl = string.Format(requestUrl, appkey, appsecret);
            var result = GetAccessToken(requestUrl);
            JavaScriptSerializer js = new JavaScriptSerializer();
            Token token = js.Deserialize<Token>(result);
            string access_token = token.access_token;
            return access_token;
        }
        /// <summary>
        /// 查询员工的userid
        /// </summary>
        public static string queryonjob(int offset)
        {
            string token = fileStr();
            string requestUrl = "https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob?access_token={0}";
            requestUrl = string.Format(requestUrl, token);
            string postData = "status_list=3&offset={0}&size=20";
            postData = string.Format(postData, offset);
            string result = PostAccessToken(requestUrl, postData);
            return result;
        }
        /// <summary>
        /// 获取源文件
        /// </summary>
        /// <param name="_Url">链接地址</param>
        /// <param name="_Charset">编码</param>
        /// <returns></returns>
        public static string GetAccessToken(string _Url, string _Charset = "UTF-8")
        {
            string strRet = string.Empty;
            // 网页客户端,用于打开链接,获取返回参数
            WebClient wc = new WebClient();
            try
            {
                byte[] responseData = null;
                wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                responseData = wc.DownloadData(_Url);
                strRet = Encoding.GetEncoding(_Charset).GetString(responseData);
                strRet = strRet.Trim();
            }
            catch (Exception ex)
            {
                strRet = "错误:" + ex.Message;
            }
            finally
            {
                wc.Dispose();
                wc = null;
            }
            return strRet;
        }
        /// <summary>
        ////// </summary>
        /// <param name="_Url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostAccessToken(string _Url, string postData)
        {
            // 网页客户端,用于打开链接,获取返回参数
            WebClient wc = new WebClient();
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            client.Headers.Add("ContentLength", postData.Length.ToString());
            Encoding enc = Encoding.GetEncoding("UTF-8");
            byte[] responseData = client.UploadData(_Url, "POST", bytes);
            string re = enc.GetString(responseData);
            return re;
        }
        /// <summary>
        /// 判断token的值是否过期
        /// </summary>
        /// <returns></returns>
        public static string fileStr() 
        {
            if (File.Exists(@"d:\Token.txt"))
            {
                string token = File.ReadAllText(@"d:\Token.txt");
                string [] date = token.Split(',');
                if(DateTime.Compare(Convert.ToDateTime(DateTime.Now.ToString()),Convert.ToDateTime(date[1]))<0)
                {
                    return date[0];
                }
                else
                {
                    string inputToken = "";
                    string token1 = GainToken();
                    inputToken = token1 + "," + DateTime.Now.AddMinutes(118).ToString();
                    FileStream stream = new FileStream(@"d:\Token.txt", FileMode.Create);//fileMode指定是读取还是写入
                    StreamWriter writer = new StreamWriter(stream);//创建一个写入流
                    writer.WriteLine(inputToken);//写入一行,写完后会自动换行
                    writer.Close();//释放内存
                    stream.Close();//释放内存
                    string Token1 = File.ReadAllText(@"d:\Token.txt");
                    string[] token2 = Token1.Split(',');
                    return token2[0];
                }
            }
            else
            {
                string inputToken = "";
                string token= GainToken();
                inputToken = token + "," + DateTime.Now.AddMinutes(118).ToString();
                FileStream stream = new FileStream(@"d:\Token.txt", FileMode.Create);//fileMode指定是读取还是写入
                StreamWriter writer = new StreamWriter(stream);//创建一个写入流
                writer.WriteLine(inputToken);//写入一行,写完后会自动换行
                writer.Close();//释放内存
                stream.Close();//释放内存
                string Token = File.ReadAllText(@"d:\Token.txt");
                string[] token1 = Token.Split(',');
                return token1[0];
            }
        }
        /// <summary>
        /// 获取员工的详细信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string Employeelist(string userid)
        {
            string token = fileStr();
            string requestUrl = "https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list?access_token={0}";
            requestUrl = string.Format(requestUrl, token);
            string postData = "userid_list={0}&field_filter_list={1}";
                                                    //手机号    部门                            姓名         身份证号码      出生日期
            postData = string.Format(postData, userid, "sys00-mobile,sys00-jobNumber,sys00-name,sys02-certNo");
            string result = PostAccessToken(requestUrl, postData);
            return result;
        }
    }
}

 

posted @ 2019-05-23 23:18  锦大大的博客呀!  阅读(3048)  评论(3编辑  收藏  举报