欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

阿里云短信服务

程序员文章站 2024-02-29 20:11:28
...

阿里云短信服务

短信服务,需要先注册阿里云账号,开通短信服务,增加用户组,以及充值操作,可以直接进阿里云官网操作,这里就不多进行写说了,直接上代码
导的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xiao</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>com.xiao</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--导入依赖-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

service接口

public interface SendSms {
    public boolean send(String phoneNum,String templateCode,Map<String,Object> code);
}

接口实现层
注意:下面的AccessKey ID和AccessKey Secret都是自己在阿里云注册用户的时候才有的,签名需要符合阿里云的规范,否则会申请失败,我就是申请了三四次才可以的,个人用户只需要申请验证码即可,所有的包都需要导和阿里云有关系的包,否则会编译不了

package com.xiao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xiao.service.SendSms;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @outhor liu
 * @dare 2020/5/2 16:56
 */
@Service
public class SendSmsImpl implements SendSms {
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou","AccessKey ID","AccessKey Secret");
        DefaultAcsClient client = new DefaultAcsClient(profile);

        //构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //自定义的参数:手机号、验证码、签名、模板
        request.putQueryParameter("PhoneNumbers",phoneNum);
        request.putQueryParameter("SignName","码农java天地app");
        request.putQueryParameter("TemplateCode",templateCode);
        //构建一个短信的验证码
//        HashMap<String,Object> map = new HashMap<>();
//        map.put("code",1234);

        request.putQueryParameter("TemplateParam",JSONObject.toJSONString(code));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}

controller层

package com.xiao.controller;

import com.aliyuncs.utils.StringUtils;
import com.xiao.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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;

/**
 * @outhor liu
 * @dare 2020/5/2 16:59
 */
@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){
        //调用方法
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return phone + ":" + "已存在,还没有过期";
        }
         code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        boolean send = sendSms.send(phone, "SMS_189616087", map);
        if (send){
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.SECONDS);
            return phone + ":" + code + "发送成功";
        }else{
            return "发送失败";
        }
    }
}

application.properties配置

spring.redis.host=127.0.0.1
spring.redis.port=6379

配置完redis的配置之后,记得要开启redis.server服务