webapi 用腾讯云手机短信验证码

 #region 验证码相关
public class SmsSDK
{ #region 短信发送的必要参数
/// <summary>
/// appId
/// </summary>
private static int appId =自己的; /// <summary>
/// appKey
/// </summary>
private static string appKey = "自己的"; /// <summary>
/// 短信模板ID
/// </summary>
private static int tmplateId =自己的; #endregion #region 接收验证码的手机号
/// <summary>
/// 接受手机号
/// </summary>
private static string phoneNumber = "";
#endregion #region 获取验证码
/// <summary>
/// 获取验证码
/// </summary>
/// <param name="args"></param>
/// <param name="phone">手机号</param>
/// <returns></returns>
public bool GetMain(string phone)
{
var tel = phone;
phoneNumber = tel;
SmsSingleSenderResult singleResult;
List<string> templParams = new List<string>();
SmsSingleSender singleSender = new SmsSingleSender(appId, appKey);
//获取随机码
var val = new SmsSenderUtil().GetRandom().ToString();
SixNums = val; templParams.Add(val);
templParams.Add("");
singleResult = singleSender.SendWithParam(phoneNumber, tmplateId, templParams);
if (singleResult.result == )
{
return true;
}
return false; }
#endregion
 #region 判断验证码
/// <summary>
/// 随机码
/// </summary>
private static string SixNums = ""; /// <summary>
/// 判断验证码
/// </summary>
/// <param name="IfgCode">返回填写的验证码</param>
/// <returns></returns>
public bool JudgeIdentifyingCode(string IfgCode)
{
if (SixNums != IfgCode)
{
return false;
}
return true;
}
#endregion
}
#endregion #region 腾讯云配置
#region 短信类型枚举
/// <summary>
/// 短信类型枚举
/// </summary>
public enum SmsType
{
普通短信 = ,
营销短信 =
}
#endregion #region 短信单发
/// <summary>
/// 单发
/// </summary>
class SmsSingleSender
{
#region 变量
/// <summary>
/// appId
/// </summary>
private int appId;
/// <summary>
/// appkey
/// </summary>
private string appkey;
/// <summary>
/// url
/// </summary>
private string url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";
/// <summary>
/// util
/// </summary>
private SmsSenderUtil util = new SmsSenderUtil();
#endregion #region 构造
/// <summary>
/// 构造函数
/// </summary>
/// <param name="sdkappid"></param>
/// <param name="appkey"></param>
public SmsSingleSender(int sdkappid, string appkey)
{
this.appId = sdkappid;
this.appkey = appkey;
}
#endregion #region 指定模板单发
/// <summary>
/// 指定模板单发
/// </summary>
/// <param name="phoneNumber">不带国家码的手机号</param>
/// <param name="templId">模板 id</param>
/// <param name="templParams">模板参数列表,如模板 {1}...{2}...{3},那么需要带三个参数</param>
/// <param name="sign">短信签名,如果使用默认签名,该字段可缺省</param>
/// <param name="extend">扩展码,可填空</param>
/// <param name="ext">服务端原样返回的参数,可填空</param>
/// <returns>SmsSingleSenderResult</returns>
public SmsSingleSenderResult SendWithParam(string phoneNumber, int templId, List<string> templParams, string sign= "", string extend = "", string ext = "")
{
long random = util.GetRandom();
long curTime = util.GetCurTime();
// 按照协议组织 post 请求包体
JObject tel = new JObject();
tel.Add("nationcode", SmsSenderUtil.nationCode);
tel.Add("mobile", phoneNumber);
JObject data = new JObject();
data.Add("tel", tel);
data.Add("sig", util.CalculateSigForTempl(appkey, random, curTime, phoneNumber));
data.Add("tpl_id", templId);
data.Add("params", util.SmsParamsToJSONArray(templParams));
data.Add("sign", sign);
data.Add("time", curTime);
data.Add("extend", extend);
data.Add("ext", ext);
string wholeUrl = url + "?sdkappid=" + appId + "&random=" + random;
HttpWebRequest request = util.GetPostHttpConn(wholeUrl);
byte[] requestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
request.ContentLength = requestData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestData, , requestData.Length);
requestStream.Close();
// 接收返回包
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string responseStr = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
SmsSingleSenderResult result;
if (HttpStatusCode.OK == response.StatusCode)
{
result = util.ResponseStrToSingleSenderResult(responseStr);
}
else
{
result = new SmsSingleSenderResult();
result.result = -;
result.errmsg = "http error " + response.StatusCode + " " + responseStr;
}
return result;
}
#endregion
}
#endregion
 #region 单发结果
