当前位置:网站首页>Alibaba Cloud SMS Service Activation
Alibaba Cloud SMS Service Activation
2022-08-10 00:55:00 【llp1110】
一、Alibaba Cloud SMS service is activated
1.Aliyun SMS description
https://dysms.console.aliyun.com/overview
Log in to access Alibaba Cloud SMS service,You can see the general operation steps:
1.申请签名,如:【阿里云短信】
2.申请模板,如:【阿里云通信】您正在使用阿里云短信测试服务,体验验证码是:8888,如非本人操作,请忽略本短信!
3.系统设置,状态报告,审核通知,Upstream message reception, etc
4.发送短信
Alibaba Cloud provides a verification code sending test,We can test the effect by sending a text message to the mobile phone.
From the figure below, we can see that the messages sent by Alibaba Cloud are divided into domestic messages and international messages/There are two types of Hong Kong, Macao and Taiwan news,Both require a separate application for a signature template to send.This article has been distributed by domestic news as an example,International news is the same.
APIDemo
2.接入阿里云短信
2.1RAMAccess control to add users
AccessKeyand sub-usersAccessKey的区别在于AccessKeyThe account has all permissions and is a sub-userAccessKey需要手动添加.
Here I choose to add new users after the sub-account is entered as follows,We create this account and then use the interface to call the Ali SMS service to send SMS messages,So it must be checked hereOpenApI通用访问.
After the account is added successfully, we need to assign permissions to the sub-account,授权:AliyunDysmsFullAccess
开通账户之后,Be sure to record itAccessKeyId, AccessKeySecret便于后续使用
3.开通短信服务
3.1、开通
3.2、添加签名
3.3、添加模板
3.4、套餐
free.aliyun.com A free trial service is provided,If it is just to learn the transformation of the test at ordinary times,A free trial can be requested through this website
3.5快速学习
4.测试短信发送
https://next.api.aliyun.com/api/Dysmsapi/2017-05-25/SendSms?params=%7B%22RegionId%22%3A%22cn-hangzhou%22%2C%22PhoneNumbers%22%3A%2215023501990%22%2C%22SignName%22%3A%22%22%2C%22TemplateCode%22%3A%22%22%7D&sdkStyle=old
4.1、查找使用示例
4.2、测试短信发送
4.3、查看发送结果
短信服务->业务统计->发送记录查询
二、Alibaba Cloud SMS service development
In daily development, the SMS service is mainly used to obtain user verification codes、Already message notification and other services.Here, the user obtains the verification code through the mobile phone number to register the account as an example.
The verification code acquisition business process
1.基础配置
<!--阿里云短信-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
#阿里云短信
aliyun:
sms:
region-id: cn-hangzhou
key-id: 你的appId
key-secret: 你的appkey
template-code: 你的模板id
sign-name: 你的签名
1.This configuration class implementsInitializingBean接口实现afterPropertiesSet方法,当Spring容器将regionId、keyId、keySecretAfter parameter assignment,程序会调用afterPropertiesSetmethod we can assign the value of the configuration to the constant,This way we can pass the class name.Constant name to get the value.
2.With the configuration below we are inapplication.ymlIt can prompt us to configure the variables defined by the class itself,In this way, we can first define the configuration class before writingapplication.yml中的配置
配置类
@Data
@Component
@ConfigurationProperties(value = "aliyun.sms")
public class SmsProperties implements InitializingBean {
private String regionId;
private String keyId;
private String keySecret;
private String templateCode;
private String signName;
public static String REGION_Id;
public static String KEY_ID;
public static String KEY_SECRET;
public static String TEMPLATE_CODE;
public static String SIGN_NAME;
//当私有成员被赋值后,此方法自动被调用,从而初始化常量
@Override
public void afterPropertiesSet() throws Exception {
REGION_Id = regionId;
KEY_ID = keyId;
KEY_SECRET = keySecret;
TEMPLATE_CODE = templateCode;
SIGN_NAME = signName;
}
}
IdeaThe following error message is reported(不影响程序的编译和运行):
解决方案参考文档:
controller层
@ApiOperation("获取验证码")
@GetMapping("/send/{mobile}")
public R send(@ApiParam(value = "手机号码", required = true)
@PathVariable String mobile) {
//手机号码不能为空
Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
//手机号码是否合法
Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
//Whether the phone number has been registered
boolean result = coreUserInfoClient.checkMobile(mobile);
Assert.isTrue(result==false,ResponseEnum.MOBILE_EXIST_ERROR);
//生成验证码
Map<String, Object> map = new HashMap<>();
String code = RandomUtils.getFourBitRandom();
log.info("验证码:{}",code);
map.put("code", code);
//发送阿里云短信验证码
smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);
//发送短信验证码
// rlySmsService.send(mobile, RLYSmsProperties.TEMPLATE_ID, map);
//将验证码存入redis中
redisTemplate.opsForValue().set("srb:mms:code:" + mobile, code);
return R.ok().message("获取验证码成功").data("code",code);
}
service层
The code for sending text messages is basically the samedemo中拷贝出来,We only need to define a few variables in the SMS template.
@Override
public void send(String mobile, String templateCode, Map<String, Object> param) {
//创建远程连接客户端对象
DefaultProfile profile = DefaultProfile.getProfile(
SmsProperties.REGION_Id,
SmsProperties.KEY_ID,
SmsProperties.KEY_SECRET);
IAcsClient client = new DefaultAcsClient(profile);
//创建远程连接的请求参数
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", SmsProperties.REGION_Id);
request.putQueryParameter("PhoneNumbers", mobile);
request.putQueryParameter("SignName", SmsProperties.SIGN_NAME);
request.putQueryParameter("TemplateCode", templateCode);
Gson gson = new Gson();
String json = gson.toJson(param);
request.putQueryParameter("TemplateParam", json);
try {
//使用客户端对象携带请求对象发送请求并得到响应结果
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
//ALIYUN_RESPONSE_FAIL(-501, "阿里云响应失败"),
Assert.isTrue(success, ResponseEnum.ALIYUN_RESPONSE_FAIL);
String data = response.getData();
HashMap<String, String> resultMap = gson.fromJson(data, HashMap.class);
String code = resultMap.get("Code");
String message = resultMap.get("Message");
log.info("阿里云短信发送响应结果:");
log.info("code:" + code);
log.info("message:" + message);
//ALIYUN_SMS_LIMIT_CONTROL_ERROR(-502, "短信发送过于频繁"),//业务限流
Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
//ALIYUN_SMS_ERROR(-503, "短信发送失败"),//其他失败
Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);
} catch (ServerException e) {
log.error("阿里云短信发送SDK调用失败:");
log.error("ErrorCode=" + e.getErrCode());
log.error("ErrorMessage=" + e.getErrMsg());
throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
} catch (ClientException e) {
log.error("阿里云短信发送SDK调用失败:");
log.error("ErrorCode=" + e.getErrCode());
log.error("ErrorMessage=" + e.getErrMsg());
throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
}
}
2. 4-6Bit random generator class
/** * Generate four and six digit random numbers */
public class RandomUtils {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
private static final DecimalFormat sixdf = new DecimalFormat("000000");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
/** * 给定数组,抽取n个数据 * @param list * @param n * @return */
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
// 生成随机数字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 从HashMap导入数组
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 遍历数组并打印数据
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
边栏推荐
猜你喜欢
随机推荐
Snap: 322. Change of Change
【接口测试】requests 库请求体字符串解码
61.【快速排序法详解】
金仓数据库 KingbaseGIS 使用手册(6.2. 管理函数)
外包的水有多深?腾讯15k的外包测试岗能去吗?
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
What are the Shenzhen fortress machine manufacturers?Which one do you recommend?
国内BI厂商一览
ALV报表总结2022.8.9
带着昇腾去旅行:一日看尽金陵城里的AI胜景
力扣:474.一和零
干货!迈向鲁棒的测试时间适应
拼多多店铺运营不得不知的留个运营小知识
leetcode 20. Valid Parentheses 有效的括号(中等)
Forbidden (CSRF token missing or incorrect.): /
【哲理】事教人
【渗透工具】浏览器数据导出工具
IT传奇人物菲尔德的转型经验教训及给CIO的建议
【SSL集训DAY3】控制棋盘【二分图匹配】
ECCV 2022 | 微软开源TinyViT :搞定小模型的预训练能力