阿里云短信服务是基于 狂神说视频的总结,仅供个人学习和复习用。
七牛云短信服务是基于 世俗的大尾巴也熊的文章提取,仅供个人学习和复习用
阿里云短信服务
阿里云用户权限操作
- 登录阿里云,鼠标移到右上角头像找到AccessKey管理。
- 使用子用户AccessKey,创建用户组。
- 点击新建的用户组,选择权限管理—>添加权限—>添加管理短信服务(SMS)的权限—>确定。
- 创建用户,记得勾选上编程访问,一定要保留好AccessKeyID和密码。然后在用户组中添加组成员。
注意:ID和密码需要保管好,当泄露出去时记得立马停用删除与跟换。
开通阿里云短信服务
前提
:短信服务需要扣费,你需要在你的阿里云账号中先进行充值。
1.打开消息服务
2.选择国内消息,开通服务,点击模板管理—->添加模板。(建议先过一遍左边的快速学习)
3.添加签名,等待审核通过。(需要有正当理由)
4.查看帮助文档。
测试使用
导入Maven依赖
<!--导入javasdk-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<!--如果需要字符串处理导入json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<!--如果需要放入Redis内存中设置时间失效整合导入Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
测试代码
package com.zsky.helloworld;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
@SpringBootTest
class HelloworldApplicationTests {
@Test
void contextLoads() {
//连接阿里云
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "AccessKeyID的账号ID", "AccessKey的密码");
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("AddSmsSign");
//自定义的参数(手机号,验证码,签名,模板!)
request.putQueryParameter("PhoneNumbers", "需要发送到的手机号");
request.putQueryParameter("SignName", "你的签名");
request.putQueryParameter("TemplateCode", "模版CODE");
//构建一个短信验证码
HashMap<String,Object> map = new HashMap<>();
map.put("code",233333);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
通用模板
Server层接口
import java.util.Map;
public interface SendSms {
public boolean send(String phoneNum, String templateCode, Map<String,Object> code);
}
Server层实现类
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.zsky.helloworld.service.SendSms;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class SendSmsImpl implements SendSms {
@Override
public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
//连接阿里云
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "AccessKeyID的账号ID", "AccessKey的密码");
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("AddSmsSign");
//自定义的参数(手机号,验证码,签名,模板!)
request.putQueryParameter("PhoneNumbers", "phoneNum");
request.putQueryParameter("SignName", "你的签名");
request.putQueryParameter("TemplateCode", "templateCode");
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
Controller控制层
import com.zsky.helloworld.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@RestController
@CrossOrigin //跨域支持
public class SmsApiController {
@Autowired
private SendSms sendSms;
@Autowired
private RedisTemplate<String,String> redisTemplate;
@GetMapping("/send/{phone}")
public String code(@PathVariable("phone") String phone){
//调用发送方法,模拟真实业务(Redis)
String code = redisTemplate.opsForValue().get("phone");
if(!StringUtils.isEmpty(code)){
return phone + ":" + code + "已存在,还没有过期";
}
//生成验证码并存贮到redis中
code = UUID.randomUUID().toString().substring(0,4);
HashMap<String, Object> param = new HashMap<>();
param.put("code",code);
boolean isSend = sendSms.send(phone,"SMS_****",param);
if(isSend){
redisTemplate.opsForValue().set(phone,code,30, TimeUnit.SECONDS);
return phone + ":" + code + "发送成功!";
}else {
return "发送失败!";
}
}
}
七牛云短信服务
前提时您已实名注册七牛云并设置了AccessKeyID和密码
导入Maven依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
短信接口util
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import com.qiniu.util.Auth;
import com.whl.project.properties.GlobalProperites;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Slf4j
@Component
public class SendMessageUtil {
@Autowired
private GlobalProperites globalProperites;
/**
* 发送手机验证码
*/
public Boolean sendMessageCheck(String[] phone, Map<String, String> map){
String accessKey = "**********************";
String secretKey = "**********************";
Auth auth = Auth.create(accessKey, secretKey);
SmsManager smsManager = new SmsManager(auth);
try {
Response resp = smsManager.sendMessage(TemplateId, phone , map);
if(resp.statusCode == 200){
return true;
}else {
return false;
}
} catch (QiniuException e) {
log.info("发生短信异常 =======================" ,e);
}
return false;
}
}
这里resp.statusCode == 200是把调用短信返回的状态码取出来了,如果等于200,说明发送成功。你也可以直接查看返回的参数resp。
实现接口
/**
* 发送短信验证码
*/
@RequestMapping(value = "/api/sendValidCode", method = RequestMethod.POST)
public @ResponseBody
Response<Boolean> sendValidCode(@RequestParam("phone") String phone) throws Exception {
//获取验证码
code = UUID.randomUUID().toString().substring(0,4);
//存入redis
redisService.set(WhlConstants.Redis.MESSAGECODE_PHONE + phone, code , 60*3L);
Map<String , String> map = new HashMap<String , String>();
map.put("code",code);
Boolean rest = sendMessageUtil.sendMessageCheck(new String[]{phone},map);
return Response.buildSuccess(rest);
}