/// <summary>
/// 单发结果
/// </summary>
public class SmsSingleSenderResult
{
/// <summary>
/// 错误码,0 表示成功(计费依据),非 0 表示失败
/// </summary>
public int result { set; get; }
/// <summary>
/// 错误消息,result 非 0 时的具体错误信息
/// </summary>
public string errmsg { set; get; }
/// <summary>
/// 用户的 session 内容,腾讯 server 回包中会原样返回
/// </summary>
public string ext { set; get; }
/// <summary>
/// 本次发送标识 id,标识一次短信下发记录
/// </summary>
public string sid { set; get; }
/// <summary>
/// 短信计费的条数
/// </summary>
public int fee { set; get; }
/// <summary>
/// ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("SmsSingleSenderResult\nresult {0}\nerrMsg {1}\next {2}\nsid {3}\nfee {4}", result, errmsg, ext, sid, fee);
}
}
#endregion #region 公共类
/// <summary>
/// 公共类
/// </summary>
class SmsSenderUtil
{
/// <summary>
/// 国家码
/// </summary>
public static string nationCode = "";
/// <summary>
/// 随机数生成器
/// </summary>
private Random random = new Random(); #region GetPostHttpConn
/// <summary>
/// GetPostHttpConn
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public HttpWebRequest GetPostHttpConn(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
return request;
}
#endregion
 #region 生成随机数
/// <summary>
/// 生成随机数
/// </summary>
/// <returns></returns>
public long GetRandom()
{
return random.Next() % + ;
}
#endregion #region 获取请求发起时间
/// <summary>
/// 获取请求发起时间,
/// unix 时间戳(单位:秒),如果和系统时间相差超过 10 分钟则会返回失败
/// </summary>
/// <returns></returns>
public long GetCurTime()
{
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(, , ))).TotalSeconds;
return unixTimestamp;
}
#endregion #region 字符串转SHA256
/// <summary>
/// 字符串转SHA256
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string StrToHash(string str)
{
SHA256 sha256 = SHA256Managed.Create();
byte[] resultByteArray = sha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
return ByteArrayToHex(resultByteArray);
} /// <summary>
/// 将二进制的数值转换为 16 进制字符串,如 "abc" => "616263"
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
private static string ByteArrayToHex(byte[] byteArray)
{
string returnStr = "";
if (byteArray != null)
{
for (int i = ; i < byteArray.Length; i++)
{
returnStr += byteArray[i].ToString("x2");
}
}
return returnStr;
}
#endregion #region 将单发回包解析成结果对象
/// <summary>
/// 将单发回包解析成结果对象
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public SmsSingleSenderResult ResponseStrToSingleSenderResult(string str)
{
SmsSingleSenderResult result = JsonConvert.DeserializeObject<SmsSingleSenderResult>(str);
return result;
}
#endregion #region List<string>转JArray
/// <summary>
/// List<string>转JArray
/// </summary>
/// <param name="templParams"></param>
/// <returns></returns>
public JArray SmsParamsToJSONArray(List<string> templParams)
{
JArray smsParams = new JArray();
foreach (string templParamsElement in templParams)
{
smsParams.Add(templParamsElement);
}
return smsParams;
}
#endregion #region PhoneNumbersToJSONArray
/// <summary>
/// PhoneNumbersToJSONArray
/// </summary>
/// <param name="nationCode"></param>
/// <param name="phoneNumbers"></param>
/// <returns></returns>
public JArray PhoneNumbersToJSONArray(string nationCode, List<string> phoneNumbers)
{
JArray tel = new JArray();
int i = ;
do
{
JObject telElement = new JObject();
telElement.Add("nationcode", nationCode);
telElement.Add("mobile", phoneNumbers.ElementAt(i));
tel.Add(telElement);
} while (++i < phoneNumbers.Count);
return tel;
}
#endregion #region 计算App凭证
/*
"sig" 字段根据公式 sha256(appkey=$appkey&random=$random&time=$time&mobile=$mobile)生成
*/
public string CalculateSigForTempl(string appkey, long random, long curTime, List<string> phoneNumbers)
{
string phoneNumbersString = phoneNumbers.ElementAt();
for (int i = ; i < phoneNumbers.Count; i++)
{
phoneNumbersString += "," + phoneNumbers.ElementAt(i);
}
return StrToHash(String.Format(
"appkey={0}&random={1}&time={2}&mobile={3}",
appkey, random, curTime, phoneNumbersString));
} public string CalculateSigForTempl(string appkey, long random, long curTime, string phoneNumber)
{
List<string> phoneNumbers = new List<string>();
phoneNumbers.Add(phoneNumber);
return CalculateSigForTempl(appkey, random, curTime, phoneNumbers);
} public string CalculateSig(string appkey, long random, long curTime, List<string> phoneNumbers)
{
string phoneNumbersString = phoneNumbers.ElementAt();
for (int i = ; i < phoneNumbers.Count; i++)
{
phoneNumbersString += "," + phoneNumbers.ElementAt(i);
}
return StrToHash(String.Format(
"appkey={0}&random={1}&time={2}&mobile={3}",
appkey, random, curTime, phoneNumbersString));
}
#endregion
}
#endregion
#endregion

//使用时需要将配置里的内容换成自己的;

上一篇:Java中字符转int


下一篇:Java中char和String的相互转换