【Java + Alibaba】阿里云手机短信服务整合

概要

阿里云官网操作

引入依赖

修改yml

配置类读取yml信息

控制层

业务层


概要

        在登录页面中,常见的就是注册账号密码然后登录。但是并不是什么项目都止步于此,对于如今现代化的科技技术中,手机登录与微信登录网址已经成了必备的登录手段。所以这篇文章我将会总结关于项目Web中如何做到阿里云的手机短信服务。具体步骤思想如下:

1、客户端会先输入手机号传给服务端

2、服务端将手机号和自己生成的验证码发送到阿里云

3、阿里云将这条信息发送给客户手机

4、客户再填入验证码发送到后端进行验证

5、验证码正确就传给客户端通过指令,否则就表示验证码错误。

6、客户端根据服务端传来的response.data进行辨别从而操作

注意:这篇我只总结了服务端的代码实现,并没有前端的代码。

阿里云官网操作

网址如下:阿里云企业应用中心-提供企业办公管理软件、工商财税等一站式服务

1、先进入到阿里云的短信服务

2、在国内消息中点击添加签名 填完那些信息即可 大致2个工作日内可以申请通过

这里需要注意一个信息是项目中需要的参数:签名名称

3、在国内消息中选中模块管理点击添加模块即可 大致1个工作日内可以申请通过

这里需要注意一个信息是项目中需要的参数:模板CODE

4、点击页面右上角个人中心的AccessKey管理

5、在AccessKey中点击创建

这里需要注意两个信息是项目中需要的参数:AccessKey ID 和 AccessKey Secret

6、以上的四个参数都拿到后呢 回到短信服务 -> 快速学习和测试 填入通过的签名和模块把自己的手机测试成功通过后,才能在项目中进行运用。

引入依赖

<!--阿里云的SMS短信服务依赖-->
<dependency>
	<groupId>com.aliyun</groupId>
	<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>

修改yml

server:
  port: 8808

spring:
  #这里使用了Redis缓存了手机验证码
  redis:
    host: localhost
    port: 6379
    database: 1
    timeout: 18000
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 5
        min-idle: 0

#阿里云的短信配置
aliyun:
  sms:
    regionId: default
    accessKeyId: 个人中心的AccessKey ID
    secret: 个人中心的AccessKey Secret

配置类读取yml信息

/**
 * 从配置文件中获取阿里云服务的工具类
 */
@Component
public class ConstantPropertiesUtil implements InitializingBean {
    @Value("${aliyun.sms.regionId}")
    private String regionId;
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.secret}")
    private String secret;

    public static String REGION_ID;
    public static String ACCESS_KEY_ID;
    public static String SECRET;

    @Override
    public void afterPropertiesSet() throws Exception {
        REGION_ID = this.regionId;
        ACCESS_KEY_ID = this.accessKeyId;
        SECRET = this.secret;
    }
}

控制层

@RestController
@RequestMapping("/sms")
public class SMSController {
    @Autowired
    private SMSService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 通过手机号发送验证码
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public String sendCode(@PathVariable("phone") String phone){
        //先从Redis中获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return "Success";
        //如果获取不到就通过阿里云获取验证码
        //生成六位随机数
        DecimalFormat df = new DecimalFormat("000000")
        code = sixDf.format(random.nextInt(1000000));
        //通过整合阿里云短信服务发送
        Boolean isSend = smsService.send(phone,code);
        //验证码放到Redis中设置过期时间:1分钟
        if(isSend){
            redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
            return "Success";
        }else {
            return "Error";
        }
    }
}

业务层

public interface SMSService {
    /**
     * 判断发送手机验证码成功与否
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    boolean send(String phone, String code);
}

@Service
public class SMSServiceImpl implements SMSService {
    /**
     * 判断发送手机验证码成功与否
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    @Override
    public boolean send(String phone, String code) {
        if(StringUtils.isEmpty(phone)) return false;
        //整合阿里云短信服务 设置相关参数
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtil.REGION_ID,
                        ConstantPropertiesUtil.ACCESS_KEY_ID,
                        ConstantPropertiesUtil.SECRET);
        //调用固定的阿里云的地址
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);//手机号
        request.putQueryParameter("SignName", "自己的签名名称");
        request.putQueryParameter("TemplateCode", "自己的模板code");
        Map<String,Object> map = new HashMap<>();
        map.put("code",code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));//验证码
        IAcsClient client = new DefaultAcsClient(profile);
        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_65563175/article/details/129500393