吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3134|回复: 19
收起左侧

[讨论] 阿里云短信服务快速搭建

  [复制链接]
tzforevereer 发表于 2021-9-4 22:22

0.源码地址

https://github.com/tzforevereer/AliMessageDemo

1. 技术栈

  • java
  • springboot
  • maven
  • redis

2.进入阿里云官网

https://www.aliyun.com/

2.1 登录=>选择进入短信服务

3.png

2.2 开通服务=>进入管理控制台

注:我已经开通服务,所以显示的是管理控制台

4.png

2.3 添加模板管理

选择 国内消息 - 模板管理 - 添加模板

9.png

点击 添加模板,进入到添加页面,输入模板信息

  • 选择模板类型:验证码
  • 模板名称:xxxxx (一定要有具体的意义,否则审核不通过)
  • 模板内容: 输入框下方可以使用常用模板库
  • 申请说明: xxxx (有具体说明)

10.png

点击提交,等待审核,审核通过后可以使用

2.4 添加签名管理

选择 国内消息 - 签名管理 - 添加签名

5.png

点击添加签名,进入添加页面,填入相关信息注意:签名要写的有实际意义

  • 签名
  • 使用场景
  • 申请说明:可不写

7.png

点击提交,等待审核,审核通过后可以使用

2.5 注意自己的Accesskey

保存自己的AccessKeyID和AccessKeySecret

11.png

3. 项目初始化

3.1创建空的maven项目

1.png

2.png

3.2 添加项目依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.3.3</version>
        </dependency>
        <!--lombok用来简化实体类:需要安装lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided </scope>
        </dependency>
        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.7.0</version>
        </dependency>
</dependencies>

3.3 创建application.properties

server.port=8001

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000

spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1

spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

3.4 创建启动器AliApplication

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //避免不连接数据库报错
public class AliApplication {
    public static void main(String[] args) {
        SpringApplication.run(AliApplication.class,args);
    }
}

3.5 创建接口定义返回码

public interface ResultCode {

    public static Integer SUCCESS = 20000;

    public  static  Integer ERROR = 20001;
}

3.5 创建统一结果返回类

@Data
public class R {
    //是否成功
    private Boolean success;

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private Map<String, Object> data = new HashMap<String, Object>();

    private R(){};

    public static R ok(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }
    public static R error(){
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }
    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }

3.6 创建utils包下的RandomUtil

package com.demo.aliservice.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 * 
 * home.php?mod=space&uid=686208 qianyi
 *
 */
public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     * home.php?mod=space&uid=952169 list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            int position = Integer.parseInt(String.valueOf(robjs[i]));
            r.add(list.get(position));
        }
        return r;
    }
}

3.7 创建servie接口和service的实现类

service接口

public interface AliService {
    boolean send(Map<String, Object> param, String phone);
}

service的实现了

@Service
public class AliServiceImpl implements AliService {
    public boolean send(Map<String, Object> param, String phone) {
        if(StringUtils.isEmpty(phone)) return false;

                /**
        参数一,default
        参数二,阿里云的AccessKeyID
        参数三,阿里云的AccessKeySecret:
        **/
        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAaASQDF1CGTEEFGUXZHMA", "WRTSbya6qe1SDS6qwe13aWSH0");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        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","我的xxx在线网站"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_139315701"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据,转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

3.8 创建控制器controller

@RestController
@RequestMapping("/msm")
public class AliController {
    @Autowired
    private AliService aliService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sedMsm(@PathVariable String phone){
        // 1. 从redis中获取验证码,获取不到就发送
        String code1 = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code1)){
            return R.ok();
        }

        //生成随机值,传递阿里云进行发送
        String code = RandomUtil.getFourBitRandom();

        Map<String,Object> param = new HashMap<String,Object>();
        param.put("code",code);

        boolean isSend =  aliService.send(param,phone);
        if(isSend){
            //发送成功,把成功的验证码放到redis中,设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }

    }
}

3.9整体项目结构

13.png

4. 运行代码并使用postman调试

12.png

收到信息:
13jpg.jpg

免费评分

参与人数 14吾爱币 +14 热心值 +11 收起 理由
dnightx7 + 1 + 1 咱也不懂,但咱大受震撼!想学
等老子火了 + 1 + 1 我看不懂,但我大受震撼
jeehom + 1 + 1 谢谢@Thanks!
Mdr + 1 + 1 我很赞同!
dgy + 1 谢谢@Thanks!
为妳 + 1 + 1 好完整的教程,赞一个!让我仿佛打开了CSDN。。。。
郑郑郑 + 1 谢谢@Thanks!
wangzhenj + 1 我很赞同!
wksbb + 1 + 1 我很赞同!
iandros + 1 我很赞同!
cc66528 + 1 + 1 我很赞同!
Mainos + 2 + 1 鼓励转贴优秀软件安全工具和文档!
lidaoxin + 1 + 1 我很赞同!
limit7 + 1 + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

limit7 发表于 2021-9-4 23:35
好完整的教程,赞一个!让我仿佛打开了CSDN。。。。
天云尊者 发表于 2021-9-4 23:46
YiQiu 发表于 2021-9-5 01:25
超详细,适合小白如我。
普通短信0.45一条不便宜噢
TogetherC 发表于 2021-9-5 08:41
YiQiu 发表于 2021-9-5 01:25
超详细,适合小白如我。
普通短信0.45一条不便宜噢

又重新看了一下,是0.045
Eapoul 发表于 2021-9-5 08:42
正好在学习
a569421 发表于 2021-9-5 08:50
谢谢大佬分享
blindcat 发表于 2021-9-5 09:24
很详细,谢谢楼主
anwen 发表于 2021-9-5 09:28
很好的东西,当时我们在做测试的时候当时申请哪个验证码好像还得审核比较慢..  我们就没用了 就用了一个假的自己写手机号自己获取...
dreamfly 发表于 2021-9-5 09:50
给力,点赞!
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-11 19:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表