阿里云短信接口使用
接入
一.nuget下载
二.复制接口
1.这里要注意的是AccessKey ID和AccessKey Secret是需要在阿里云生成的,路径:头像=>AccessKey 管理=>创建
* * * ```
* @pa * @re */using CSRedis;
using Microsoft.AspNetCore.Mvc;
using SmartHotel.Domain.Dto;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Tea;
using Tea.Utils;
namespace SmartHotel.WebApi.Common
{
public class PhoneCode
{
/**
* 使用AK&SK初始化账号Client
ram accessKeyId
* @param accessKeySecret
turn Client
* @throws Exception
public static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// 必填,您的 AccessKey ID
AccessKeyId = "LTAI5tFjGDns1sCGBQPasc6V",
// 必填,您的 AccessKey Secret
AccessKeySecret = "TQ1fQlTK6Q2lzjR4ES5UqgzgnJd5l7",
};
// 访问的域名
config.Endpoint = "dysmsapi.aliyuncs.com";
return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
}
```
public static Object Code(string args)
{
string codeStr = "";
for (int i = 0; i < 6; i++)
{
Random codes = new Random();
codeStr += codes.Next(0, 9);
}
AlibabaCloud.SDK.Dysmsapi20170525.Client client = CreateClient("LTAI5tFjGDns1sCGBQPasc6V", "TQ1fQlTK6Q2lzjR4ES5UqgzgnJd5l7");
AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
{
SignName = "胡卓个人博客",
TemplateCode = "SMS_267655261",
TemplateParam = "{\"code\":\"" + codeStr + "\"}",
PhoneNumbers = args,
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
//将数据保存进redis
var result = client.SendSmsWithOptions(sendSmsRequest, runtime);
if (result.StatusCode == 200 && result.Body.Message == "OK")
{
// 复制代码运行请自行打印 API 的返回值
return codeStr;
}
return result;
}
catch (TeaException error)
{
// 如有需要,请打印 error
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
return error.Message;
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// 如有需要,请打印 error
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
return error.Message;
}
}
}}
三.控制器调用(因为是静态方法,所以直接点出来)
/// <summary>
/// 短信测试
/// </summary>
/// <param name="phone"></param>
/// <param name="userId"></param>
/// <returns></returns>
[HttpGet]
public IActionResult SendInfor(string phone,int userId)
{
var code = _cSRedis.Get("code"+userId);
var apiResult = new ApiResult();
if (code!=null)
{
apiResult.Code = 500;
apiResult.Msg = "验证码已发送,请勿频繁操作";
return Ok(apiResult);
}
else
{
var result = PhoneCode.Code(phone);
_cSRedis.Set("code" + userId, result, 300);
apiResult.Code = 200;
apiResult.Msg = "验证码已发送";
return Ok(apiResult);
}
二:详细说明
在进行登录场景的时候,可以将生成的验证码存放在redis中,设置好生存时间,根据前端传进来的数据来进行对比,通过的话就可以进行下面的操作
标签:短信,apiResult,接口,return,阿里,error,using,new,AlibabaCloud From: https://www.cnblogs.com/Zhuo-Hu/p/17128013.html