基于阿里云短信服务发送手机验证码

使用springboot3集成阿里云的短信服务

登录阿里云(实名认证后)

登录成功后点击云市场

找到想要的服务(每个服务的代码略有不同)

 点击详细

进去免费使用或者直购买

购买成功后去到阿里管控中心-工具于镜像

 需要AppCode

AppCode是后面进行短信发送的认证

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信
     *
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        // TODO 生成随机4位验证码
        String code = RandomStringUtils.randomNumeric(4);

        System.out.println("code =============> " + code);

        // TODO 存入Redis 15分钟内有效
        stringRedisTemplate.opsForValue().set(phone, code, 15, TimeUnit.MINUTES);

        // TODO 发送短信
        sendMessage(phone, code);
    }

// phone为要发送到短信的手机号 code为验证码
    private void sendMessage(String phone, String code) {
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "自己的appcode 从阿里复制";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求,定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:" + code);
        bodys.put("template_id", "CST_ptdie100");  //注意,CST_ptdie100该模板ID仅为调试使用,调试结果为"status": "OK" ,即表示接口调用成功,然后联系客服报备自己的专属签名模板ID,以保证短信稳定下发
        bodys.put("phone_number", phone);


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println("------->==="+response.toString());
            //获取response的body
            System.out.println("------>"+EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

创建工具类(也可以去阿里云下载)直接复制下面的代码即可

<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值