1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import cn.hutool.core.util.RandomUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import com.ilubov.exception.BusinessException; import com.ilubov.property.AliSmsProperty; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;
@Slf4j @Component public class AliSmsUtil {
@Autowired private AliSmsProperty property;
private static AliSmsUtil instance = null;
public static final long EXPIRE_TIME = 5 * 60L;
public AliSmsUtil() { instance = this; }
public static void sendSms(String telephone) { // 六位验证码 String authCode = String.valueOf(RandomUtil.randomInt(100000, 999999)); DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", instance.property.getAccessKeyId(), instance.property.getAccessKeySecret()); 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("RegionId", "cn-hangzhou"); request.putQueryParameter("PhoneNumbers", telephone); request.putQueryParameter("SignName", instance.property.getSignName()); request.putQueryParameter("TemplateCode", instance.property.getTemplateCode()); // 模板参数 ${code} request.putQueryParameter("TemplateParam", "{\"code\":" + authCode + "}"); JSONObject result = null; try { CommonResponse response = client.getCommonResponse(request); String data = response.getData(); log.info("手机号: {}, 短信服务返回信息: {}", telephone, data); result = JSON.parseObject(data); } catch (Exception e) { log.error("短信服务系统错误", e); throw new BusinessException("短信服务系统错误"); } if (!"OK".equals(result.getString("Code"))) { throw new BusinessException(result.getString("Message")); } log.info("手机号: {}, 验证码: {}", telephone, authCode); // 存缓存 RedisUtil.set(telephone, authCode, EXPIRE_TIME); } }
|