Java对接云MAS发送短信验证码(HTTPS方式)
作者:互联网
准备阶段
一.官网下载下载对接文档
二.登录云平台配置账户
管理–>接口管理–>新建短信接口建立自己的用户信息
三.建立好账户后导出证书(用于对接)
代码编写
代码编写
SendReq.java:
@Data public class SendReq { private String ecName; //集团客户名称 private String apId; //用户名 private String secretKey; //密码 private String mobiles; //手机号码逗号分隔。(如“18137282928,18137282922,18137282923”) private String content; //发送短信内容 private String sign; //网关签名编码,必填,签名编码在中国移动集团开通帐号后分配,可以在云MAS网页端管理子系统-SMS接口管理功能中下载。 private String addSerial; //扩展码,根据向移动公司申请的通道填写,如果申请的精确匹配通道,则填写空字符串(""),否则添加移动公司允许的扩展码。 private String mac; //API输入参数签名结果,签名算法:将ecName,apId,secretKey,mobiles,content ,sign,addSerial按照顺序拼接,然后通过md5(32位小写)计算后得出的值。 }
SendRes:
@Data public class SendRes { private String rspcod; //响应状态码 private String msgGroup; //消息批次号,由云MAS平台生成,用于验证短信提交报告和状态报告的一致性(取值msgGroup)注:如果数据验证不通过msgGroup为空 private boolean success; //数据校验结果 }
SMSClient.java:
import cn.com.smart.api.util.JOSNUtil; import cn.com.smart.api.util.MD5Util; import cn.com.smart.common.model.SMS.SendReq; import cn.com.smart.common.model.SMS.SendRes; import lombok.Data; import cn.hutool.http.HttpRequest; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; @Component @Data public class SMSClient { private static String apId="smt"; private static String secretKey="Qzsy@3011071"; private static String ecName = "衢州市第三医院";//集团名称 private static String sign = "knwmf0iAO";//网关签名编码 网关签名编码既第三步导出签名的编码 private static String addSerial = "";//拓展码 填空 public static String msg = "验证码:"; public static String url = "https://112.35.10.201:28888/sms/submit";//请求url /** * * @param mobiles 手机号 * @param code 验证码 * @return * @throws IOException */ public static int sendMsg(String mobiles,int code) throws IOException { SendReq sendReq = new SendReq(); sendReq.setApId(apId); sendReq.setEcName(ecName); sendReq.setSecretKey(secretKey); sendReq.setContent(msg+code); sendReq.setMobiles(mobiles); sendReq.setAddSerial(addSerial); sendReq.setSign(sign); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(sendReq.getEcName()); stringBuffer.append(sendReq.getApId()); stringBuffer.append(sendReq.getSecretKey()); stringBuffer.append(sendReq.getMobiles()); stringBuffer.append(sendReq.getContent()); stringBuffer.append(sendReq.getSign()); stringBuffer.append(sendReq.getAddSerial()); sendReq.setMac(MD5Util.MD5(stringBuffer.toString()).toLowerCase()); String reqText = JSON.toJSONString(sendReq); String encode = Base64.encodeBase64String(reqText.getBytes()); //此处使用hutool工具包httpRequest工具类发送https请求 String resStr = HttpRequest.post(url) .header("contentType", "utf-8") .body(encode) .execute() .body(); System.out.println("发送短信结果:"+resStr); SendRes sendRes = JOSNUtil.json2pojo(resStr, SendRes.class); if(sendRes.isSuccess() && !"".equals(sendRes.getMsgGroup()) && "success".equals(sendRes.getRspcod())){ return 1; }else{ return 0; } } }
Md5Util.java:
import org.apache.commons.codec.binary.Base64; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.MessageDigest; /** * @author xiaoyafeng */ public class Md5Util { static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; /** * 生成MD5码 * @param plainText 要加密的字符串 * @return md5值 */ public final static String MD5(String plainText) { try { byte[] strTemp = plainText.getBytes("UTF-8"); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } /** * 生成MD5码 * @param plainText 要加密的字符串 * @return md5值 */ public final static String MD5(byte[] plainText) { try { byte[] strTemp = plainText; MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } /** * 先进行HmacSHA1转码再进行Base64编码 * @param data 要SHA1的串 * @param key 秘钥 * @return * @throws Exception */ public static String HmacSHA1ToBase64(String data, String key) throws Exception { SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); byte[] rawHmac = mac.doFinal(data.getBytes()); return Base64.encodeBase64String(rawHmac); } /** * 校验MD5码 * @param text 要校验的字符串 * @param md5 md5值 * @return 校验结果 */ public static boolean valid(String text, String md5) { return md5.equals(MD5(text)) || md5.equals(MD5(text).toUpperCase()); } /** * @param params * @return */ public static String MD5(String... params) { StringBuilder sb = new StringBuilder(); for (String param : params) { sb.append(param); } return MD5(sb.toString()); } }
BaseController.java:
@Slf4j @RestController @RequestMapping("api/auth") public class AuthController extends BaseController{ @Autowired private StringRedisTemplate stringRedisTemplate; @ApiOperation(value = "短信验证码") @GetMapping("/sendSMSMessage") public void sendSMSMessage(String phoneNum){ Assert.isTrue(StringUtils.isNotBlank(phoneNum),"请输入手机号!"); int result = 0; //随机生成6位数验证码 int code = (int) ((Math.random() * 6 + 1) * 100000); try { result = SMSClient.sendMsg(phoneNum,code); } catch (IOException e) { ResponseUtil.renderJsonResult(response, errorReply(e)); } //将phoneNum当做键,把验证码存入redis stringRedisTemplate.opsForValue().set(phoneNum,code+""); //设置redis的过期时间,1分钟 stringRedisTemplate.expire(phoneNum,60,TimeUnit.SECONDS); if (result>0) { ResponseUtil.renderJsonResult(response, successReply()); } }
//验证 @PostMapping("checkSMSCode") public void checkSMSCode(String phoneNum,String code) { if (StringUtils.isBlank(code)) { throw new BizException("验证码不能为空!"); } String serverCode = stringRedisTemplate.opsForValue().get(phoneNum); // String serverCode = (String) map.get(phoneNum); //验证码为空或为空字符 if (serverCode == null || serverCode.equals("")) { throw new BizException("请输入验证码!"); } //验证码不匹配 if (!code.equals(serverCode)) { throw new BizException("验证码错误!"); }else { Boolean isDelete = stringRedisTemplate.delete(phoneNum); if (isDelete){ ResponseUtil.renderJsonResult(response, successReply()); } } }
标签:MAS,Java,String,private,static,sendReq,HTTPS,return,public 来源: https://www.cnblogs.com/mushang/p/15903309.html