asp.Net企業微信開発の同期通信録

14310 ワード

テンセントが提供した企業微信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
    --" + boundary + "\r
    "); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r
    --" + boundary + "--\r
    "); string fileName = "ou.osv"; // StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r
    Content-Type:application/octet-stream\r
    \r
    ", 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;
            }
    
  • フロント
  • 
    
    
    
    
    
        
        
    
    
        <form id="form1" runat="server">
            <div>
                <button runat="server" id="syncOrga" text="        " onclick="syncOrga_Click"/>     
            </div>
        </form>
    
    
    
    </code></pre>
    <h2>    :https://work.weixin.qq.com/api/doc/#90000/90135/90982</h2>
    <p>             。<br/>   。</p>
    </div>
    </div>
    </div>
    </div>