Ejemplo n.º 1
0
        /// <summary>
        /// 创建部门到微信中
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentid"></param>
        /// <param name="order"></param>
        /// <param name="id"></param>
        /// <param name="compid"></param>
        /// <returns></returns>
        public ReturnJson CreateDep(string name, int parentid, int order, int id, string compid)
        {
            string    sqlstr       = string.Format($"select * from Company where CompanyID='{compid}'");
            DataTable dt           = sql.GetDataTableCommand(sqlstr);
            string    accecctoken2 = AccessTokenHelper.GetQiye(dt.Rows[0]["Longcode"].ToString(), compid, dt.Rows[0]["attoken"].ToString(), DateTime.Parse(dt.Rows[0]["expressYxq"].ToString()));
            string    accecctoken  = "q5hqUNPXpenqP8CYoBKIXk_O1BQeEgGPGbAFAH4RZ0tlwbHg7RfUnehzzTflsBrzgTZ3SAfQoTyw-3JNenL8ZwqbJ032lpIdlzg9mHfi0JFq3i5hngTrQ39cgaSlXBCdbuFjox6je9mOIPwIJsDmJHNbznpjvJENrq5cIWzehBHSiruAKatdqY0leae1kFWJqW_izuoDRo3VpUB1r1GYfA";

            if (accecctoken.Contains("access_token"))
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(QiYeaccess_token));
                MemoryStream     ms            = new MemoryStream(Encoding.UTF8.GetBytes(accecctoken));
                QiYeaccess_token obj           = (QiYeaccess_token)ser.ReadObject(ms);
                string           sqlstr2       = string.Format($"exec proc_Weixin 'UpdateAtoken','','','','','{compid}','','{obj.access_token}','{DateTime.Now.AddSeconds(int.Parse(obj.expires_in)).ToString("yyyy-MM-dd HH:mm:ss")}'");
                string           info2         = sql.EditDataCommand(sqlstr2);
                BonusHelper.AppConfig.Access_Token_Qiye = obj.access_token;
                BonusHelper.AppConfig.Qiye_YouXRQ       = DateTime.Now.AddSeconds(int.Parse(obj.expires_in)).ToString("yyyy-MM-dd HH:mm:ss");
            }
            //string accecctoken = "q5hqUNPXpenqP8CYoBKIXk_O1BQeEgGPGbAFAH4RZ0tlwbHg7RfUnehzzTflsBrzgTZ3SAfQoTyw-3JNenL8ZwqbJ032lpIdlzg9mHfi0JFq3i5hngTrQ39cgaSlXBCdbuFjox6je9mOIPwIJsDmJHNbznpjvJENrq5cIWzehBHSiruAKatdqY0leae1kFWJqW_izuoDRo3VpUB1r1GYfA";
            string url       = $"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={accecctoken}";
            string strpost   = "{\"name\": \"" + name + "\",   \"parentid\": " + parentid + ",   \"order\": " + order + "}";
            string strResult = httpHelp.PostWebRequest(url, strpost, Encoding.UTF8);

            try
            {
                if (!string.IsNullOrWhiteSpace(strResult) && strResult.Substring(0, 1) == "{" && strResult.Substring(strResult.Length - 1, 1) == "}")
                {
                    return(JSON.parse <ReturnJson>(strResult));
                }
                else
                {
                    return(new ReturnJson()
                    {
                        errmsg = string.IsNullOrWhiteSpace(strResult) ? "error" : strResult
                    });
                }
            }
            catch (Exception ex)
            {
                log.AppenLog("创建部门到微信中失败:" + ex.Message);
                return(new ReturnJson()
                {
                    errmsg = string.IsNullOrWhiteSpace(strResult) ? "error" : strResult
                });
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 得到永久授权码
        /// </summary>
        /// <param name="rc"></param>
        private void GetLongCode(object rc)
        {
            weixinStrct bs          = (weixinStrct)rc;
            string      ShortCode   = bs.ShortCode;
            string      corId       = bs.corpId;
            string      SuiteTicket = bs.SuiteTicket;

            log.AppenLog("线程:ShortCode:" + ShortCode + "_corId:" + corId + "_SuiteTicket:" + SuiteTicket);
            try
            {
                #region

                //通过临时授权码得到永久授权码
                //得到第三方应用凭证
                string suite_access_token = AccessTokenHelper.IssuitResult(corId, BonusHelper.AppConfig.Corpsecret, SuiteTicket);
                log.AppenLog("第三方应用凭证:" + suite_access_token);
                #region
                //ReturnJson rj = new ReturnJson();
                //if (!string.IsNullOrWhiteSpace(suitResult) && suitResult.Substring(0, 1) == "{" && suitResult.Substring(suitResult.Length - 1, 1) == "}")
                //{
                //    log.AppenLog("不为null");
                //    rj=JSON.parse<ReturnJson>(suitResult);
                //}
                //else
                //{
                //    log.AppenLog("为null");
                //    rj =new ReturnJson() { errmsg = string.IsNullOrWhiteSpace(suitResult) ? "error" : suitResult };
                //}
                #endregion
                //通过第三方应用凭证得到永久授权码
                Tuple <bool, LongShouquan> tu = GetLongCode(suite_access_token, ShortCode);
                if (tu.Item1)
                {
                    log.AppenLog("tu.Item1");
                    string sqlstr = string.Format($"exec proc_Weixin 'ZhuceCompany','{tu.Item2.auth_corp_info.corp_full_name}','{tu.Item2.auth_user_info.userid}','{tu.Item2.auth_corp_info.corp_square_logo_url}','{tu.Item2.permanent_code}','{tu.Item2.auth_corp_info.corpid}','{tu.Item2.auth_user_info.name}'");

                    log.AppenLog("Sqlstr:" + sqlstr);
                    //string str = "";
                    //Session[str] = tu.Item2;
                    string info = sql.EditDataCommand(sqlstr);
                    if (info == "0")
                    {
                        log.AppenLog("跟新成功");
                        //获取企业AccessToken  用于得到用户和部门

                        string Access_Token = AccessTokenHelper.GetQiye(tu.Item2.permanent_code.Replace("\"", ""), tu.Item2.auth_corp_info.corpid, string.Empty, DateTime.Now.AddDays(-1));
                        log.AppenLog("获取企业AccessToken:" + Access_Token);
                        if (Access_Token.Contains("access_token"))
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(QiYeaccess_token));
                            MemoryStream     ms            = new MemoryStream(Encoding.UTF8.GetBytes(Access_Token));
                            QiYeaccess_token obj           = (QiYeaccess_token)ser.ReadObject(ms);
                            string           sqlstr2       = string.Format($"exec proc_Weixin 'UpdateAtoken','','','','','{tu.Item2.auth_corp_info.corpid}','','{obj.access_token}','{DateTime.Now.AddSeconds(int.Parse(obj.expires_in)).ToString("yyyy-MM-dd HH:mm:ss")}'");
                            string           info2         = sql.EditDataCommand(sqlstr2);
                            BonusHelper.AppConfig.Access_Token_Qiye = obj.access_token;
                            BonusHelper.AppConfig.Qiye_YouXRQ       = DateTime.Now.AddSeconds(int.Parse(obj.expires_in)).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    else
                    {
                        log.AppenLog("跟新失败");
                    }
                }
                else
                {
                    log.AppenLog("false");
                }


                #endregion
            }
            catch (Exception ex)
            {
                log.AppenLog("线程错误:" + ex.Message);
            }
            //通过永久和id得到token
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取指定公司部门可见信息
        /// </summary>
        /// <param name="compid">公司id</param>
        /// <returns></returns>
        public ActionResult SelectDep(string compid)
        {
            compid = Base64MIMA.JIE(compid);
            string           sqlstr      = string.Format($"select * from Company where CompanyID='{compid}'");
            DataTable        dt          = sql.GetDataTableCommand(sqlstr);
            string           accecctoken = AccessTokenHelper.GetQiye(dt.Rows[0]["Longcode"].ToString(), compid, dt.Rows[0]["attoken"].ToString(), DateTime.Parse(dt.Rows[0]["expressYxq"].ToString()));
            QiYeaccess_token obj         = new QiYeaccess_token();

            if (accecctoken.Contains("access_token"))
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(QiYeaccess_token));
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(accecctoken));
                obj = (QiYeaccess_token)ser.ReadObject(ms);
                string sqlstr2 = string.Format($"exec proc_Weixin 'UpdateAtoken','','','','','{compid}','','{obj.access_token}','{DateTime.Now.AddSeconds(int.Parse(obj.expires_in)).ToString("yyyy-MM-dd HH:mm:ss")}'");
                string info2   = sql.EditDataCommand(sqlstr2);
                accecctoken = obj.access_token;
            }
            //数据库里的部门
            string    sqldep = string.Format($"select * from Depart where CompanyID='wx512ad5972960e003'");
            DataTable dtdep  = sql.GetDataTableCommand(sqldep);

            string url       = $"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={accecctoken}&id=ID";
            string strResult = httpHelp.GetWebRequest(url);

            log.AppenLog("部门:" + strResult);
            try
            {
                if (!string.IsNullOrWhiteSpace(strResult) && strResult.Substring(0, 1) == "{" && strResult.Substring(strResult.Length - 1, 1) == "}")
                {
                    WechatReturnDep wrd = JSON.parse <WechatReturnDep>(strResult);
                    if (wrd.errcode == "0")
                    {
                        List <WechatDep> listDep = wrd.department;
                        if (listDep.Count > 0)
                        {
                            string sqlstr2 = "";
                            #region 将数据库里的数据给修改过来,以微信为准
                            var vupdate = (from s in listDep
                                           where dtdep.AsEnumerable().Any(x => s.id == x.Field <int>("DepartID") && compid == x.Field <string>("CompanyID") || s.name != x.Field <string>("DepartName") || s.parentid != x.Field <int>("PID"))
                                           select s).ToList();
                            log.AppenLog("vupdate:" + vupdate.Count);
                            if (vupdate.Count > 0)
                            {
                                foreach (var item in vupdate)
                                {
                                    string JX = Pinyin.GetInitials(item.name);                //简写
                                    string QP = Pinyin.GetPinyin(item.name).Replace(" ", ""); //全拼
                                    sqlstr2 += string.Format($"update Depart set SpellJX='{JX}',SpellQP='{QP}',DepartName='{item.name}',PID='{item.parentid}' where DepartID={item.id} and  CompanyID='{compid}' ");
                                }
                            }
                            #endregion

                            #region 将数据库里有微信没有的删掉
                            var vupdel = (from s in dtdep.AsEnumerable()
                                          where !listDep.Any(x => x.id == s.Field <int>("DepartID") && compid == s.Field <string>("CompanyID"))
                                          select s).ToList();
                            if (vupdel.Count > 0)
                            {
                                foreach (var item in vupdel)
                                {
                                    sqlstr2 += string.Format($"delete Depart where DepartID={item.Field<int>("DepartID")} and CompanyID='{compid}' ");
                                }
                            }
                            #endregion

                            #region 将数据库中没有,微信中有的增加
                            var vupadd = (from s in listDep
                                          where !dtdep.AsEnumerable().Any(x => s.id == x.Field <int>("DepartID") && compid == x.Field <string>("CompanyID"))
                                          select s).ToList();
                            foreach (var item in vupadd)
                            {
                                //看数据库里是否又这个部门,如果有就不用添加到数据库


                                //else
                                //{
                                string JX = Pinyin.GetInitials(item.name);                //简写
                                string QP = Pinyin.GetPinyin(item.name).Replace(" ", ""); //全拼
                                sqlstr2 += string.Format($"insert into Depart(DepartID,DepartName, PID, DepartPrincipal, Remark,SpellJX,SpellQP,CompanyId) values({item.id},'{item.name}', '{item.parentid}', null, '','{JX}','{QP}','{compid}') ");

                                //}
                                //循环添加到数据库中
                            }
                            #endregion
                            if (sqlstr2 == "")
                            {
                                return(Content("数据一致,不需要同步"));
                            }
                            string num = sql.EditDataCommand(sqlstr2);
                            if (num == "0")
                            {
                                return(Content("ok"));
                            }
                            else
                            {
                                return(Content("同步失败"));
                            }
                        }
                        else
                        {
                            return(Content("暂无信息需要同步"));
                        }
                    }
                    else
                    {
                        return(Content("error:" + strResult));
                    }
                }
                else
                {
                    return(Content("error:" + strResult));
                    //return new ReturnJson() { errmsg = string.IsNullOrWhiteSpace(strResult) ? "error" : strResult };
                }
            }
            catch (Exception ex)
            {
                log.AppenLog("从微信中读取数据失败:" + ex.Message);
                return(Content("从微信中读取数据失败:" + strResult));
            }
        }