Asp.Net发送手机验证码
C#发送手机验证码,平台有很多,我就说说其中的1个平台
测试环境:.net2.0
测试效果:速度还可以,10秒内接收短信
1、去http://www.yuntongxun.com注册,会送8元测试金额;正式使用必须充值500元以上才行
2、部署代码
另一个平台感觉也不错,注册送100条短信,认证再送500条短信http://www.etuocloud.com
核心测试代码,红色为你需要改下的参数
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Reflection; public partial class ceshi : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ret = null; CCPRestSDK.CCPRestSDK api = new CCPRestSDK.CCPRestSDK();
//ip格式如下,不带https://
bool isInit = api.init("app.cloopen.com", "");//sandboxapp.cloopen.com
api.setAccount("816da7878745458787545878", "7bbd1891jkdjfjaksldfjk054bd54f6");//主账号,主账号令牌
api.setAppId("jkdsjfkdjfkdsfjlsjueorun");//AppID try
{
if (isInit)
{
string[] data = { "", "" };//验证码,时间
Dictionary<string, object> retData = api.SendTemplateSMS("", "", data);//短信接收号码, 短信模板id, 内容数据
ret = getDictionaryData(retData);
string statusCode = retData["statusCode"].ToString();
string statusMsg = retData["statusMsg"].ToString(); Response.Write(statusCode + "==" + statusMsg + "<br><br><br><br>"); }
else
{
ret = "初始化失败";
}
}
catch (Exception exc)
{
ret = exc.Message;
}
finally
{
Response.Write(ret);
}
} private string getDictionaryData(Dictionary<string, object> data)
{
string ret = null;
foreach (KeyValuePair<string, object> item in data)
{
if (item.Value != null && item.Value.GetType() == typeof(Dictionary<string, object>))
{
ret += item.Key.ToString() + "={";
ret += getDictionaryData((Dictionary<string, object>)item.Value);
ret += "};";
}
else
{
ret += item.Key.ToString() + "=" + (item.Value == null ? "null" : item.Value.ToString()) + ";";
}
}
return ret;
}
}
CCPRestSDK类,经改良支持.net2.0
/*
* Copyright (c) 2014 The CCP project authors. All Rights Reserved.
*
* Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
* that can be found in the LICENSE file in the root of the web site.
*
* http://www.114390.com
*
* An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/ using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml; namespace CCPRestSDK
{
enum EBodyType:uint
{
EType_XML = ,
EType_JSON
}; public class CCPRestSDK
{
private string m_restAddress = null;
private string m_restPort = null;
private string m_mainAccount = null;
private string m_mainToken = null;
private string m_subAccount = null;
private string m_subToken = null;
private string m_voipAccount = null;
private string m_voipPwd = null;
private string m_appId = null;
private bool m_isWriteLog = false; private EBodyType m_bodyType = EBodyType.EType_XML; /// <summary>
/// 服务器api版本
/// </summary>
const string softVer = "2013-12-26"; /// <summary>
/// 初始化函数
/// </summary>
/// <param name="serverIP">服务器地址</param>
/// <param name="serverPort">服务器端口</param>
/// <returns></returns>
public bool init(string restAddress, string restPort)
{
this.m_restAddress = restAddress;
this.m_restPort = restPort; if (m_restAddress == null || m_restAddress.Length < || m_restPort == null || m_restPort.Length < || Convert.ToInt32(m_restPort) < )
return false; return true;
} /// <summary>
/// 设置主帐号信息
/// </summary>
/// <param name="accountSid">主帐号</param>
/// <param name="accountToken">主帐号令牌</param>
public void setAccount(string accountSid, string accountToken)
{
this.m_mainAccount = accountSid;
this.m_mainToken = accountToken;
} /// <summary>
/// 设置子帐号信息
/// </summary>
/// <param name="subAccountSid">子帐号</param>
/// <param name="subAccountToken">子帐号令牌</param>
/// <param name="voipAccount">VoIP帐号</param>
/// <param name="voipPassword">VoIP密码</param>
public void setSubAccount(string subAccountSid, string subAccountToken, string voipAccount, string voipPassword)
{
this.m_subAccount = subAccountSid;
this.m_subToken = subAccountToken;
this.m_voipAccount = voipAccount;
this.m_voipPwd = voipPassword;
} /// <summary>
/// 设置应用ID
/// </summary>
/// <param name="appId">应用ID</param>
public void setAppId(string appId)
{
this.m_appId = appId;
} /// <summary>
/// 日志开关
/// </summary>
/// <param name="enable">日志开关</param>
public void enabeLog(bool enable)
{
this.m_isWriteLog = enable;
} /// <summary>
/// 获取日志路径
/// </summary>
/// <returns>日志路径</returns>
public string GetLogPath()
{
string dllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
dllpath = dllpath.Substring(, dllpath.Length - ); // 8是 file:// 的长度
return System.IO.Path.GetDirectoryName(dllpath)+"\\log.txt";
} /// <summary>
/// 主帐号信息查询
/// </summary>
/// <exception cref="Exception"></exception>
/// <returns>包体内容</returns>
public Dictionary<string,object> QueryAccountInfo()
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/AccountInfo?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("QueryAccountInfo url = "+uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "GET";
Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("QueryAccountInfo responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null); XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "Account")
{
Dictionary<string, object> data = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
data.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> {{item.Name,data}};
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, data);
responseResult["data"] = data1;
}
}
return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("QueryAccountInfo responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
Dictionary<string, object> responseResult = new Dictionary<string, object> ();
responseResult["resposeBody"] = responseStr;
return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
} // 获取请求
}
catch (Exception e)
{
throw e;
} } /// <summary>
/// 创建子帐号
/// </summary>
/// <param name="friendlyName">子帐号名称。可由英文字母和阿拉伯数字组成子帐号唯一名称,推荐使用电子邮箱地址</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns>包体内容</returns>
public Dictionary<string, object> CreateSubAccount(string friendlyName)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if(friendlyName == null)
throw new ArgumentNullException("friendlyName"); try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/SubAccounts?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("CreateSubAccount url = " +uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><SubAccount>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<friendlyName>").Append(friendlyName).Append("</friendlyName>");
data.Append("</SubAccount>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"appId\":\"").Append(m_appId).Append("\"");
data.Append(",\"friendlyName\":\"").Append(friendlyName).Append("\"");
data.Append("}");
} byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("CreateSubAccount requestBody = " +data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("CreateSubAccount responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "SubAccount")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 获取应用下子帐号
/// </summary>
/// <param name="startNo">开始的序号,默认从0开始</param>
/// <param name="offset">一次查询的最大条数,最小是1条,最大是100条</param>
/// <exception cref="ArgumentOutOfRangeException">参数超出范围</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> GetSubAccounts(uint startNo, uint offset)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (offset < || offset > )
{
throw new ArgumentOutOfRangeException("offset超出范围");
}
try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/GetSubAccounts?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("GetSubAccounts url = "+uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><SubAccount>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<startNo>").Append(startNo).Append("</startNo>");
data.Append("<offset>").Append(offset).Append("</offset>");
data.Append("</SubAccount>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"appId\":\"").Append(m_appId).Append("\"");
data.Append(",\"startNo\":\"").Append(startNo).Append("\"");
data.Append(",\"offset\":\"").Append(offset).Append("\"");
data.Append("}");
} byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("GetSubAccounts requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("GetSubAccounts responseBody = "+responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null); Dictionary<string, object> retData = new Dictionary<string, object>();
List<object> subAccountList = new List<object>(); if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "totalCount")
{
retData.Add(item.Name, item.InnerText);
}
else if (item.Name == "SubAccount")
{
Dictionary<string, object> SubAccount = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
SubAccount.Add(subItem.Name, subItem.InnerText);
}
subAccountList.Add(SubAccount);
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} if (retData.Count > )
{
if (subAccountList.Count > )
{
retData.Add("SubAccount", subAccountList);
}
responseResult["data"] = retData;
}
return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 查询子帐号信息
/// </summary>
/// <param name="friendlyName">子帐号名称</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns>包体内容</returns>
public Dictionary<string, object> QuerySubAccount(string friendlyName)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (friendlyName == null)
throw new ArgumentNullException("friendlyName"); try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/QuerySubAccountByName?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("QuerySubAccount url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><SubAccount>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<friendlyName>").Append(friendlyName).Append("</friendlyName>");
data.Append("</SubAccount>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"appId\":\"").Append(m_appId).Append("\"");
data.Append(",\"friendlyName\":\"").Append(friendlyName).Append("\"");
data.Append("}");
} byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("QuerySubAccount requestBody = "+data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("QuerySubAccount responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "SubAccount")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 发送短信
/// </summary>
/// <param name="to">短信接收端手机号码集合,用英文逗号分开,每批发送的手机号数量不得超过100个</param>
/// <param name="body">短信内容</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="ArgumentOutOfRangeException">参数超出范围</exception>
/// <exception cref="Exception"></exception>
/// <returns>包体内容</returns>
public Dictionary<string, object> SendSMS(string to, string body)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (to == null)
{
throw new ArgumentNullException("to");
} if (body == null)
{
throw new ArgumentNullException("body");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/SMS/Messages?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("SendSMS url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><SMSMessage>");
data.Append("<to>").Append(to).Append("</to>");
data.Append("<body>").Append(body).Append("</body>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("</SMSMessage>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"to\":\"").Append(to).Append("\"");
data.Append(",\"body\":\"").Append(body).Append("\"");
data.Append(",\"appId\":\"").Append(m_appId).Append("\"");
data.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("SendSMS requestBody = "+data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("SendSMS responseBody = "+responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "SMSMessage")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{ throw e;
} } /// <summary>
/// 模板短信
/// </summary>
/// <param name="to">短信接收端手机号码集合,用英文逗号分开,每批发送的手机号数量不得超过100个</param>
/// <param name="templateId">模板Id</param>
/// <param name="data">可选字段 内容数据,用于替换模板中{序号}</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> SendTemplateSMS(string to, string templateId, string[] data)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (to == null)
{
throw new ArgumentNullException("to");
} if (templateId == null)
{
throw new ArgumentNullException("templateId");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/SMS/TemplateSMS?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("SendTemplateSMS url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder bodyData = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; bodyData.Append("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>");
bodyData.Append("<to>").Append(to).Append("</to>");
bodyData.Append("<appId>").Append(m_appId).Append("</appId>");
bodyData.Append("<templateId>").Append(templateId).Append("</templateId>");
if (data != null && data.Length>)
{
bodyData.Append("<datas>");
foreach (string item in data)
{
bodyData.Append("<data>").Append(item).Append("</data>");
}
bodyData.Append("</datas>");
}
bodyData.Append("</TemplateSMS>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; bodyData.Append("{");
bodyData.Append("\"to\":\"").Append(to).Append("\"");
bodyData.Append(",\"appId\":\"").Append(m_appId).Append("\"");
bodyData.Append(",\"templateId\":\"").Append(templateId).Append("\"");
if (data != null && data.Length > )
{
bodyData.Append(",\"datas\":[");
int index = ;
foreach (string item in data)
{
if (index == )
{
bodyData.Append("\""+item+"\"");
}
else
{
bodyData.Append(",\"" + item + "\"");
}
index++;
}
bodyData.Append("]");
}
bodyData.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(bodyData.ToString()); WriteLog("SendTemplateSMS requestBody = " + bodyData.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("SendTemplateSMS responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "TemplateSMS")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } }; Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{ throw e;
}
} /// <summary>
/// 双向回呼
/// </summary>
/// <param name="from">主叫电话</param>
/// <param name="to">被叫电话</param>
/// <param name="customerSerNum">可选字段 被叫侧显示的客服号码,根据平台侧显号规则控制</param>
/// <param name="fromSerNum">可选字段 主叫侧显示的号码,根据平台侧显号规则控制</param>
/// <param name="promptTone">可选字段 第三方自定义回拨提示音</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns>包体内容</returns>
public Dictionary<string, object> CallBack(string from, string to, string customerSerNum, string fromSerNum, string promptTone)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
} initError = paramCheckSunAccount();
if (initError != null)
{
return initError;
} if (from == null)
{
throw new ArgumentNullException("from");
} if (to == null)
{
throw new ArgumentNullException("to");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_subAccount + m_subToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/SubAccounts/{3}/Calls/Callback?sig={4}", m_restAddress, m_restPort, softVer, m_subAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("CallBack url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_subAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder();
if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><CallBack>");
data.Append("<from>").Append(from).Append("</from>");
data.Append("<to>").Append(to).Append("</to>");
if (customerSerNum != null)
{
data.Append("<customerSerNum>").Append(customerSerNum).Append("</customerSerNum>");
} if (fromSerNum != null)
{
data.Append("<fromSerNum>").Append(fromSerNum).Append("</fromSerNum>");
} if (promptTone != null)
{
data.Append("<promptTone>").Append(promptTone).Append("</promptTone>");
} data.Append("</CallBack>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"from\":\"").Append(from).Append("\"");
data.Append(",\"to\":\"").Append(to).Append("\"");
if (customerSerNum != null)
{
data.Append(",\"customerSerNum\":\"").Append(customerSerNum).Append("\"");
}
if (fromSerNum != null)
{
data.Append(",\"fromSerNum\":\"").Append(fromSerNum).Append("\"");
}
if (promptTone != null)
{
data.Append(",\"promptTone\":\"").Append(promptTone).Append("\"");
}
data.Append("}");
} byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("CallBack requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("CallBack responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "CallBack")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 外呼通知
/// </summary>
/// <param name="to">被叫号码</param>
/// <param name="mediaName">可选字段 语音文件名称,格式 wav。与mediaTxt不能同时为空,不为空时mediaTxt属性失效</param>
/// <param name="mediaTxt">可选字段 文本内容,默认值为空</param>
/// <param name="displayNum">可选字段 显示的主叫号码,显示权限由服务侧控制</param>
/// <param name="playTimes">可选字段 循环播放次数,1-3次,默认播放1次</param>
/// <param name="type">可选字段 语音文件名的类型,默认值为0,表示用户语音文件;值为1表示平台通用文件</param>
/// <param name="respUrl">可选字段 外呼通知状态通知回调地址,云通讯平台将向该Url地址发送呼叫结果通知</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> LandingCall(string to, string mediaName, string mediaTxt, string displayNum, string playTimes, int type, string respUrl)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (to == null)
{
throw new ArgumentNullException("to");
} if (mediaName==null && mediaTxt==null)
{
throw new ArgumentNullException("mediaName和mediaTxt同时为null");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/Calls/LandingCalls?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("LandingCall url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder();
if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><LandingCall>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<to>").Append(to).Append("</to>"); if (mediaName != null)
{
data.Append("<mediaName type=\""+type+"\">").Append(mediaName).Append("</mediaName>");
} if (mediaTxt != null)
{
data.Append("<mediaTxt>").Append(mediaTxt).Append("</mediaTxt>");
} if (displayNum!=null)
{
data.Append("<displayNum>").Append(displayNum).Append("</displayNum>");
} if (playTimes!=null)
{
data.Append("<playTimes>").Append(playTimes).Append("</playTimes>");
} if (respUrl!=null)
{
data.Append("<respUrl>").Append(respUrl).Append("</respUrl>");
} data.Append("</LandingCall>"); }
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"to\":\"").Append(to).Append("\"");
data.Append(",\"appId\":\"").Append(m_appId).Append("\"");
if (mediaName != null)
{
data.Append(",\"mediaName\":\"").Append(mediaName).Append("\"");
data.Append(",\"mediaNameType\":\"").Append(type).Append("\"");
} if (mediaTxt != null)
{
data.Append(",\"mediaTxt\":\"").Append(mediaTxt).Append("\"");
} if (displayNum != null)
{
data.Append(",\"displayNum\":\"").Append(displayNum).Append("\"");
} if (playTimes != null)
{
data.Append(",\"playTimes\":\"").Append(playTimes).Append("\"");
} if (respUrl != null)
{
data.Append(",\"respUrl\":\"").Append(respUrl).Append("\"");
} data.Append("}");
}
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("LandingCall requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("LandingCall responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "LandingCall")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 语音验证码
/// </summary>
/// <param name="to">接收号码</param>
/// <param name="verifyCode">验证码内容,为数字和英文字母,不区分大小写,长度4-8位</param>
/// <param name="displayNum">可选字段 显示主叫号码,显示权限由服务侧控制</param>
/// <param name="playTimes">可选字段 循环播放次数,1-3次,默认播放1次</param>
/// <param name="respUrl">可选字段 语音验证码状态通知回调地址,云通讯平台将向该Url地址发送呼叫结果通知</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> VoiceVerify(string to, string verifyCode, string displayNum, string playTimes, string respUrl)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (to == null)
{
throw new ArgumentNullException("to");
} if (verifyCode == null)
{
throw new ArgumentNullException("verifyCode");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/Calls/VoiceVerify?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("VoiceVerify url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder();
if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><VoiceVerify>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<verifyCode>").Append(verifyCode).Append("</verifyCode>");
data.Append("<to>").Append(to).Append("</to>"); if (displayNum != null)
{
data.Append("<displayNum>").Append(displayNum).Append("</displayNum>");
} if (playTimes != null)
{
data.Append("<playTimes>").Append(playTimes).Append("</playTimes>");
} if (respUrl != null)
{
data.Append("<respUrl>").Append(respUrl).Append("</respUrl>");
} data.Append("</VoiceVerify>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"to\":\"").Append(to).Append("\"");
data.Append(",\"appId\":\"").Append(m_appId).Append("\"");
data.Append(",\"verifyCode\":\"").Append(verifyCode).Append("\""); if (displayNum != null)
{
data.Append(",\"displayNum\":\"").Append(displayNum).Append("\"");
} if (playTimes != null)
{
data.Append(",\"playTimes\":\"").Append(playTimes).Append("\"");
} if (respUrl != null)
{
data.Append(",\"respUrl\":\"").Append(respUrl).Append("\"");
} data.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("VoiceVerify requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("VoiceVerify responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else if (item.Name == "VoiceVerify")
{
Dictionary<string, object> retData = new Dictionary<string, object>();
foreach (XmlNode subItem in item.ChildNodes)
{
retData.Add(subItem.Name, subItem.InnerText);
}
//responseResult["data"] = new Dictionary<string, object> { { item.Name, retData } };
Dictionary<string, object> data1 = new Dictionary<string, object>();
data1.Add(item.Name, retData);
responseResult["data"] = data1;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// IVR外呼 暂不支持json格式
/// </summary>
/// <param name="number">待呼叫号码</param>
/// <param name="userdata">可选字段 用户数据,在<startservice>通知中返回,只允许填写数字字符</param>
/// <param name="record">可选字段 是否录音,可填项为true和false,默认值为false不录音</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> IvrDial(string number, string userdata, string record)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (number == null)
{
throw new ArgumentNullException("number");
} try
{
string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/ivr/dial?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("IvrDial url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST";
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder(); data.Append("<?xml version='1.0' encoding='utf-8'?><Request>");
data.Append("<Appid>").Append(m_appId).Append("</Appid>");
data.Append("<Dial ");
data.Append("number=\"" + number + "\"");
if (userdata != null)
{
data.Append(" userdata=\"" + userdata + "\"");
} if (record != null && record=="true")
{
data.Append(" record=\"true\"");
} data.Append("></Dial>");
data.Append("</Request>"); byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("IvrDial requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("IvrDial responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} /// <summary>
/// 话单下载
/// </summary>
/// <param name="date">day 代表前一天的数据(从00:00 – 23:59);week代表前一周的数据(周一 到周日);month表示上一个月的数据(上个月表示当前月减1,如果今天是4月10号,则查询结果是3月份的数据)</param>
/// <param name="keywords">客户的查询条件,由客户自行定义并提供给云通讯平台。默认不填忽略此参数</param>
/// <exception cref="ArgumentNullException">参数不能为空</exception>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public Dictionary<string, object> BillRecords(string date, string keywords)
{
Dictionary<string, object> initError = paramCheckRest();
if (initError != null)
{
return initError;
}
initError = paramCheckMainAccount();
if (initError != null)
{
return initError;
}
initError = paramCheckAppId();
if (initError != null)
{
return initError;
} if (date == null)
{
throw new ArgumentNullException("date");
} try
{
string mydate = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容
string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + mydate);
string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/BillRecords?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr);
Uri address = new Uri(uriStr); WriteLog("BillRecords url = " + uriStr); // 创建网络请求
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
setCertificateValidationCallBack(); // 构建Head
request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8");
byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + mydate);
string authStr = Convert.ToBase64String(myByte);
request.Headers.Add("Authorization", authStr); // 构建Body
StringBuilder data = new StringBuilder();
if (m_bodyType == EBodyType.EType_XML)
{
request.Accept = "application/xml";
request.ContentType = "application/xml;charset=utf-8"; data.Append("<?xml version='1.0' encoding='utf-8'?><BillRecords>");
data.Append("<appId>").Append(m_appId).Append("</appId>");
data.Append("<date>").Append(date).Append("</date>"); if (keywords != null)
{
data.Append("<keywords>").Append(keywords).Append("</keywords>");
} data.Append("</BillRecords>");
}
else
{
request.Accept = "application/json";
request.ContentType = "application/json;charset=utf-8"; data.Append("{");
data.Append("\"appId\":\"").Append(m_appId).Append("\"");
data.Append(",\"date\":\"").Append(date).Append("\""); if (keywords != null)
{
data.Append(",\"keywords\":\"").Append(keywords).Append("\"");
}
data.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("BillRecords requestBody = " + data.ToString()); // 开始请求
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, , byteData.Length);
} // 获取请求
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseStr = reader.ReadToEnd(); WriteLog("BillRecords responseBody = " + responseStr); if (responseStr != null && responseStr.Length > )
{
//Dictionary<string, object> responseResult = new Dictionary<string, object> { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } };
Dictionary<string, object> responseResult = new Dictionary<string, object>();
responseResult.Add("statusCode", "");
responseResult.Add("statusMsg", "成功");
responseResult.Add("data", null);
Dictionary<string, object> retData = new Dictionary<string, object>(); if (m_bodyType == EBodyType.EType_XML)
{
XmlDocument resultXml = new XmlDocument();
resultXml.LoadXml(responseStr);
XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes;
foreach (XmlNode item in nodeList)
{
if (item.Name == "statusCode")
{
responseResult["statusCode"] = item.InnerText;
}
else if (item.Name == "statusMsg")
{
responseResult["statusMsg"] = item.InnerText;
}
else
{
retData.Add(item.Name, item.InnerText);
}
}
}
else
{
responseResult.Clear();
responseResult["resposeBody"] = responseStr;
} if (retData.Count > )
{
responseResult["data"] = retData;
}
return responseResult;
}
//return new Dictionary<string, object> { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", );
data2.Add("statusMsg", "无返回");
data2.Add("data", null);
return data2;
}
}
catch (Exception e)
{
throw e;
}
} #region MD5 和 https交互函数定义 private void WriteLog(string log)
{
if (m_isWriteLog)
{
string strFilePath = GetLogPath();
System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now.ToString() + "\t" + log);
sw.Close();
fs.Close();
}
} /// <summary>
/// 检查服务器地址信息
/// </summary>
/// <returns></returns>
private Dictionary<string, object> paramCheckRest()
{
int statusCode = ;
string statusMsg = null; if (m_restAddress == null)
{
statusCode = ;
statusMsg = "IP空";
}
else if (m_restPort == null)
{
statusCode = ;
statusMsg = "端口错误";
} if (statusCode != )
{
//return new Dictionary<string, object> { { "statusCode", statusCode + "" }, { "statusMsg", statusMsg }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", statusCode + "");
data2.Add("statusMsg", statusMsg);
data2.Add("data", null);
return data2;
} return null;
} /// <summary>
/// 检查主帐号信息
/// </summary>
/// <returns></returns>
private Dictionary<string, object> paramCheckMainAccount()
{
int statusCode = ;
string statusMsg = null; if (m_mainAccount == null)
{
statusCode = ;
statusMsg = "主帐号空";
}
else if (m_mainToken == null)
{
statusCode = ;
statusMsg = "主帐号令牌空";
} if (statusCode != )
{
//return new Dictionary<string, object> { { "statusCode", statusCode + "" }, { "statusMsg", statusMsg }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", statusCode + "");
data2.Add("statusMsg", statusMsg);
data2.Add("data", null);
return data2;
} return null;
} /// <summary>
/// 检查子帐号信息
/// </summary>
/// <returns></returns>
private Dictionary<string, object> paramCheckSunAccount()
{
int statusCode = ;
string statusMsg = null; if (m_subAccount == null)
{
statusCode = ;
statusMsg = "子帐号空";
}
else if (m_subToken == null)
{
statusCode = ;
statusMsg = "子帐号令牌空";
}
else if (m_voipAccount == null)
{
statusCode = ;
statusMsg = "VoIP帐号空";
}
else if (m_voipPwd == null)
{
statusCode = ;
statusMsg = "VoIP密码空";
} if (statusCode != )
{
//return new Dictionary<string, object> { { "statusCode", statusCode+"" }, { "statusMsg", statusMsg }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", statusCode + "");
data2.Add("statusMsg", statusMsg);
data2.Add("data", null);
return data2;
} return null;
} /// <summary>
/// 检查应用ID
/// </summary>
/// <returns></returns>
private Dictionary<string, object> paramCheckAppId()
{
if (m_appId == null)
{
//return new Dictionary<string, object> { { "statusCode", 172012 + "" }, { "statusMsg", "应用ID为空" }, { "data", null } };
Dictionary<string, object> data2 = new Dictionary<string, object>();
data2.Add("statusCode", + "");
data2.Add("statusMsg", "应用ID为空");
data2.Add("data", null);
return data2;
} return null;
} /// <summary>
/// MD5加密
/// </summary>
/// <param name="source">原内容</param>
/// <returns>加密后内容</returns>
public static string MD5Encrypt(string source)
{
// Create a new instance of the MD5CryptoServiceProvider object.
System.Security.Cryptography.MD5 md5Hasher = System.Security.Cryptography.MD5.Create(); // Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(source)); // Create a new Stringbuilder to collect the bytes and create a string.
StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data and format each one as a hexadecimal string.
for (int i = ; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("X2"));
} // Return the hexadecimal string.
return sBuilder.ToString();
} /// <summary>
/// 设置服务器证书验证回调
/// </summary>
public void setCertificateValidationCallBack()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = CertificateValidationResult;
} /// <summary>
/// 证书验证回调函数
/// </summary>
/// <param name="obj"></param>
/// <param name="cer"></param>
/// <param name="chain"></param>
/// <param name="error"></param>
/// <returns></returns>
public bool CertificateValidationResult(object obj, System.Security.Cryptography.X509Certificates.X509Certificate cer, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
#endregion
}
}
Asp.Net发送手机验证码的更多相关文章
- asp.net限时发送手机验证码
html代码 <p> <strong>手机验证码:</strong> <asp:TextBox ID="code" runat=" ...
- C#发送手机验证码
C#发送手机验证码,平台有很多,我就说说其中的1个平台 测试环境:.net2.0 测试效果:速度还可以,10秒内接收短信 1.去http://www.yuntongxun.com注册,会送8元测试金额 ...
- django 发送手机验证码
一.流程分析: 1.用户在项目前端,输入手机号,然后点击[获取验证码],将手机号发到post到后台. 2.后台验证手机号是否合法,是否已被占用,如果通过验证,则生成验证码,并通过运行脚本,让短信运营商 ...
- C# WinForm 使用SMS接口发送手机验证码+图形验证码+IP限制
https://blog.csdn.net/IT_xiao_guang_guang/article/details/104299983 前言 1.发送手机验证码用的是网建的SMS接口(http:/ ...
- Java实现发送手机验证码功能(短信+语音)
利用第三方平台可以实现发送手机短信验证码和语音验证码的功能,本文使用框架是struts2+spring+hibernate,现就action层给出核心代码功能. public class Verify ...
- flask+阿里云短信服务实现注册发送手机验证码
效果图: 该效果主要讲解实现通过调用阿里云的SDK实现发送注册验证码短信(阿里云短信付费使用) 购买阿里云短信服务 购买链接:https://www.aliyun.com/product/sms 1. ...
- [.NET开发] C#实现发送手机验证码功能
之前不怎么了解这个,一直以为做起来很复杂. 直到前两天公司要求要做这个功能. 做了之后才发现 这不过就是一个POST请求就能实现的东西.现在给大家分享一下,有不足之处还请多多指教. 废话不多说 直接上 ...
- iOS --发送手机验证码收不到手机验证码
方法一:使用受信任设备上显示的验证码. 如果您的受信任设备是iOS 9 及以上系统时,则验证码将自动显示在受信任设备上.此时你信任的设备上会弹出你在某地登录ID位置的小地图,有一个选择允许与不允许登录 ...
- php 发送手机验证码
嗯哼,做为一个好的程序猿,一定要给顾客爸爸剁手的时候,充分的告诉他,你剁完手了,所以不只有邮件通知还要有手机短信的通知,今天就来写一下php发送验证码 1.首先我就写了几个个方法,因为配置在后台,直接 ...
随机推荐
- webDriver.Close() 和 webDriver.Quit() 、webDriver.Dispose() 的区别
1. webDriver.Close() - Close the browser window that the driver has focus of //关闭当前焦点所在的窗口2. webDriv ...
- springAOP记录用户操作日志
项目已经开发完成,需要加用户操作日志,如果返回去加也不太现实,所以使用springAOP来完成比较合适. 注解工具类: @Retention(RetentionPolicy.RUNTIME) @Tar ...
- MYSQL-innodb性能优化几个点
MYSQL-innodb性能优化几个点 数据库常用参数 MYSQL数据库的参数配置一般在my.ini配置(部分参数也可以用set global 参数名=值 做临时调整,重启后失效),配置完后需要重启 ...
- uploadify.js参数说明(转)
一.属性 属性名称 默认值 说明 auto true 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 . buttonClass ” 按钮样式 buttonCursor ‘ ...
- Intellij Idea免费激活方法
填入下面的license server: http://intellij.mandroid.cn/http://idea.imsxm.com/http://idea.iteblog.com/key.p ...
- 巧用linux服务器的/dev/shm/
巧用linux服务器的/dev/shm/,如果合理使用,可以避开磁盘IO不给力,提高网站访问速度. 首先让我们认识一下,什么是tmpfs和/dev/shm/? tmpfs是Linux/Unix系统上的 ...
- MFC添加自定义窗口消息
原文链接: http://www.cnblogs.com/smartvessel/archive/2011/07/18/2109472.html 1. 在头文件stdafx.h中增加一个自定义消息宏 ...
- Springboot使用junit
1. 首先要下载配套的spring-boot-starter-test包,注意版本要对应. compile("org.springframework.boot:spring-boot-sta ...
- golang包time用法详解
在我们编程过程中,经常会用到与时间相关的各种务需求,下面来介绍 golang 中有关时间的一些基本用法,我们从 time 的几种 type 来开始介绍. 时间可分为时间点与时间段,golang 也不例 ...
- Hibernate 连接访问多个数据库(含访问不同数据库的相同表)(转)
利用hibernate访问不同数据库中的不同表或不同数据库中的相同表. 本人在开发过程中的解决方案,希望大家交流.一般用myEclipse工具会自动生成Hibernate的相关文件,大致有下面几类: ...