using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Web; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Exceptions; using Aliyun.Acs.Core.Profile; using Aliyun.Acs.Dysmsapi.Model.V20170525; using LitJson; using mas.ecloud.sdkclient; namespace LeaRun.Application.Web.Common { public class SMSServiecs { public string access_token = ""; public static Thread t; //阿里云短息 start static String product = "Dysmsapi";//短信API产品名称 static String domain = "dysmsapi.aliyuncs.com";//短信API产品域名 static String accessId = ConfigurationManager.ConnectionStrings["accessId"].ConnectionString;//"LTAIInQow33DmSFr"; static String accessSecret = ConfigurationManager.ConnectionStrings["accessSecret"].ConnectionString;//"l4xcoP3uzTIktAF5VYAZrd7yRQIb6m"; static String regionIdForPop = "cn-hangzhou"; //阿里云短信 end public static String flagStr = ConfigurationManager.ConnectionStrings["SMSCompany"].ConnectionString; public static String SignName = ConfigurationManager.ConnectionStrings["SignName"].ConnectionString; private static Client client = Client.instance; #region 阿里短信发送 public static void aliSmsSend(String phone, String temp,String type) { IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret); DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); try { //String sessionCode = SessionHelper.GetSession("verifyCode"); String json = "{"; String[] arr = temp.Split('$'); for (int i = 0; i < arr.Length; i++) { json = json + "\"param" + (i + 1).ToString() + "\":\"" + arr[i] + "\","; } json = json.TrimEnd(','); json = json + "}"; //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名(状态必须是验证通过)" //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE(状态必须是验证通过)" //request.RecNum = "13567939485";//"接收号码,多个号码可以逗号分隔" //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。" //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request); //RNum = RandomNum(); //SessionHelper.WriteSession("rNum", RNum); request.PhoneNumbers = phone; request.SignName = SignName;//"营业收费管理系统"; request.TemplateCode = type; //"SMS_96865015"; request.TemplateParam = json;//"{\"code\":\"" + nr + "\"}"; request.OutId = "123456789"; //请求失败这里会抛ClientException异常 SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request); //System.Console.WriteLine(sendSmsResponse.Message); } catch (ServerException e) { System.Console.WriteLine("ServerException"); } catch (ClientException e) { System.Console.WriteLine("ClientException"); } } #endregion public static string LoginGo(String phone, String nr) { //Http地址 string T_StengStatus = ""; try { //LoginStatus = PostHttp_Login(Url, LoginType, Ecname, Username, Password, ContentType);//登录验证 bool loginResult = client.login("", "", "", ""); int sendResult = client.sendDSMS(new string[] { phone }, nr, "", 5, "N4otVqnS", Guid.NewGuid().ToString()); //JsonData json = JsonMapper.ToObject(LoginStatus); //access_token = (String)json["access_token"]; //mas_user_id = (String)json["mas_user_id"]; //string MacString = mas_user_id + mobiles + content + sign + serial + access_token; //string mac = GetMd5Hash(MacString); // T_StengStatus = Http_SendSms(Url, SentType, mas_user_id, mobiles, content, sign, serial, mac, ContentType); T_StengStatus = sendResult.ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); } return T_StengStatus; } //登录验证 public static string PostHttp_Login(string url, string LoginType, string Ecname, string Username, string Password, string contentType) { //url += LoginType; string responseContent = "准备登录"; string body = "ec_name=" + Ecname + "&user_name=" + Username + "&user_passwd=" + Password; responseContent = HttpPost(url, body, contentType); return responseContent; } //短信发送 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) { url += senttype; string body = "mas_user_id=" + mas_user_id + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac; // Console.WriteLine("【连接】:" + url + body); string SentStatus = "准备发送"; SentStatus = HttpPost(url, body, contentType); //SentStatus = WebPost(url, body, contentType); return SentStatus; } 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) { url += senttype; string body = "mas_user_id=" + mas_user_id + "&template_id=" + tempId + "¶ms=" + param + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac; //Console.WriteLine("【连接】:" + url + body); string SentStatus = "准备发送"; SentStatus = HttpPost(url, body, contentType); //SentStatus = WebPost(url, body, contentType); return SentStatus; } //MD5计算mac public static string GetMd5Hash(String input) { if (input == null) { return null; } MD5 md5Hash = MD5.Create(); // 将输入字符串转换为字节数组并计算哈希数据 byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // 创建一个 Stringbuilder 来收集字节并创建字符串 StringBuilder sBuilder = new StringBuilder(); // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串 for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("X2")); } // 返回十六进制字符串 return sBuilder.ToString(); } //HttpPost方法 //body是要传递的参数,格式"roleId=1&uid=2" //post的cotentType填写: //"application/x-www-form-urlencoded" //soap填写:"text/xml; charset=utf-8" //http登录post private static string HttpPost(string Url, string Body, string ContentType) { string ResponseContent = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; ; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = 20000; //setInstanceFollowRedirects httpWebRequest.MediaType = "json"; byte[] btBodys = Encoding.UTF8.GetBytes(Body); httpWebRequest.ContentLength = btBodys.Length; httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); try { HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()); ResponseContent = streamReader.ReadToEnd(); httpWebResponse.Close(); streamReader.Close(); httpWebRequest.Abort(); httpWebResponse.Close(); } catch (Exception ex) { return ex.Message; } return ResponseContent; } //HttpPost方法 //body是要传递的参数,格式"roleId=1&uid=2" //post的cotentType填写: //"application/x-www-form-urlencoded" //soap填写:"text/xml; charset=utf-8" //http登录post private static string WebPost(string Url, string Body, string ContentType) { string ResponseContent = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url); httpWebRequest.ContentType = ContentType; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = 20000; byte[] btBodys = Encoding.UTF8.GetBytes(Body); httpWebRequest.ContentLength = btBodys.Length; httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); StreamReader stream = null; try { using (WebResponse response = httpWebRequest.GetResponse()) { stream = new StreamReader(response.GetResponseStream()); } } catch (WebException e) { stream = new StreamReader(e.Response.GetResponseStream()); } ResponseContent = stream.ReadToEnd(); return ResponseContent; } public static void StartSMSSend(Boolean flag) { if (flag) { t = new Thread(new ThreadStart(GainSendInfoThread)); t.Start(); } } static void GainSendInfoThread() { String phone = ""; String nr = ""; String Id = ""; String reStr = ""; String templateType =""; String templateParam = ""; //A001: while (true) { try { DataTable dt = GainSendDt(); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { phone = dt.Rows[i]["mobileNuber"].ToString(); nr = dt.Rows[i]["SMSContent"].ToString(); Id = dt.Rows[i]["SMSSend_ID"].ToString(); templateParam = dt.Rows[i]["SendParams"].ToString(); templateType = dt.Rows[i]["SendTemplate"].ToString(); switch (flagStr) { case "移动": reStr = LoginGo(phone, nr); break; case "阿里": aliSmsSend(phone, templateParam, templateType); break; } UpdateSendDt(Id); } } } catch (Exception) { } //Thread.Sleep(50); t.Suspend(); } // goto A001; } public static void topack() { switch (t.ThreadState) { // System.Threading.ThreadState.WaitSleepJoin case System.Threading.ThreadState.Stopped: t.Start(); break; case System.Threading.ThreadState.Suspended: t.Resume(); break; } } //获取数据 private static DataTable GainSendDt() { String sql = "SELECT SMSSend_ID,mobileNuber ,SMSContent,SendParams,SendTemplate FROM BCS_SMSSendRecords Where SendState = 0 ";//AND SendNum < 2 AND sendTime < GETDATE() DataTable dt; dt = SqlHelper.ExecuteDataTable(sql, CommandType.Text, null); return dt; } private static void UpdateSendDt(String Id) { String sql = "Update BCS_SMSSendRecords SET sendState = 1 WHERE SMSSend_ID = " + Id;//SendNum = SendNum + 1 int num = SqlHelper.ExecuteNoQuery(sql, CommandType.Text, null); } } }