使用springboot3集成阿里云的短信服务
登录阿里云(实名认证后)
登录成功后点击云市场
找到想要的服务(每个服务的代码略有不同)
点击详细
进去免费使用或者直购买
购买成功后去到阿里管控中心-工具于镜像
需要AppCode
AppCode是后面进行短信发送的认证
@Service
public class SmsServiceImpl implements SmsService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 发送短信
*
* @param phone
*/
@Override
public void sendCode(String phone) {
// TODO 生成随机4位验证码
String code = RandomStringUtils.randomNumeric(4);
System.out.println("code =============> " + code);
// TODO 存入Redis 15分钟内有效
stringRedisTemplate.opsForValue().set(phone, code, 15, TimeUnit.MINUTES);
// TODO 发送短信
sendMessage(phone, code);
}
// phone为要发送到短信的手机号 code为验证码
private void sendMessage(String phone, String code) {
String host = "https://dfsns.market.alicloudapi.com";
String path = "/data/send_sms";
String method = "POST";
String appcode = "自己的appcode 从阿里复制";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("content", "code:" + code);
bodys.put("template_id", "CST_ptdie100"); //注意,CST_ptdie100该模板ID仅为调试使用,调试结果为"status": "OK" ,即表示接口调用成功,然后联系客服报备自己的专属签名模板ID,以保证短信稳定下发
bodys.put("phone_number", phone);
try {
HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println("------->==="+response.toString());
//获取response的body
System.out.println("------>"+EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
创建工具类(也可以去阿里云下载)直接复制下面的代码即可
<