时间: 2019-05-16 来源: 华兴软通 本文链接:https://www.smshx.com/news_jishufangan3.html
在我们的工作生活中,使用各类网站、APP时,无论注册、支付,还是修改密码等情境下,都被要求获取短信验证码进行验证,那么验证码是如何发送的呢?接下来小编以华兴云短信为例,为大家详细介绍一下c#发送短信验证码的实现过程(同时实现防刷短信验证码机制,加密通信)。
一、实现思路
二、实现流程
1、注册账号
注册华兴云短信账号,填写基本信息,会有专人联系开户,并预送少量短信供测试使用。
2、下载接口
点击“产品中心”,进入产品页,选择对应的c#安全云短信接口及HTTPS版云短信接口文档下载;下载完毕文档如下:
3、配置参数变量
配置HttpsRequest.cs文件:
(1)将HttpsRequest.cs文件拷贝到项目中相应的位置,调用该类下的sendSms方法进行短信发送,及短信余额的查询getBalance方法。
(2)将sendSms方法中的注册码(regCode),密码(regPasswod),签名(signature),短信内容(content)修改成自己的信息。注意:短信内容可能需要报备。
(3)将目标手机号和内容根据代码里面的注释规则修改,在需要发送短信的地方调用sendSms这个方法就可以了。
4、报备短信模板
将待发内容提交至华兴客服工作人员,由工作人员进行黑名单、敏感词等检查,完成报备工作。
5、调用接口测试短信
完成前期的一系列准备工作,实际测试调用c#云短信接口的短信发送情况。
三、运行代码
查看HTTPS版云短信接口文档查看接口地址,参数说明及示例,调用下图代码配置好参数后,调用该方法测试发送短信,打印返回值,可查看文档中错误码
发送短信代码示例
图片验证码生成Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
//引用的命名空间
public class Handler : IHttpHandler, IRequiresSessionState
{
public string charSet = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y";
public void ProcessRequest (HttpContext context)
{
string validateCode = CreateRandomCode(4);
context.Session["ValidateCode"] = validateCode;
CreateImage(validateCode, context);
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
//string validateCode = CreateRandomCode(4);
//context.Session["ValidateCode"] = validateCode;
//CreateImage(validateCode, context);
}
public bool IsReusable
{
get
{
return false;
}
}
private string CreateRandomCode(int n)
{
string[] CharArray = charSet.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < n; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
} int t = rand.Next(CharArray.Length - 1);
if (temp == t)
{
return CreateRandomCode(n);
} temp = t;
randomCode += CharArray[t];
}
return randomCode;
}
//绘制验证码图片
private void CreateImage(string checkCode, HttpContext context)
{
int iwidth = (int)(checkCode.Length * 13);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 23);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold)); // 前景色
Brush b = new System.Drawing.SolidBrush(Color.Black); // 背景色
g.Clear(Color.White); // 填充文字
g.DrawString(checkCode, f, b, 0, 1); // 随机线条
Pen linePen = new Pen(Color.Gray, 0);
Random rand = new Random();
for (int i = 0; i < 5; i++)
{
int x1 = rand.Next(image.Width);
int y1 = rand.Next(image.Height);
int x2 = rand.Next(image.Width);
int y2 = rand.Next(image.Height);
g.DrawLine(linePen, x1, y1, x2, y2);
}
// 随机点
for (int i = 0; i < 30; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
image.SetPixel(x, y, Color.Gray);
}
// 边框
g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);
// 输出图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.Response.ClearContent();
context.Response.ContentType = "image/Jpeg";
context.Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
}
前端页面Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:Label ID="Label2" runat="server" Text="手机号"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" Height="32px"></asp:TextBox>
<br /><br />
<asp:Label ID="Label1" runat="server" Text="验证码"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Height="32px"></asp:TextBox>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="看不清 换一张" />
 
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Handler.ashx" />
</ContentTemplate>
</asp:UpdatePanel><br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="提交" />
</div>
</form>
</body>
</html>
后端验证图片验证码并发送短信代码Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.ToUpper().Trim() == Session["ValidateCode"].ToString().ToUpper().Trim())
{
string phonestr = TextBox2.Text.ToUpper().Trim();
string regularphone = @"^((13[0-9])|(14[579])|(15([012356789]))|(166)|(17[0135678])|(18[0-9])|(19[89]))\d{8}$";
Regex tReg = new Regex(regularphone);
if (tReg.IsMatch(phonestr))
{
//发送短信验证码
string url = "https://www.stongnet.com/sdkhttp/sendsms.aspx";
string regCode = "101100-WEB-HUAX-111111"; // 华兴软通注册码,请在这里填写您从客服那得到的注册码
string regPasswod = "11111111"; // 华兴软通注册码对应的密码,请在这里填写您从客服那得到的注册码
string sourceAdd = null; //子通道号(最长10位,可为空
string phone = phonestr; //手机号码(最多1000个),多个用英文逗号(,)隔开,不可为空
string signature = "【华兴】"; //签名
Random random = new Random();
//短信内容,请严格按照客服定义的模板生成短信内容,否则发送将失败
string content = "华兴软通$-_.+!*',^(αβ &@#%)验证码:" + (1000 + random.Next(9000)) + signature;
//content中含有空格,换行,中文等非ascii字符时,需要进行url编码,否则无法正确传输到服务器
content = HttpUtility.UrlEncode(content, Encoding.UTF8);
string param = "reg=" + regCode + "&pwd=" + regPasswod + "&sourceadd=" + sourceAdd + "&phone=" + phone + "&content=" + content;
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Method = "POST"; //指定允许数据发送的请求的一个协议方法
httpWebRequest.ContentType = "application/x-www-form-urlencoded"; //设置 ContentType 属性设置为适当的值
byte[] data = Encoding.UTF8.GetBytes(param);
using (Stream stream = httpWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length); //写入数据
}
WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse; //发起请求,得到返回对象
Stream dataStream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
string returnStr = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
webResponse.Close();
Response.Write("<script>alert('"+ returnStr +"')</script>");
}
else {
Response.Write("<script>alert('手机号错误!')</script>");
}
}
else
{
Response.Write("<script>alert('验证码不正确')</script>");
}
}
//看不清,换一张
protected void Button2_Click(object sender, EventArgs e)
{
//通过超链接传值来改变验证码图片
ImageButton1.ImageUrl = "Handler.ashx?id=" + new Random().Next(62);
}
}
按照示例可使用客服提供的注册号密码进行手机号短信验证码的发送测试,根据接口返回码和文档按自己的要求做进一步的功能开发。