C#루프 메시지 사용자 및 커뮤니티 작업

11649 단어 C#ASP.NET
최근 프로젝트에서 링 편지를 사용했는데 공식 문서에 따라 하나의 종류를 봉하여 실현할 수 있다
사용자 등록
그룹 생성
텍스트 메시지 보내기
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Text;
namespace WinBLL
{
    public static class WinHxGroups
    {
        private static string HXAppKey = System.Web.Configuration.WebConfigurationManager.AppSettings["HXAppKey"].Split('#')[0];
        private static string HXAppKey1 = System.Web.Configuration.WebConfigurationManager.AppSettings["HXAppKey"].Split('#')[1];
        private static string HXClientID = System.Web.Configuration.WebConfigurationManager.AppSettings["HXClientID"];
        private static string HXClientSecret = System.Web.Configuration.WebConfigurationManager.AppSettings["HXClientSecret"];
        private static string HXAdminMobile= System.Web.Configuration.WebConfigurationManager.AppSettings["HXAdminMobile"]; 

        #region       Token
        /// 
        ///       Token
        /// 
        /// 
        public static string GetHXToken()
        {
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/token";
            var postData = "{ \"grant_type\": \"client_credentials\", \"client_id\": \"" + HXClientID + "\", \"client_secret\": \"" + HXClientSecret + "\"}";
            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpClient client = new HttpClient();
            HttpResponseMessage hrm = client.PostAsync(url, httpContent).Result;
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                JObject JO = (JObject)JsonConvert.DeserializeObject(hrm.Content.ReadAsStringAsync().Result);
                return JO["access_token"].ToString();
            }
            hrm.Dispose();
            client.Dispose();
            // string Token = client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
            return "";
        }
        #endregion

        #region          
        /// 
        ///          
        /// 
        /// 
        public static List ChatGroups()
        {
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/chatgroups";
            var postData = "Bearer " + GetHXToken();

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", postData);
            HttpResponseMessage hrm = client.GetAsync(url).Result;


            List LS_Groups = new List();
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                JObject JO = (JObject)JsonConvert.DeserializeObject(hrm.Content.ReadAsStringAsync().Result);
                JArray JA = (JArray)JsonConvert.DeserializeObject(JO["data"].ToString());
                foreach (JObject j in JA)
                {
                    //      ,          
                    url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/chatgroups/" + j["groupid"].ToString();
                    hrm = client.GetAsync(url).Result;
                    JObject GroupInfo = (JObject)JsonConvert.DeserializeObject(hrm.Content.ReadAsStringAsync().Result);
                    JArray JA1 = (JArray)JsonConvert.DeserializeObject(GroupInfo["data"].ToString());
                    WinModel.HuanXin.HX_Group m = new WinModel.HuanXin.HX_Group()
                    {
                        GroupID = j["groupid"].ToString(),//   ID
                        GroupUsersCount = int.Parse(JA1[0]["affiliations_count"].ToString()),
                        GroupType = JA1[0]["description"].ToString()
                    };
                    LS_Groups.Add(m);
                }
            }
            hrm.Dispose();
            client.Dispose();
            return LS_Groups;
        }
        #endregion

        #region           
        public static bool CheckUser(string ID)
        {
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/users/" + ID;
            var postData = "Bearer " + GetHXToken();

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", postData);
            HttpResponseMessage hrm = client.GetAsync(url).Result;
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region       
        /// 
        ///         
        /// 
        ///    
        /// IOS     0  IOS 1    
        /// 
        public static bool RegeditUser(string ID, int GroupType,out string GroupID)
        {
            GroupID = string.Empty;
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/users"; 
            string postData = "{ \"username\": \"" + ID + "\", \"password\": \"" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(ID, "MD5").ToLower() + "\"}";
            string Token = GetHXToken();
            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token);
            HttpResponseMessage hrm = client.PostAsync(url, httpContent).Result;//reg
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //    
                HxGroups Model = new HxGroups();
                Model = GetModel(GroupType);//                   
                if (Model.HX_GroupType == null)
                {
                    //          
                    Model = CreatGroup("   ", 1, GroupType,Token); 
                }
                url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/chatgroups/" + Model.HX_GroupID + "/users/" + ID;
                hrm = client.PostAsync(url, null).Result;//   
                if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Model.HX_GroupUsers += 1;                    
                    Update(Model);//                        
                    //       ID
                    GroupID = Model.HX_GroupID;
                    hrm.Dispose();
                    client.Dispose();
                    return true;
                }
                hrm.Dispose();
                client.Dispose();
                return false;
            }
            hrm.Dispose();
            client.Dispose();
            // string Token = client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
            return false;
        }
        #endregion

        #region       
        public static HxGroups CreatGroup(string GroupName, int GroupUsers, int GroupType,string Token)
        {
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/chatgroups"; 
            string postData = " {\"groupname\": \""+ (GroupName+ (GroupType==0?"IOS":"AZ")) + "\",\"desc\": \"" + (GroupType == 0 ? "IOS" : "AZ") + "\",\"public\": false,\"maxusers\": 2000,\"approval\": true,\"owner\": \""+ HXAdminMobile + "\"}";
            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token);
            HttpResponseMessage hrm = client.PostAsync(url, httpContent).Result;
            HxGroups Model = new HxGroups();
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                JObject JO = (JObject)JsonConvert.DeserializeObject(hrm.Content.ReadAsStringAsync().Result);
                JO = (JObject)JsonConvert.DeserializeObject(JO["data"].ToString());
                string GroupID = JO["groupid"].ToString();
               // JArray JA = (JArray)JsonConvert.DeserializeObject(JO["data"].ToString());
                Model.HX_GroupID = GroupID;
                Model.HX_GroupType = GroupType;
                Model.HX_GroupUsers = 1;
                if(Insert(Model))//                  
                {
                    hrm.Dispose();
                    client.Dispose();
                    return Model;
                }
                else
                {
                    hrm.Dispose();
                    client.Dispose();
                    return null;
                } 
            }
            else
            {
                hrm.Dispose();
                client.Dispose();
                return null;
            }
        }
        #endregion

        #region       
        /// 
        ///            
        /// 
        ///   
        ///      IOS ,0  IOS 1    
        /// 
        public static bool SendMsgToGroups(string Msg,int GroupType,out string ReturnCode)
        {            
            ReturnCode = "200";
            string url = "http://a1.easemob.com/" + HXAppKey + "/" + HXAppKey1 + "/messages";
            List LS_HX = new List();
            LS_HX = GetList(GroupType);//                  
            StringBuilder sb = new StringBuilder();

            foreach(HxGroups m in LS_HX)
            {
                sb.Append("\""+m.HX_GroupID+"\",");
            }
      
            string postData = "{\"target_type\": \"chatgroups\", \"target\": ["+sb.ToString().TrimEnd(',')+"],\"msg\": {\"type\": \"txt\",\"msg\": \""+ Msg + "\"}}";
            string Token = GetHXToken();
            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token);
            HttpResponseMessage hrm = client.PostAsync(url, httpContent).Result;//reg
            if (hrm.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return true;
            }
            ReturnCode = hrm.StatusCode.ToString();
            return false;
            }
        #endregion
    }
}

좋은 웹페이지 즐겨찾기