asp.net企业微信开发之同步通讯录

参考腾讯提供的企业微信api,得知企业微信在同步通讯录时需要先将部门和人员按照规定格式上传,然后再根据上传后返回的media_id执行部门或者人员的覆盖操作。
话不多说,直接上菜。

  • 同步程序
  public string SyncOrga()
        {
            string result = string.Empty;
            string token = getToken();

            //生成部门csv文件
            string ouCSVFilePath = GetOUCSV();

            // 先将部门文件上传至腾讯服务器
            string url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=file";
            string mediaid = string.Empty;

            //调用接口上传
            string mediaidou = HttpUploadFile(url, ouCSVFilePath);

            JObject resultInfo = JsonConvert.DeserializeObject(mediaidou);
            int errcode = Convert.ToInt32(resultInfo["errcode"]);
            if (errcode == 0)
            {
                mediaid = Convert.ToString(resultInfo["media_id"]);
                //把上传反馈的id传入批量操作部门接口
                string replacepartyInfo = ReplacepartyTest(mediaid, token);
                JObject mediaouInfo = JsonConvert.DeserializeObject(replacepartyInfo);
                int replacepartyerrcode = Convert.ToInt32(mediaouInfo["errcode"]);
                if (replacepartyerrcode == 0)
                {
                    //获取全量覆盖部门jobid
                    string jobidBM = Convert.ToString(mediaouInfo["jobid"]);
                    string ReturnBMInfo = GetReturnByJobid(token, jobidBM);
                    JObject BMResultInfo = JsonConvert.DeserializeObject(ReturnBMInfo);
                    if (Convert.ToInt32(BMResultInfo["errcode"])==0)
                    {
                        BMMsg.Text = Convert.ToString(BMResultInfo["result"]);
                    }
                    else
                    {
                        BMMsg.Text = ReturnBMInfo;

                    }
                    //上传用户文件至腾讯服务器
                    string userCSVFilePath = GetUserCSV();

                    string mediaiduser = HttpUploadFile(url, userCSVFilePath);
                    JObject resultUserInfo = JsonConvert.DeserializeObject(mediaiduser);
                    int mediaiduserErrCode = Convert.ToInt32(resultUserInfo["errcode"]);
                    if (mediaiduserErrCode == 0)
                    {
                        string userMediaId = Convert.ToString(resultUserInfo["media_id"]);
                        //把上传反馈的id传入批量操作部门接口
                        string replaceuserInfo = ReplaceUser(userMediaId, token);
                        JObject mediaiduserInfo = JsonConvert.DeserializeObject(replaceuserInfo);
                        int UserErrorCode = Convert.ToInt32(mediaiduserInfo["errcode"]);
                        if (UserErrorCode == 0)
                        {
                            //获取全量覆成员jobid
                            string jobidUser = Convert.ToString(mediaiduserInfo["jobid"]);
                            string ReturnUserInfo = GetReturnByJobid(token, jobidUser);
                            JObject UserResultInfo = JsonConvert.DeserializeObject(ReturnUserInfo);
                            if (Convert.ToInt32(UserResultInfo["errcode"]) == 0)
                            {
                                UserMsg.Text = Convert.ToString(UserResultInfo["result"]);
                            }
                            else
                            {
                                UserMsg.Text = ReturnUserInfo;

                            }
                            msg.Text = "同步成功";
                        }
                        else
                        {
                            msg.Text = replaceuserInfo;
                        }
                    }
                    else
                    {
                        msg.Text = mediaiduser;
                    }

                }
                else
                {
                    msg.Text = replacepartyInfo;
                }

            }
            else
            {
                msg.Text = mediaidou;
            }

            return result;
        }
  • 生成部门CSV文件
    public string GetOUCSV()
        {
            //更新部门
            //定义一个csv路径
            string attPath_Source = Epoint.Frame.Bizlogic.BasePage.GetApplicationPath() + "epoint_weixin_orga\\" + DateTime.Now.ToString("yyyyMMddHHmmss");//获取模板的文件夹路径
            string FileDir = System.Web.HttpContext.Current.Server.MapPath(attPath_Source);//获取服务器上的物理路径
            if (!Directory.Exists(FileDir))
            {
                Directory.CreateDirectory(FileDir);
            }
            String ouCSVFilePath = FileDir + "\\ou.csv";
            DataView dv = GetOU();
            if (!File.Exists(ouCSVFilePath)) //当文件不存在时创建文件
            {
                //创建文件流(创建文件)
                FileStream fs = new FileStream(ouCSVFilePath, FileMode.Create, FileAccess.Write);
                //创建流写入对象,并绑定文件流
                StreamWriter sw = new StreamWriter(fs);
                //实例化字符串流
                StringBuilder sb = new StringBuilder();
                //将数据添加进字符串流中(如果数据标题有变更,修改此处)
                sb.Append("部门名称").Append(",").Append("部门ID").Append(",").Append("父部门ID").Append(",").Append("排序");
                //将字符串流数据写入文件
                sw.WriteLine(sb);
                for (int i = 0; i < dv.Count; i++)
                {
                    string OUName = Convert.ToString(dv[i]["OUName"]);
                    int OUId =GetOuId( Convert.ToString(dv[i]["OUGuid"]));
                    int ParentOUid = GetOuId( Convert.ToString(dv[i]["ParentOUGuid"]));
                    string OrderNumber = Convert.ToString(dv[i]["OrderNumber"]) == null ? "0" : Convert.ToString(dv[i]["OrderNumber"]);

                    StringBuilder sbd = new StringBuilder();
                    //将需要保存的数据添加到字符串流中
                    sbd.Append(OUName).Append(",").Append(OUId).Append(",").Append(ParentOUid).Append(",").Append(OrderNumber);
                    sw.WriteLine(sbd);

                }
                //刷新文件流
                sw.Flush();
                sw.Close();
                fs.Close();
            }
            else
            {

                StreamWriter swd = new StreamWriter(ouCSVFilePath, true, Encoding.UTF8);
                StringBuilder sb = new StringBuilder();
                //将数据添加进字符串流中(如果数据标题有变更,修改此处)
                sb.Append("部门名称").Append(",").Append("部门ID").Append(",").Append("父部门ID").Append(",").Append("排序");
                //将字符串流数据写入文件
                swd.WriteLine(sb);
                for (int i = 0; i < dv.Count; i++)
                {
                    string OUName = Convert.ToString(dv[i]["OUName"]);
                    int OUId = GetOuId(Convert.ToString(dv[i]["OUGuid"]));
                    int ParentOUid = GetOuId(Convert.ToString(dv[i]["ParentOUGuid"]));
                    string OrderNumber = Convert.ToString(dv[i]["OrderNumber"]) == null ? "0" : Convert.ToString(dv[i]["OrderNumber"]);

                    StringBuilder sbd = new StringBuilder();
                    //将需要保存的数据添加到字符串流中
                    sbd.Append(OUName).Append(",").Append(OUId).Append(",").Append(ParentOUid).Append(",").Append(OrderNumber);
                    swd.WriteLine(sbd);

                }
                swd.Flush();
                swd.Close();
            }
            return ouCSVFilePath;

        }
  • 调用接口将CSV文件上传
 public static string HttpUploadFile(string url, string path)//这个方法是两个URL第一个url是微信接口地址,第二个是文件地址
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            string fileName = "ou.osv";

            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }
  • 上传反馈的id传入批量操作部门接口
        public string ReplacepartyTest(string media_id, string token)
        {
            string postDataStr = JsonSerializer(new InsertMessageparam
            {
                media_id = media_id,

            });
            // 把上传反馈的id传入批量操作部门接口
            string url1 = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty?access_token=" + token;
            string replaceparty = HttpPost(url1, postDataStr, "0");

            return replaceparty;

        }
  • Post请求
 private string HttpPost(string Url, string postDataStr, string type)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";

            if (type.Equals("1"))
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }

            else
            {
                request.ContentType = "application/json;charset=utf-8";
            }
            request.ContentLength = (long)Encoding.UTF8.GetBytes(postDataStr).Length;

            //request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            Stream myStreamWriter = request.GetRequestStream();
            myStreamWriter.Write(Encoding.UTF8.GetBytes(postDataStr), 0, Encoding.UTF8.GetByteCount(postDataStr));
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream);
            string retString = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

  • 参数
  public static string JsonSerializer(T t)
        {
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream memoryStream = new MemoryStream();
            dataContractJsonSerializer.WriteObject(memoryStream, t);
            string @string = Encoding.UTF8.GetString(memoryStream.ToArray());
            memoryStream.Close();
            return @string;
        }
   public class InsertMessageparam
        {
            public string media_id
            {
                get;
                set;
            }
        }
  • Get请求,用于获取全量覆盖部门接口调用结果
public static string HttpGet(string url)
        {
            string serviceAddress = url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
  • 前台
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sync.aspx.cs" Inherits="WebService.Sync" %>





    
    


    

参考文档:https://work.weixin.qq.com/api/doc/#90000/90135/90982

同步人员操作与同步部门类似。
以上。

你可能感兴趣的:(笔记)