阿里云短信
发送短信验证码是现在日常生活中很常见的事务,但相信很多人都只是接受过验证码,并不知道验证码的生成过程,也不知道如何自己创建一个验证码。会简单介绍如何通过阿里云来创建一个验证码短信。
一、首先打开阿里云官网
官网:https://www.aliyun.com/
二、开通阿里云短信服务
开通后五个学习任务,自行完成,可随意填写
三、完成学习后,获取AccessKey
鼠标点击右上角的头像
点击进去后,直接创建key,记录好自己key,后面需要用到
四、简单入门
点击左边导航栏,选择快速学习和测试,如下选择
点击调用之后可以看到如下
点击SDK实例
可以自行选择需要的语言。
点击右上角SDK信息,里面有需要的依赖坐标。
给自己的项目导入坐标后,编写代码
1.首先创建一个AliYunConfig类
package com.kk.user.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AliYunSmsConfig {
@Value("${aliyun.accessKey.id}")
private String accessKeyId;
@Value("${aliyun.accessKey.secret}")
private String accessKeySecret;
@Value("${aliyun.dysms.endpoint}")
private String endpoint;
/**
* 使用AK&SK初始化账号Client
*/
@Bean
public com.aliyun.dysmsapi20170525.Client smsClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = endpoint;
return new com.aliyun.dysmsapi20170525.Client(config);
}
}
2.再编写业务实现
package com.kk.user.service.impl;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kk.redis.utils.RedisCache;
import com.kk.user.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.tools.jar.CommandLine;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
@Value("${aliyun.dysms.templateCode}")
private String templateCode;
@Value("${aliyun.dysms.sign}")
private String sign;
@Autowired
private RedisCache redisCache;
@Autowired
private Client smsClient;
@Override
public void registerSmsSend(String phone) {
String code = this.generateVerifyCode("MATH", 4);
try {
this.send(phone,code);
} catch (RuntimeException re){
throw new RuntimeException(re);
} catch (Exception e) {
e.printStackTrace();
}
redisCache.setCacheObject("USERS:REGISTER:VERIFY_CODE:"+phone, code, 30L, TimeUnit.MINUTES);
}
private void send(String phone,String code) throws Exception{
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setSignName(sign)
.setTemplateCode(templateCode)
.setPhoneNumbers(phone)
.setTemplateParam("{\"code\":\""+code+"\"}");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// 复制代码运行请自行打印 API 的返回值
SendSmsResponse sendSmsResponse = smsClient.sendSmsWithOptions(sendSmsRequest, runtime);
SendSmsResponseBody body = sendSmsResponse.getBody();
ObjectMapper objectMapper = new ObjectMapper();
String resJson = objectMapper.writeValueAsString(body);
log.info("[短信服务] 阿里云发送短信相应结果:",resJson);
if(!"ok".equalsIgnoreCase(body.code)){
throw new RuntimeException(body.message);
}
}
private String generateVerifyCode(String type, int len){
StringBuffer code = new StringBuffer();
if("MATH".equalsIgnoreCase(type)){
Random random = new Random();
for (int i = 0; i < len; i++) {
code.append(random.nextInt(10));
}
} else {
String uuid = UUID.randomUUID().toString().replaceAll("-","");
code = new StringBuffer(uuid.substring(0, len));
log.info("[验证码] 生成验证码 ====》 type={}, len={}, code={}",type,len,code);
}
return code.toString();
}
}
以上代码都是根据阿里云自己提供的实例修改
一下为阿里云实例
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;
import com.aliyun.tea.*;
public class Sample {
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(accessKeySecret);
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
public static void main(String[] args_) throws Exception {
java.util.List<String> args = java.util.Arrays.asList(args_);
// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用,仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
com.aliyun.dysmsapi20170525.Client client = Sample.createClient(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setSignName("阿里云短信测试")
.setTemplateCode("SMS_154950909")
.setPhoneNumbers("13558435832")
.setTemplateParam("{\"code\":\"1234\"}");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// 复制代码运行请自行打印 API 的返回值
client.sendSmsWithOptions(sendSmsRequest, runtime);
} catch (TeaException error) {
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 错误 message
System.out.println(error.getMessage());
// 诊断地址
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}