Newer
Older
newfiber-termite / newfiber-system / newfiber-system-sms / src / main / java / com / newfiber / system / template / QiniuSmsTemplate.java
package com.newfiber.system.template;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.newfiber.common.redis.service.RedisService;
import com.newfiber.system.api.enums.ESystemRedisKey;
import com.newfiber.system.domain.model.SmsCode;
import com.newfiber.system.domain.model.SmsData;
import com.newfiber.system.domain.model.SmsProperties;
import com.newfiber.system.domain.model.SmsResponse;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.sms.SmsManager;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;

/**
 * 七牛云短信发送类
 *
 * @author Chill
 */
@AllArgsConstructor
public class QiniuSmsTemplate implements SmsTemplate {

	private final SmsProperties smsProperties;
	private final SmsManager smsManager;
	private final RedisService redisService;

	@Override
	public SmsResponse sendMessage(SmsData smsData, Collection<String> phones) {
		try {
			Response response = smsManager.sendMessage(smsProperties.getTemplateId(), Convert.toStrArray(phones), smsData.getParams());
			return new SmsResponse(response.isOK(), response.statusCode, response.toString());
		} catch (QiniuException e) {
			e.printStackTrace();
			return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
		}
	}

	@Override
	public SmsCode sendValidate(SmsData smsData, String phone) {
		SmsCode smsCode = new SmsCode();
		boolean temp = sendSingle(smsData, phone);
		if (temp && StringUtil.isNotBlank(smsData.getKey())) {
			String id = IdUtil.randomUUID();
			String value = smsData.getParams().get(smsData.getKey());
			redisService.setCacheObject(ESystemRedisKey.SmsCaptcha, cacheKey(phone, id), value, 30L, TimeUnit.MINUTES);
			smsCode.setId(id).setValue(value);
		} else {
			smsCode.setSuccess(Boolean.FALSE);
		}
		return smsCode;
	}

	@Override
	public boolean validateMessage(SmsCode smsCode) {
		String id = smsCode.getId();
		String value = smsCode.getValue();
		String phone = smsCode.getPhone();
		String cache = redisService.getCacheObject(ESystemRedisKey.SmsCaptcha, cacheKey(phone, id));
		if (StringUtil.isNotBlank(value) && StringUtil.equalsIgnoreCase(cache, value)) {
			redisService.deleteObject(ESystemRedisKey.SmsCaptcha, cacheKey(phone, id));
			return true;
		}
		return false;
	}

}