package com.starry.admin.utils; import cn.hutool.core.util.RandomUtil; import com.starry.common.redis.RedisCache; import com.starry.common.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * @Author: huchuansai * @Date: 2024/7/29 5:41 PM * @Description: */ @Slf4j @Service public class SmsUtils { @Resource private RedisCache redisCache; // 发送短信验证码接口 public void sendSmsApi(String phone) { String code = RandomUtil.randomNumbers(4); sendSms(phone, code, "CST_paqequfcmkuv11286"); String key = "sms:phone:" + phone; // 存放到redis里 redisCache.setCacheObject(key, code, 10L, java.util.concurrent.TimeUnit.MINUTES); } // 校验短信验证码是否正确 public void checkSmsCode(String phone, String code) { if(StringUtils.isEmpty(code)){ throw new RuntimeException("短信验证码必填"); } String key = "sms:phone:" + phone; Object data = redisCache.getCacheObject(key); if (Objects.isNull(data)) { throw new RuntimeException("短信验证码无效或已过期"); } if (!code.equals(data.toString())) { throw new RuntimeException("短信验证码错误"); } } private static void sendSms(String phone, String code, String templateId) { String host = "https://wwsms.market.alicloudapi.com"; String path = "/send_sms"; String method = "POST"; String appcode = "18639b38538849e1bc8a3413a8d0c0e5"; Map headers = new HashMap<>(); headers.put("Authorization", "APPCODE " + appcode); headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); Map querys = new HashMap<>(); Map bodys = new HashMap<>(); bodys.put("content", "code:" + code); bodys.put("template_id", templateId); //注意,模板CST_11253 仅作调试使用,下发短信不稳定,请联系客服报备自己的专属签名模板,以保障业务稳定使用 bodys.put("phone_number", phone); try { HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys); String resp = EntityUtils.toString(response.getEntity()); log.info("send sms result:" + resp); } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } } public static void main(String[] args) { sendSms("15974132949", "123456", "CST_paqequfcmkuv11286"); } }