1 Star 0 Fork 165

ElonChung / Java-Review

forked from flatfish / Java-Review 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
阿里云短信验证码服务.md 8.84 KB
一键复制 编辑 原始数据 按行查看 历史
icanci 提交于 2020-08-07 15:12 . :white_check_mark:更新 基础小工具篇

阿里云短信验证码服务

阿里云短信服务

1595076994722

了解阿里云用户权限操作

登录阿里云账号,然后悬停头像,会发现AccessKey 管理,点击去

1595077086699

这个时候为了安全,选择子用户的 AccessKey

1595077171082

创建用户组

1595077242704

然后填写,会验证验证码

1595077299265

1595077340977

1595077355439

开通阿里云短信服务

创建好用户组之后,需要点开用户组,然后添加权限

1595077488257

然后添加用户

1595077586777

创建好之后保存自己的密码和账户

1595077692093

用户登录名称 icanci@1829881847712669.onaliyun.com
AccessKey ID LTAI4G4JptDwzhS624rapUz2
SECRET jKrNsVyG1jhYkWN5g6V5v3IzQZoGZS

然后进入短信服务

1595077852074

然后添加一个模板

1595078186685

然后再添加签名

1595078300581

添加短信模板

  • 短信的基本内容
  • 等待审核通过 需要正当的理由

添加签名

  • 公司的名称
  • 等待审核通过 需要正当的理由

添加用户到组,否则没有权限操作

1595118580625

编写测试代码

新建SpringBoot项目

添加依赖

<!-- 阿里云短信业务 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.4.3</version>
</dependency>

<!-- 如果有需要使用JSON -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
<!-- 整合 Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
package cn.icanci.sms.test;

import com.alibaba.fastjson.JSON;
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 java.util.HashMap;

/**
 * @Author: icanci
 * @ProjectName: aliyun-sms
 * @PackageName: cn.icanci.sms.test
 * @Date: Created in 2020/7/18 22:16
 * @ClassAction:
 */
public class SendSms {
    public static void main(String[] args) {
        // 连接阿里云
        DefaultProfile profile =
            DefaultProfile.getProfile(
            "cn-hangzhou",
            "账户",
            "密码"
        );
        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("SendSms");
        // 自定义的参数 (手机号,验证码,签名,模板)
        // 自定义手机号
        request.putQueryParameter("PhoneNumbers", "15252067235");
        // 自定义签命
        request.putQueryParameter("SignName", "是小猪童鞋啦");
        // 自定义模板 Code
        request.putQueryParameter("TemplateCode", "SMS_196653273");
        // 构建短信验证码
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",9711);
        // 自定义验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

编写可复用的微服务接口、实现验证码的发送

// Service 接口
public interface SendSms {
    /**
     * 短信发送业务
     * @param phoneNum 手机号
     * @param templateCode 模板Code
     * @param code 需要发送的信息
     * @return 返回是否发送成功
     */
    boolean send(String phoneNum, String templateCode, Map<String, Object> code);
}
// Service 实现类

package cn.icanci.sms.service.impl;

import cn.icanci.sms.service.SendSms;
import com.alibaba.fastjson.JSON;
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.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: icanci
 * @ProjectName: aliyun-sms
 * @PackageName: cn.icanci.sms.service.impl
 * @Date: Created in 2020/7/19 8:34
 * @ClassAction:
 */
@Service
public class SendSmsImpl implements SendSms {
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        /**
         * 连接阿里云
         */
        DefaultProfile profile =
            DefaultProfile.getProfile(
            // 不需要改
            "cn-hangzhou",
            // key
            "LTAI4G4JptDwzhS624rapUz2",
            // pwd
            "jKrNsVyG1jhYkWN5g6V5v3IzQZoGZS"
        );
        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("SendSms");
        // 自定义的参数 (手机号,验证码,签名,模板)
        // 自定义手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        // 自定义签命
        request.putQueryParameter("SignName", "是小猪童鞋啦");
        // 自定义模板 Code
        request.putQueryParameter("TemplateCode", templateCode);
        // 自定义验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(code));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            // 是否成功
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
# 本机 redis 配置

spring:
  redis:
    port: 6379
    host: 127.0.0.1
// 发送短信的业务接口

package cn.icanci.sms.controller;

import cn.icanci.sms.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.*;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: icanci
 * @ProjectName: aliyun-sms
 * @PackageName: cn.icanci.sms.controller
 * @Date: Created in 2020/7/19 8:39
 * @ClassAction: 发送短信业务的接口
 */
@RestController
@CrossOrigin
public class SendSmsController {
    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String getSmsCode(@PathVariable("phone") String phone) {
        // 调用方法发送 (模拟真实业务)
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            // 已经存在,没有过期
            return phone + " : " + code;
        }
        // 生成验证码并且存储到Redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);
        boolean isSend = sendSms.send(phone, "SMS_196653273", codeMap);
        if (isSend) {
            // 将手机号作为key,验证码作为 code,有效时间是5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + " : " + code + " 发送成功";
        } else {
            return "发送失败";
        }
    }
}

启动项目,浏览器输入http://localhost:8080/send/15252067235

等待手机接受验证码即可

1
https://gitee.com/elonchung/Java-Review.git
git@gitee.com:elonchung/Java-Review.git
elonchung
Java-Review
Java-Review
master

搜索帮助