发表于: 2020-09-12 22:31:39
0 1355
package com.mb.util;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import lombok.Data;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class SendMessageUtil {
@Autowired
RedisTemplate redisTemplate;
private static Logger logger = Logger.getLogger(SendMessageUtil.class);
private String serverIp;
private String serverPort;
private String accountSId;
private String accountToken;
private String appId;
//set方法注入
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public void setServerPort(String serverPort) {
this.serverPort = serverPort;
}
public void setAccountSId(String accountSId) {
this.accountSId = accountSId;
}
public void setAccountToken(String accountToken) {
this.accountToken = accountToken;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void sendTelCode(String tel) {
CCPRestSmsSDK sdk = new CCPRestSmsSDK();
// 初始化服务器地址和端口,格式如下,服务器地址不需要写https:
sdk.init(serverIp, serverPort);
// 初始化主帐号和主帐号TOKEN
sdk.setAccount(accountSId, accountToken);
// 初始化应用ID
sdk.setAppId(appId);
// 1-电话作为参数输入
// 2-模板ID
String templateId = "1";
// 3-随机四位验证码,直接 String.valueOf() 会有小数,不是整数
int yzm = (int) ((Math.random() * 8999) + 1000);
// 将手机号为key,验证码为value,存储缓存,设置过期时间2分钟
try {
redisTemplate.opsForValue().set("tel", "yzm", 120, TimeUnit.SECONDS);
logger.info("手机号,验证码放入缓存成功");
} catch (Exception e){
logger.info("手机号,验证码放入缓存失败");
}
//设置模板中的2个参数 第一个为验证码yzm 第二个为2 (2分钟内输入验证码)
String[] datas= {"yzm","2"};
logger.info("验证码:" + yzm);
logger.info("准备传入的参数"+tel+"==="+templateId+"====="+datas);
// 发送短信 获取发送结果
HashMap<String, Object> result = sdk.sendTemplateSMS(tel,templateId ,datas);
logger.info("短信验证发送结果 = " + result);
// statusCode状态码为000000,即为发送成功
if("000000".equals(result.get("statusCode"))){
// 正常返回输出data包体信息(map)
HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
// 获取data中的key
Set<String> keySet = data.keySet();
// 遍历key,通过key得到对应的值,输出
for(String key:keySet){
Object object = data.get(key);
logger.info(key +" = "+object);
}
}else{
//异常返回输出错误码和错误信息
logger.info("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
}
}
}
测试
@Test
public void xx(){
String tel = "17609006625";
sendMessage.sendTelCode(tel);
}
今日问题 暂无
评论