• 欢迎光临~

阿里短信发送的工具集成

开发技术 开发技术 2022-08-05 次浏览

1.工具类

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.qiniu.util.Json;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Data
@ConfigurationProperties(prefix = "alimessage")
public class AliMessageUtils {

private String accessKeyId;

private String accessKeySecret;

@Autowired
private RedisTemplate redisTemplate;

public boolean sendMessage(MessageSign messageSign,String phoneNumber) throws Exception {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId("")
// 您的AccessKey Secret
.setAccessKeySecret("");
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
Client client=new Client(config);
String sendCode=sendCode();
Map map=new HashMap();
map.put("code",sendCode);
redisTemplate.opsForValue().set("phones:" + phoneNumber, sendCode,5, TimeUnit.MINUTES);
SendSmsRequest sendReq=new SendSmsRequest()
.setPhoneNumbers(phoneNumber)
.setSignName("签名名称")
.setTemplateCode(messageSign.getValue())
.setTemplateParam(Json.encode(map));
SendSmsResponse sendResp = client.sendSms(sendReq);
String getCode = sendResp.body.code;
if (!Common.equalString(getCode, "OK")) {
System.out.println(sendResp.body.message + "");
return false;
}else{
return true;
}
}
//生成6位验证码
private String sendCode(){
String sjs="";
for (int i = 0; i < 6; i++) {
int max=9,min=0;
int ran2 = (int) (Math.random()*(max-min)+min);
sjs = ran2 + sjs;
}
return sjs;
}
}

2.短信签名模板
public enum MessageSign {

REGIST_SIGN("SMS_1605","注册"),
LOGIN_SIGN("SMS_1605","登录"),
RESET_SIGN("SMS_1605","重置密码"),
COMMON_SIGN("SMS_1918","通用模板");


private String value;//值
private String desc;//描述
/**
* @param value
*/
private MessageSign(String value, String desc){
this.value=value;
this.desc=desc;
}
/**
* @return
*/
public String getValue(){
return value;
}
public String getDesc(){
return desc;
}
}

3.测试调用
@Autowired
private AliMessageUtils aliMessageUtils;
aliMessageUtils.sendMessage(MessageSign.COMMON_SIGN, sysPhone);


程序员灯塔
转载请注明原文链接:阿里短信发送的工具集成
喜欢 (0)