model类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IQingWei.Core.RongIM
{
public class RongIMMOdel
{
}
/// <summary>
/// 发送消息对象
/// </summary>
public class SendMessageModel
{
/// <summary>
/// 发送者ID
/// </summary>
public string fromUserId { set; get; }
/// <summary>
/// 接收者ID
/// </summary>
public string toUserId { set; get; }
/// <summary>
/// 消息类型
/// 文字消息 RC:TxtMsg TextMessage
/// 语音消息 RC:VcMsg VoiceMessage
/// 高质量语音消息 RC:HQVCMsg HQVoiceMessage
/// 图片消息 RC:ImgMsg ImageMessage
/// GIF 图片消息 RC:GIFMsg GIFMessage
/// 图文消息 RC:ImgTextMsg RichContentMessage
/// 文件消息 RC:FileMsg FileMessage
/// 位置消息 RC:LBSMsg LocationMessage
/// 小视频消息 RC:SightMsg SightMessage
/// 合并转发消息 RC:CombineMsg CombineMessage
/// 公众服务单图文消息 RC:PSImgTxtMsg PublicServiceRichContentMessage
/// 公众服务多图文消息 RC:PSMultiImgTxtMsg PublicServiceMultiRichContentMessage
/// </summary>
public string objectName { set; get; }
/// <summary>
/// 消息内容 此消息是一个对象
/// </summary>
public Content content { set; get; }
/// <summary>
/// 推送内容
/// </summary>
public string pushContent { set; get; }
/// <summary>
/// 推送时间
/// </summary>
public string pushData { set; get; }
/// <summary>
/// 未读消息条数 1
/// </summary>
public int count { set; get; }
/// <summary>
/// 是否过滤接收用户黑名单列表 0标识不过滤 1表示过滤
/// </summary>
public int verifyBlacklist { set; get; }
/// <summary>
/// 云服务是否存储消息
/// </summary>
public int isPersisted { set; get; }
/// <summary>
/// 终端用户在线状态下,发送用户自己是否接收消息,0 表示为不接收,1 表示为接收,默认为 0 不接收
/// </summary>
public int isIncludeSender { set; get; }
/// <summary>
/// 针对 iOS 平台,对 SDK 处于后台暂停状态时为静默推送 1 表示为开启,0 表示为关闭,默认为 0(可选)
/// </summary>
public int contentAvailable { set; get; }
}
/// <summary>
/// 内容格式
/// </summary>
public class Content
{
/// <summary>
/// 消息内容
/// </summary>
public string content {set;get;}
/// <summary>
/// 时长
/// </summary>
public string duration { set; get; }
/// <summary>
/// 用户信息
/// </summary>
public User user { set; get; }
/// <summary>
/// 扩展信息
/// </summary>
public string extra { set; get; }
}
/// <summary>
/// 发送者用户
/// </summary>
public class User
{
/// <summary>
/// 用户ID
/// </summary>
public string id { set; get; }
/// <summary>
/// 名称
/// </summary>
public string name { set; get; }
/// <summary>
/// 头像
/// </summary>
public string icon { set; get; }
/// <summary>
/// 扩展信息
/// </summary>
public string extra { set; get; }
}
}
API类
public class RongIMApi
{
/// <summary>
/// 融云的APPKey
/// </summary>
public static string AppKey = "25wehl3u20fpw";
/// <summary>
/// 融云 密钥
/// </summary>
public static string AppSecret = "3QlaeDTArU83wg";
/// <summary>
/// 获取token的URL
/// </summary>
public static string Token_URL = "http://api-cn.ronghub.com/user/getToken.json";
/// <summary>
/// 刷新用户资料的url
/// </summary>
public static string TefreshUser_URL = "http://api-cn.ronghub.com/user/refresh.json";
/// <summary>
/// 发送消息
/// </summary>
public static string SendMessage_URL = "http://api-cn.ronghub.com/message/private/publish.json";
#region 获取token
/// <summary>
/// 获取token
/// </summary>
/// <param name="UserID">用户ID</param>
/// <param name="NickName">昵称</param>
/// <param name="FaceUrl">头像</param>
/// <returns></returns>
public static string GetToken(string UserID, string NickName, string FaceUrl)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
string nonceStr = Guid.NewGuid().ToString();
nonceStr = nonceStr.Replace("-", "");//随机字符串
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("userId", UserID);
parameters.Add("name", NickName);
parameters.Add("portraitUri", FaceUrl);
string result= RequestURL(Token_URL, parameters, nonceStr, timestamp);
string token=string.Empty;
JObject ResutObj = JObject.Parse(result);
if (ResutObj["code"] != null && ResutObj["code"].ToString() == "200")
{
token = ResutObj["token"].ToString();
}
return token;
}
#endregion
#region 刷新用户资料
/// <summary>
/// 刷新用户资料
/// </summary>
/// <param name="UserID">用户ID</param>
/// <param name="NickName">昵称</param>
/// <param name="FaceUrl">头像</param>
/// <returns></returns>
public static string TefreshUserMessage(string UserID, string NickName, string FaceUrl)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
string nonceStr = Guid.NewGuid().ToString();
nonceStr = nonceStr.Replace("-", "");//随机字符串
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("userId", UserID);
parameters.Add("name", NickName);
parameters.Add("portraitUri", FaceUrl);
string result = RequestURL(TefreshUser_URL, parameters, nonceStr, timestamp);
return result;
}
#endregion
#region 发送消息
/// <summary>
/// 发送消息
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static string SendUserMessage(IQingWei.Core.RongIM.SendMessageModel model)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
string nonceStr = Guid.NewGuid().ToString();
nonceStr = nonceStr.Replace("-", "");//随机字符串
JavaScriptSerializer _JavaScriptSerializer = new JavaScriptSerializer();//json转字符串
string ContentJSON = _JavaScriptSerializer.Serialize(model.content);
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("fromUserId", model.fromUserId);
parameters.Add("toUserId", model.toUserId);
parameters.Add("objectName", model.objectName);
parameters.Add("content", ContentJSON);
parameters.Add("pushContent", model.pushContent);
parameters.Add("pushData", model.pushData);
parameters.Add("count", model.count);
parameters.Add("verifyBlacklist", model.verifyBlacklist);
parameters.Add("isPersisted", model.isPersisted);
parameters.Add("isIncludeSender", model.isIncludeSender);
parameters.Add("contentAvailable", model.contentAvailable);
string result = RequestURL(SendMessage_URL, parameters, nonceStr, timestamp);
return result;
}
#endregion
#region 待上传的请求参数
/// <summary>
/// 待上传的请求参数
/// </summary>
/// <param name="url"></param>
/// <param name="parameters"></param>
/// <param name="Nonce"></param>
/// <param name="Timestamp"></param>
/// <returns></returns>
public static string RequestURL(string url, IDictionary<string, object> parameters, string Nonce, string Timestamp)
{
HttpWebRequest req = null;
Stream requestStream = null;
string returnValue = string.Empty;
try
{
req = (HttpWebRequest)WebRequest.Create(new Uri(url));
req.Method = "POST";
req.Timeout = 300000;
req.Host = "api-cn.ronghub.com";
req.Headers.Add("App-Key", AppKey);
req.Headers.Add("Nonce", Nonce);
req.Headers.Add("Timestamp", Timestamp);
req.Headers.Add("Signature", Sha1(Nonce, Timestamp));
req.ContentType = "application/x-www-form-urlencoded" ;
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery2(parameters, "utf8"));
requestStream = req.GetRequestStream();
requestStream.Write(postData, 0, postData.Length);
//获取服务器端的响应
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
returnValue = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return returnValue;
}
#endregion
#region 组装普通文本请求参数
/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
public static string BuildQuery2(IDictionary<string, object> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, object>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
object value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (name == "file")
{
Bitmap b = new Bitmap(value.ToString());
MemoryStream ms = new MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imagedata = null;
b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imagedata = ms.GetBuffer();
postData.Append(HttpUtility.UrlEncode(imagedata));
}
else
{
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value.ToString(), Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(value.ToString());
}
else
{
postData.Append(value);
}
}
hasParam = true;
}
}
return postData.ToString();
}
#endregion
#region 生成签名
/// <summary>
/// 生成签名 对参数 AppSecret+Nonce+Stime拼接后(+号表示连接符)进行SHA1加密得到签名,值为40位小写字符串。
/// </summary>
/// <param name="Nonce"></param>
/// <param name="Stime"></param>
/// <returns></returns>
private static string Sha1( string Nonce, string Stime)
{
var buffer = Encoding.UTF8.GetBytes(AppSecret + Nonce + Stime);
var data = SHA1.Create().ComputeHash(buffer);
var sb = new StringBuilder();
foreach (var t in data)
{
sb.Append(t.ToString("X2"));
}
return sb.ToString().ToLower();
}
#endregion