c#手机发送短信汇总:1、.NET MVC 短信验证码过程/2、C#怎么实现手机短信发送功能

原文链接:1、https://blog.csdn.net/weixin_44481764/article/details/97941984

                  2、https://pythonjishu.com/cbmxvlotimcvekz/

最近接触到发送短信的功能,有多种方法实现,(第三方类、使用短信接口提供商的服务、)网上找到几个比较详细的例子,在此记录下。

1:创建一个项目用来调用第三方的类,右键Nuget添加第三方的引用类库 qcloudsms_csharp

2:把第三方的公共类放入到我们的项目里

using qcloudsms;
using qcloudsms_csharp.httpclient;
using qcloudsms_csharp.json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiShop.Remote
{
public class TenXunYunSMS
{
//appId
public int appId;
//appKey
public string appKey = "";
//短信模板ID
private int tmplateId = 379257;
//签名内容
private string smsSign = "7hhhcn";
/// <summary>
/// 验证码
/// </summary>
public int Code { get; set; }
/// <summary>
/// 发送验证码
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public void SetSMS(string phone)
{
Random random = new Random();
int code = random.Next(100000, 999999);
try
{
SmsSingleSender ssender = new SmsSingleSender(appId, appKey);
var result = ssender.sendWithParam("86", phone,
tmplateId, new[] { code.ToString() }, smsSign, "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
}
catch (JSONException ex)
{
throw;
}
catch (HTTPException ex)
{
throw;
}
catch (Exception ex)
{
throw;
}
Code = code;
}
}
}
3:创建一张短信发送记录表 

//信息记录表
public class SMSInfo
{
public int Id { get; set; }
public int Code { get; set; }
public Int64 TelPhone { get; set; }
//创建时间
public DateTime CreateTime { get; set; }
//短信过期时间
public DateTime ExpireTime { get; set; }
}
4:数据访问层写插入短信信息表方法

public class SMSInfoRepository
{
/// <summary>
/// 将验证码和电话保存至数据库
/// </summary>
/// <param name="sMSInfo"></param>
/// <returns></returns>
public int InsertSMSInfo(SMSInfo sMSInfo)
{
int result = -1;
string sql = @"insert into SMSInfo values(@Code, @TelPhone, @CreateTime, @ExpireTime)";
SqlParameter[] sqlParameter = {
new SqlParameter(){
DbType=DbType.Int32,
ParameterName="@Code",
Value=sMSInfo.Code
},
new SqlParameter(){
DbType=DbType.Int64,
ParameterName="@TelPhone",
Value=sMSInfo.TelPhone
},
new SqlParameter(){
DbType=DbType.DateTime,
ParameterName="@CreateTime",
Value=DateTime.Now
},
new SqlParameter(){
DbType=DbType.DateTime,
ParameterName="@ExpireTime",
Value=DateTime.Now.AddMinutes(5)
}
};
DBHelper dBHelper = new DBHelper();
result =dBHelper.ExcuteNoQuery(sql,sqlParameter);
return result;
}
/// <summary>
/// 查询电话和验证码是否正确
/// </summary>
/// <param name="sMSInfo"></param>
/// <returns></returns>
public int SelCodePhone(SMSInfo sMSInfo)
{
int result = -1;
string sql = @"select COUNT(1) from SMSInfo where Code=@Code and TelPhone=@TelPhone and ExpireTime>@ExpireTime";
SqlParameter[] sqlParameter = {
new SqlParameter(){
DbType=DbType.Int32,
ParameterName="@Code",
Value=sMSInfo.Code
},
new SqlParameter(){
DbType=DbType.Int64,
ParameterName="@TelPhone",
Value=sMSInfo.TelPhone
},
new SqlParameter(){
DbType=DbType.DateTime,
ParameterName="@ExpireTime",
Value=DateTime.Now
}
};
DBHelper dBHelper = new DBHelper();
result = dBHelper.ExecuteScalar(sql, sqlParameter);
return result;
}
}


5:业务层:先引用第三方项目,先调用第三方类,发送验证码,然后将验证码存储到短信信息对象,最后调用数据访问层的插入短信的方法。

public class SMSInfoSerivice
{
/// <summary>
/// 获取验证码同时将验证码保存至数据库
/// </summary>
/// <param name="phone"></param>
/// <returns></returns>
public bool GetCode(string phone)
{
//调用第三方类
TenXunYunSMS tenXunYunSMS;
try
{
tenXunYunSMS = new TenXunYunSMS();
tenXunYunSMS.appId = Convert.ToInt32(ConfigurationManager.AppSettings["appId"]);
tenXunYunSMS.appKey = ConfigurationManager.AppSettings["appKey"];
tenXunYunSMS.SetSMS(phone);
}
catch (Exception)
{

return false;
}
SMSInfoRepository sMSInfoRepository = new SMSInfoRepository();
//创建信息对象保存验证码和电话号码
SMSInfo sMSInfo = new SMSInfo();
//将验证码存储到短信信息对象
sMSInfo.Code = tenXunYunSMS.Code;
sMSInfo.TelPhone = Convert.ToInt64(phone);
//调用插入短信信息的方法 成功返回true
return sMSInfoRepository.InsertSMSInfo(sMSInfo)>0;
}
/// <summary>
/// 查询电话和验证码是否正确
/// </summary>
/// <param name="sMSInfo"></param>
/// <returns></returns>
public bool SelCodePhone(SMSInfo sMSInfo)
{
SMSInfoRepository sMSInfoRepository = new SMSInfoRepository();
return sMSInfoRepository.SelCodePhone(sMSInfo)>0;
}
}


6:控制器写一个JsonResult的发送验证码方法需要接收手机号 

public JsonResult GetCode(string phone)
{
Operate operate = new Operate();
SMSInfoSerivice sMSInfoSerivice = new SMSInfoSerivice();
operate.Success = sMSInfoSerivice.GetCode(phone);
return Json(operate);
}

7:控制器写一个JsonResult的校验验证码方法需要接收短信信息对象 

//点击注册时查询电话号码与短信验证码是否存在
public JsonResult SelCodePhone(SMSInfo sMSInfo)
{
Operate operate = new Operate();
SMSInfoSerivice sMSInfoSerivice = new SMSInfoSerivice();
operate.Success = sMSInfoSerivice.SelCodePhone(sMSInfo);
return Json(operate);
}

8:页面点击获取验证码按钮:先禁用按钮,然后ajax post提交到控制器对应的发送验证码方法,传入手机号,然后success处理返回的结果。

//点击获取验证
$("#GetCode").click(function () {
var tel = $("#tel").val();
$.ajax({
url: "/SMSCode/GetCode?phone=" + tel,
type: "post",
success: function (result) {
if (result.Success) {
alert("获取成功");
//调用短信验证计时器方法
IntervalSMS();
}
else {
alert("获取失败");
}
}
})
})

//短信验证计时器
function IntervalSMS() {

$("#GetCode").attr("disable", "disabled");
$("#GetCode").css("color", "red");

var time = 30;
$("#GetCode").val(time + " S后重新获取验证码");

var timer = setInterval(function () {
if (time > 0) {
time--;
$("#GetCode").val(time + " S后重新获取验证码");
}
else {
$("#GetCode").removeAttr("disable").css("color", "black");
$("#GetCode").val("重新获取验证码");
clearInterval(timer);
}
}, 1000)
}


9:点击注册按钮,写一个校验验证码的方法,校验通过之后才能注册。 

//注册按钮 查询记录 为true进行保存注册
$("#btnRe").click(function () {

if (ckname == true && ckphone == true && ckrepwd == true && ckpwd == true) {

var SMSInfo = {};
SMSInfo.TelPhone = $("#tel").val();
SMSInfo.Code = $("#yan").val();
$.ajax({
url: "/SMSCode/SelCodePhone",
type: "post",
data: SMSInfo,
success: function (result) {
if (result.Success) {
//点击注册时查询电话和验证码是否正确 正确则调用该方法进行注册
reg();
}
else {
alert("短信验证码不存在");
return;
}
}
})
}
else {
alert("信息验证未通过无法注册成功");
}


//点击注册时查询电话和验证码是否正确 正确则调用该方法进行注册
function reg() {
var userInfo = {};
userInfo.UserName = $("#username").val();
userInfo.UserPwd = $("#password").val();
userInfo.UserPhone = $("#tel").val();
$.ajax({
url: "/Register/SaveUserInfo",
data: userInfo,
type: "post",
success: function (result) {
if (result.Success) {
alert("注册成功");
}
else {
alert("注册失败");
}
}
})
}

 

2、C#怎么实现手机短信发送功能

为了实现C#语言中的手机短信发送功能,我们需要使用短信接口提供商的服务。以下是一些实现方法的步骤:

步骤一:选择一个短信接口提供商
首先,我们需要选择并注册一个短信接口提供商。常见的短信接口提供商有阿里云、腾讯云、云片等。注册后,我们可以得到一些必要的信息,例如接口地址、账号、密码。

步骤二:调用短信接口
接着,我们需要使用HTTP协议来调用短信接口。我们可以使用C#中的WebClient类来发送HTTP请求和接收HTTP响应。具体来说,使用WebClient类的UploadString方法,将短信接口的地址和必要的参数以POST方式发送到服务器,并获得服务器的响应。

下面是一个示例代码,使用阿里云短信接口实现发送短信:

using System.Net;

class AliyunSMS
{
public static void sendSms(string mobile, string message)
{
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;

string host = "https://dysmsapi.aliyuncs.com";
string path = "/";

string accessKeyId = "<your-access-key-id>";
string accessKeySecret = "<your-access-key-secret>";

string templateCode = "<your-template-code>";
string signName = "<your-sign-name>";

string queryParams = "Action=SendSms"
+ "&Format=JSON"
+ "&Version=2017-05-25"
+ "&AccessKeyId=" + accessKeyId
+ "&SignatureMethod=HMAC-SHA1"
+ "&SignatureNonce=" + Guid.NewGuid().ToString().Replace("-", "")
+ "&SignatureVersion=1.0"
+ "&Timestamp=" + System.Uri.EscapeDataString(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"))
+ "&RegionId=cn-hangzhou"
+ "&PhoneNumbers=" + mobile
+ "&SignName=" + System.Uri.EscapeDataString(signName)
+ "&TemplateCode=" + templateCode
+ "&TemplateParam={"code":"123456"}";

string signature = computeSignature(queryParams, accessKeySecret);

string requestUrl = host + path + "?" + queryParams + "&Signature=" + signature;
string response = client.UploadString(requestUrl, "");

Console.WriteLine(response);
}

private static string computeSignature(string stringToSign, string accessKeySecret)
{
string key = accessKeySecret + "&";
HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(key.ToCharArray()));
byte[] dataToSign = Encoding.UTF8.GetBytes(stringToSign.ToCharArray());
MemoryStream stream = new MemoryStream(dataToSign);
byte[] signatureBytes = hmac.ComputeHash(stream);
return Convert.ToBase64String(signatureBytes);
}
}
该代码中需要替换的是accessKeyId、accessKeySecret、templateCode和signName参数。替换成针对你的阿里云账号相应的参数。

该示例发送的短信模板包含一个变量"code",可以通过后台生成一个随机数来当做变量内容。发送后,阿里云会返回一个JSON格式的响应,其中包含了发送短信的状态和响应码等信息。

步骤三:解析服务器响应
最后,我们需要解析服务器返回的响应,以确定短信是否成功发送。

以下是一个示例代码,用于解析阿里云短信接口返回的JSON响应:

using Newtonsoft.Json;

class AliyunSMS
{
public static void sendSms(string mobile, string message)
{
// ...

string response = client.UploadString(requestUrl, "");

dynamic jsonResponse = JsonConvert.DeserializeObject(response);
string code = jsonResponse.Code;
string message = jsonResponse.Message;

if (code == "OK")
{
Console.WriteLine("发送成功");
}
else
{
Console.WriteLine("发送失败:" + message);
}
}
}
以上是使用阿里云短信接口实现发送短信的示例。不同的短信接口提供商需要根据其接口文档做出相应的调整。

posted @ 2023-12-19 15:59  yinghualeihenmei  阅读(202)  评论(0编辑  收藏  举报