调用阿里云短信接口,实现验证码功能

@Component
@Data
public class MessgeUtils {

public static ExpiringMap map = null;
private static final Logger log = LoggerFactory.getLogger(MessgeUtils.class);

//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "";
static final String accessKeySecret = "";

public static SendSmsResponse sendSms(String phone , String code, String TemplateCode)  {
    //可自助调整超时时间
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    //初始化acsClient,暂不支持region化
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    try {
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
    } catch (ClientException e) {
        e.printStackTrace();
    }
    IAcsClient acsClient = new DefaultAcsClient(profile);
    SendSmsRequest request = new SendSmsRequest();
    request.setPhoneNumbers(phone);
    request.setSignName("");//需要修改为自己的签名
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("code",code);
    log.info(">>>准备发送验证码" + code);
    //模板ID
    request.setTemplateCode(TemplateCode);
    request.setTemplateParam(jsonObject.toJSONString());
    //hint 此处可能会抛出异常,注意catch
    SendSmsResponse sendSmsResponse = null;
    try {
        sendSmsResponse = acsClient.getAcsResponse(request);
    } catch (ClientException e) {
        e.printStackTrace();
    }
    if(null != sendSmsResponse && sendSmsResponse.getCode().equals("OK")){
        log.info(">>>验证码发送成功+" + code);
        //发送成功,把验证码与手机号绑定,用于验证
        map.put(phone,code,120000, TimeUnit.MILLISECONDS);
    }
    return sendSmsResponse;
}

public MessgeUtils(){
    map = ExpiringMap.builder().variableExpiration().expirationPolicy(ExpirationPolicy.CREATED).build();
}


/**
 * 发送验证码
 * @param mobile
 * @param content
 * @return
 */
public static String sendCheckCode(String mobile, String content){
    log.info(">>>发送验证码" + content);
    map.put(mobile,content,60000, TimeUnit.MILLISECONDS);
    return content;
}

}

ps:*发现一个很好的打卡工具,分享给大家:
下载链接

你可能感兴趣的:(java)