using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20190711;
using TencentCloud.Sms.V20190711.Models;
public class SMS
{
static Logger log = LogManager.GetCurrentClassLogger();
private static string secretId = "这里写腾讯云后台账号申请的secretId ,一串加密的";
private static string secretKey = "这里写腾讯云后台账号申请的secretKey,一串加密的";
private static string templateID = "申请的短信模板的ID,一串数字"
private static string companyName = "这里写公司名称";
private static string SdkAppid = "这里写腾讯云后台的SdkAppid ,一串数字";
public static string Send(string PhoneNumber, out string code, out string receive)
{
string data = "";
code = GenerateRandomCode(6);
try
{
Credential cred = new Credential
{
SecretId = secretId,
SecretKey = secretKey
};
ClientProfile clientProfile = new ClientProfile();
HttpProfile httpProfile = new HttpProfile();
httpProfile.Endpoint = ("sms.tencentcloudapi.com");
clientProfile.HttpProfile = httpProfile;
SmsClient client = new SmsClient(cred, "", clientProfile);
SendSmsRequest req = new SendSmsRequest();
req.PhoneNumberSet = new string[] { "+86" + PhoneNumber };
req.TemplateID = templateID;
req.Sign = companyName;
req.TemplateParamSet = new string[] { code };
req.SmsSdkAppid = SdkAppid;
SendSmsResponse resp = client.SendSmsSync(req);
string jsonResult = AbstractModel.ToJsonString(resp);
receive = jsonResult;
JObject jb = (JObject)JsonConvert.DeserializeObject(jsonResult);
data = jb["SendStatusSet"][0]["Code"].ToString().ToLower();
}
catch (Exception ex)
{
receive = "";
data = ex.Message;
string error = ex.Message;
log.Error("短信发送错误:" + ex.Message + "\r\n" + "详细错误:" + ex.ToString());
}
return data;
}
/// <summary>
/// 用GUID作种子生成理论上不重复的随机数作为验证码
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
private static string GenerateRandomCode(int length)
{
var result = new StringBuilder();
for (var i = 0; i < length; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
result.Append(r.Next(0, 10).ToString());
}
string code = result.ToString();
return code;
}
}
注意:验证码是要程序自己生成的,并作为参数传给,腾讯云短信api的,我这里设置了三个参数
PhoneNumber:手机号码,如果要发给多个,改为string数组即可。
code:out 传出生成的验证码,可以将手机号作为Key,手机号为value,存入缓存验证用户输入的验证码是否正确。
receive:out 传出参数 返回调用腾讯云API后返回的结果消息,有误异常等