SMSServiecs.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Web;
  12. using Aliyun.Acs.Core;
  13. using Aliyun.Acs.Core.Exceptions;
  14. using Aliyun.Acs.Core.Profile;
  15. using Aliyun.Acs.Dysmsapi.Model.V20170525;
  16. using LitJson;
  17. using mas.ecloud.sdkclient;
  18. namespace LeaRun.Application.Web.Common
  19. {
  20. public class SMSServiecs
  21. {
  22. public string access_token = "";
  23. public static Thread t;
  24. //阿里云短息 start
  25. static String product = "Dysmsapi";//短信API产品名称
  26. static String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
  27. static String accessId = ConfigurationManager.ConnectionStrings["accessId"].ConnectionString;//"LTAIInQow33DmSFr";
  28. static String accessSecret = ConfigurationManager.ConnectionStrings["accessSecret"].ConnectionString;//"l4xcoP3uzTIktAF5VYAZrd7yRQIb6m";
  29. static String regionIdForPop = "cn-hangzhou";
  30. //阿里云短信 end
  31. public static String flagStr = ConfigurationManager.ConnectionStrings["SMSCompany"].ConnectionString;
  32. public static String SignName = ConfigurationManager.ConnectionStrings["SignName"].ConnectionString;
  33. private static Client client = Client.instance;
  34. #region 阿里短信发送
  35. public static void aliSmsSend(String phone, String temp,String type)
  36. {
  37. IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);
  38. DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
  39. IAcsClient acsClient = new DefaultAcsClient(profile);
  40. SendSmsRequest request = new SendSmsRequest();
  41. try
  42. {
  43. //String sessionCode = SessionHelper.GetSession("verifyCode");
  44. String json = "{";
  45. String[] arr = temp.Split('$');
  46. for (int i = 0; i < arr.Length; i++)
  47. {
  48. json = json + "\"param" + (i + 1).ToString() + "\":\"" + arr[i] + "\",";
  49. }
  50. json = json.TrimEnd(',');
  51. json = json + "}";
  52. //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名(状态必须是验证通过)"
  53. //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE(状态必须是验证通过)"
  54. //request.RecNum = "13567939485";//"接收号码,多个号码可以逗号分隔"
  55. //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。"
  56. //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
  57. //RNum = RandomNum();
  58. //SessionHelper.WriteSession("rNum", RNum);
  59. request.PhoneNumbers = phone;
  60. request.SignName = SignName;//"营业收费管理系统";
  61. request.TemplateCode = type; //"SMS_96865015";
  62. request.TemplateParam = json;//"{\"code\":\"" + nr + "\"}";
  63. request.OutId = "123456789";
  64. //请求失败这里会抛ClientException异常
  65. SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
  66. //System.Console.WriteLine(sendSmsResponse.Message);
  67. }
  68. catch (ServerException e)
  69. {
  70. System.Console.WriteLine("ServerException");
  71. }
  72. catch (ClientException e)
  73. {
  74. System.Console.WriteLine("ClientException");
  75. }
  76. }
  77. #endregion
  78. public static string LoginGo(String phone, String nr)
  79. {
  80. //Http地址
  81. string T_StengStatus = "";
  82. try
  83. {
  84. //LoginStatus = PostHttp_Login(Url, LoginType, Ecname, Username, Password, ContentType);//登录验证
  85. bool loginResult = client.login("", "", "", "");
  86. int sendResult = client.sendDSMS(new string[] { phone }, nr, "", 5, "N4otVqnS", Guid.NewGuid().ToString());
  87. //JsonData json = JsonMapper.ToObject(LoginStatus);
  88. //access_token = (String)json["access_token"];
  89. //mas_user_id = (String)json["mas_user_id"];
  90. //string MacString = mas_user_id + mobiles + content + sign + serial + access_token;
  91. //string mac = GetMd5Hash(MacString);
  92. // T_StengStatus = Http_SendSms(Url, SentType, mas_user_id, mobiles, content, sign, serial, mac, ContentType);
  93. T_StengStatus = sendResult.ToString();
  94. }
  95. catch (Exception ex)
  96. {
  97. Console.WriteLine(ex.Message);
  98. }
  99. return T_StengStatus;
  100. }
  101. //登录验证
  102. public static string PostHttp_Login(string url, string LoginType, string Ecname, string Username, string Password, string contentType)
  103. {
  104. //url += LoginType;
  105. string responseContent = "准备登录";
  106. string body = "ec_name=" + Ecname + "&user_name=" + Username + "&user_passwd=" + Password;
  107. responseContent = HttpPost(url, body, contentType);
  108. return responseContent;
  109. }
  110. //短信发送
  111. private static string Http_SendSms(string url, string senttype, string mas_user_id, string mobiles, string content, string sign, string seria, string mac, string contentType)
  112. {
  113. url += senttype;
  114. string body = "mas_user_id=" + mas_user_id + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac;
  115. // Console.WriteLine("【连接】:" + url + body);
  116. string SentStatus = "准备发送";
  117. SentStatus = HttpPost(url, body, contentType);
  118. //SentStatus = WebPost(url, body, contentType);
  119. return SentStatus;
  120. }
  121. private static string Http_SendTSms(string url, string senttype, string mas_user_id, string tempId, string param, string mobiles, string content, string sign, string seria, string mac, string contentType)
  122. {
  123. url += senttype;
  124. string body = "mas_user_id=" + mas_user_id + "&template_id=" + tempId + "&params=" + param + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac;
  125. //Console.WriteLine("【连接】:" + url + body);
  126. string SentStatus = "准备发送";
  127. SentStatus = HttpPost(url, body, contentType);
  128. //SentStatus = WebPost(url, body, contentType);
  129. return SentStatus;
  130. }
  131. //MD5计算mac
  132. public static string GetMd5Hash(String input)
  133. {
  134. if (input == null)
  135. {
  136. return null;
  137. }
  138. MD5 md5Hash = MD5.Create();
  139. // 将输入字符串转换为字节数组并计算哈希数据
  140. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  141. // 创建一个 Stringbuilder 来收集字节并创建字符串
  142. StringBuilder sBuilder = new StringBuilder();
  143. // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
  144. for (int i = 0; i < data.Length; i++)
  145. {
  146. sBuilder.Append(data[i].ToString("X2"));
  147. }
  148. // 返回十六进制字符串
  149. return sBuilder.ToString();
  150. }
  151. //HttpPost方法
  152. //body是要传递的参数,格式"roleId=1&uid=2"
  153. //post的cotentType填写:
  154. //"application/x-www-form-urlencoded"
  155. //soap填写:"text/xml; charset=utf-8"
  156. //http登录post
  157. private static string HttpPost(string Url, string Body, string ContentType)
  158. {
  159. string ResponseContent = "";
  160. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
  161. httpWebRequest.ContentType = "application/x-www-form-urlencoded"; ;
  162. httpWebRequest.Method = "POST";
  163. httpWebRequest.Timeout = 20000; //setInstanceFollowRedirects
  164. httpWebRequest.MediaType = "json";
  165. byte[] btBodys = Encoding.UTF8.GetBytes(Body);
  166. httpWebRequest.ContentLength = btBodys.Length;
  167. httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
  168. try
  169. {
  170. HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  171. StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
  172. ResponseContent = streamReader.ReadToEnd();
  173. httpWebResponse.Close();
  174. streamReader.Close();
  175. httpWebRequest.Abort();
  176. httpWebResponse.Close();
  177. }
  178. catch (Exception ex)
  179. {
  180. return ex.Message;
  181. }
  182. return ResponseContent;
  183. }
  184. //HttpPost方法
  185. //body是要传递的参数,格式"roleId=1&uid=2"
  186. //post的cotentType填写:
  187. //"application/x-www-form-urlencoded"
  188. //soap填写:"text/xml; charset=utf-8"
  189. //http登录post
  190. private static string WebPost(string Url, string Body, string ContentType)
  191. {
  192. string ResponseContent = "";
  193. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);
  194. httpWebRequest.ContentType = ContentType;
  195. httpWebRequest.Method = "POST";
  196. httpWebRequest.Timeout = 20000;
  197. byte[] btBodys = Encoding.UTF8.GetBytes(Body);
  198. httpWebRequest.ContentLength = btBodys.Length;
  199. httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
  200. StreamReader stream = null;
  201. try
  202. {
  203. using (WebResponse response = httpWebRequest.GetResponse())
  204. {
  205. stream = new StreamReader(response.GetResponseStream());
  206. }
  207. }
  208. catch (WebException e)
  209. {
  210. stream = new StreamReader(e.Response.GetResponseStream());
  211. }
  212. ResponseContent = stream.ReadToEnd();
  213. return ResponseContent;
  214. }
  215. public static void StartSMSSend(Boolean flag)
  216. {
  217. if (flag)
  218. {
  219. t = new Thread(new ThreadStart(GainSendInfoThread));
  220. t.Start();
  221. }
  222. }
  223. static void GainSendInfoThread()
  224. {
  225. String phone = "";
  226. String nr = "";
  227. String Id = "";
  228. String reStr = "";
  229. String templateType ="";
  230. String templateParam = "";
  231. //A001:
  232. while (true)
  233. {
  234. try
  235. {
  236. DataTable dt = GainSendDt();
  237. if (dt.Rows.Count > 0)
  238. {
  239. for (int i = 0; i < dt.Rows.Count; i++)
  240. {
  241. phone = dt.Rows[i]["mobileNuber"].ToString();
  242. nr = dt.Rows[i]["SMSContent"].ToString();
  243. Id = dt.Rows[i]["SMSSend_ID"].ToString();
  244. templateParam = dt.Rows[i]["SendParams"].ToString();
  245. templateType = dt.Rows[i]["SendTemplate"].ToString();
  246. switch (flagStr)
  247. {
  248. case "移动":
  249. reStr = LoginGo(phone, nr);
  250. break;
  251. case "阿里":
  252. aliSmsSend(phone, templateParam, templateType);
  253. break;
  254. }
  255. UpdateSendDt(Id);
  256. }
  257. }
  258. }
  259. catch (Exception)
  260. {
  261. }
  262. //Thread.Sleep(50);
  263. t.Suspend();
  264. }
  265. // goto A001;
  266. }
  267. public static void topack()
  268. {
  269. switch (t.ThreadState)
  270. {
  271. // System.Threading.ThreadState.WaitSleepJoin
  272. case System.Threading.ThreadState.Stopped:
  273. t.Start();
  274. break;
  275. case System.Threading.ThreadState.Suspended:
  276. t.Resume();
  277. break;
  278. }
  279. }
  280. //获取数据
  281. private static DataTable GainSendDt()
  282. {
  283. String sql = "SELECT SMSSend_ID,mobileNuber ,SMSContent,SendParams,SendTemplate FROM BCS_SMSSendRecords Where SendState = 0 ";//AND SendNum < 2 AND sendTime < GETDATE()
  284. DataTable dt;
  285. dt = SqlHelper.ExecuteDataTable(sql, CommandType.Text, null);
  286. return dt;
  287. }
  288. private static void UpdateSendDt(String Id)
  289. {
  290. String sql = "Update BCS_SMSSendRecords SET sendState = 1 WHERE SMSSend_ID = " + Id;//SendNum = SendNum + 1
  291. int num = SqlHelper.ExecuteNoQuery(sql, CommandType.Text, null);
  292. }
  293. }
  294. }