准備工作
- 阿里雲上申請短信服務
- 創建短信應用、簽名、短信模板並申請審核,如果審核不通過,接口是調不通的。
- 配置專門用來發短信的accessKeyId和 accessKeySecret
開始開發
下載安裝sdk
安裝這兩個SDK就可以了,下面就是寫代碼了 代碼來自官方 demo
using System;
using System.Collections.Generic;
using System.Text;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
namespace Application.SMS
{
public class SmsHelper
{
/// <summary>
/// 發送阿里雲短信
/// </summary>
/// <param name="mobile"></param>
/// <param name="templateCode"></param>
/// <param name="json"></param>
private static void SendAcs(string mobile, string templateCode, dynamic json, int ourid)
{
if (string.IsNullOrEmpty(mobile))
{
throw new Exception("mobile不能為空");
}
if (string.IsNullOrEmpty(templateCode))
{
throw new Exception("templateCode不能為空");
}
string product = "Dysmsapi";//短信API產品名稱(短信產品名固定,無需修改)
string domain = "dysmsapi.aliyuncs.com";//短信API產品域名(接口地址固定,無需修改)
string accessKeyId = "xxxxxxxxxx";//你的accessKeyId,參考本文檔步驟2
string accessKeySecret = "xxxxxxxxx";//你的accessKeySecret,參考本文檔步驟2
IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
//IAcsClient client = new DefaultAcsClient(profile);
// SingleSendSmsRequest request = new SingleSendSmsRequest();
//初始化ascClient,暫時不支持多region(請勿修改)
DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
try
{
//必填:待發送手機號。支持以逗號分隔的形式進行批量調用,批量上限為1000個手機號碼,批量調用相對於單條調用及時性稍有延遲,驗證碼類型的短信推薦使用單條調用的方式,發送國際/港澳台消息時,接收號碼格式為00+國際區號+號碼,如“0085200000000”
request.PhoneNumbers = mobile;
//必填:短信簽名-可在短信控制台中找到
request.SignName = "xxxxxx";
//必填:短信模板-可在短信控制台中找到,發送國際/港澳台消息時,請使用國際/港澳台短信模版
request.TemplateCode = templateCode;
//可選:模板中的變量替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為
request.TemplateParam = JsonHelper.ToJSON(json);// "{\"name\":\"Tom\",\"code\":\"123\"}";
//可選:outId為提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
request.OutId = ourid.ToString();// "yourOutId";
//請求失敗這里會拋ClientException異常
SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
if (sendSmsResponse.BizId == null)
throw new ApplicationException(sendSmsResponse.Message);
System.Console.WriteLine(sendSmsResponse.Message);
}
catch (ServerException ex)
{
throw new ApplicationException(ex.Message);
//System.Console.WriteLine("Hello World!");
}
catch (ClientException ex)
{
throw new ApplicationException(ex.Message);
//System.Console.WriteLine("Hello World!");
}
}
}
}