最近项目中使用了环信,根据官方文档,自己封装了一个类,可以实现
用户注册
群组创建
发送文本消息
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
}
}