赞
踩
package com.cbb.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.springframework.stereotype.Component;
/**
* 登录验证码网站 http://yun.loktong.com/ 先注册一个账号,获得账号密码 需要在文本短信签名模板管理提交认证 获得token与模板Id
*
@author 陈斌斌
* @Date 2022年5月11日 14点23分
*
*/
@Component
public class Verification {
/**
* 发送验证码的接口地址
*/
private static final String URL = "http://www.lokapi.cn/smsUTF8.aspx";
/**
* 开通服务的账号
*/
private static final String USERNAME = "xxxxxxxxxxxx";
/**
* 登录密码
*/
private static final String PASSWORD = "xxxxxxxxxxxx";
/**
* 在文字短信 -产品总览- 验证码TOCKEN
*/
private static final String TOCKEN = "xxxxxxxx";
/**
* 模板管理-模板Id
*/
private static final String ACCOUNTSID = "xxxxxxxx";
/**
* 获得当前毫秒数
*/
private static final long TIMESTAMP = System.currentTimeMillis();
/**
* 传一个你要发送验证码的手机号
*
* @param phone
* @return
* @throws ParseException
*/
public Map<String, String> verificationCode(String phone) throws ParseException {
String beforSign = "action=sendtemplate&username=" + USERNAME + "&password=" + getMD5String(PASSWORD)
+ "&token=" + TOCKEN + "×tamp=" + TIMESTAMP;
String postData = "action=sendtemplate&username=" + USERNAME + "&password=" + getMD5String(PASSWORD) + "&token="
+ TOCKEN + "&templateid=" + ACCOUNTSID + "¶m=" + phone + "|" + randomCode()
+ "&rece=json×tamp=" + TIMESTAMP + "&sign=" + getMD5String(beforSign);
Map<String, String> map = new HashMap<String, String>();
try {
sendPost(URL, postData);
map.put("code", "200");
map.put("randomCode",String.valueOf(randomCode()));
map.put("message", "发送成功");
return map;
} catch (Exception e) {
map.put("code", "400");
map.put("message", "欠费");
return map;
}
}
/**
* 生成6位随机数
*/
public static int randomCode() {
return (int) ((Math.random() * 9 + 1) * 100000);
}
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String getMD5String(String rawString) { // 用来计算MD5的函数
String[] hexArray = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(rawString.getBytes());
byte[] rawBit = md.digest();
String outputMD5 = " ";
for (int i = 0; i < 16; i++) {
outputMD5 = outputMD5 + hexArray[rawBit[i] >>> 4 & 0x0f];
outputMD5 = outputMD5 + hexArray[rawBit[i] & 0x0f];
}
return outputMD5.trim();
} catch (Exception e) {
System.out.println("计算MD5值发生错误");
e.printStackTrace();
}
return null;
}
/**
* 生成秘钥
*
* @param tm
* @param key
* @return
*/
public static String createSign(TreeMap<String, String> tm, String key) {
StringBuffer buf = new StringBuffer(key);
for (Map.Entry<String, String> en : tm.entrySet()) {
String name = en.getKey();
String value = en.getValue();
if (!"sign".equals(name) && !"param".equals(name) && value != null && value.length() > 0
&& !"null".equals(value)) {
buf.append(name).append('=').append(value).append('&');
}
}
String _buf = buf.toString();
return _buf.substring(0, _buf.length() - 1);
}
/**
* 将文件转成base64 字符串
*
* @param path文件路径
* @return *
* @throws Exception
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
;
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
return "";
}
}
package com.cbb.entity;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 这是一个关于手机短信验证码的实体类
*
* @author 陈斌斌
*
* @date 2022年5月11日 09点24分
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("varificat")
public class Varificat {
/**
* 主键Id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 验证码
*/
@TableField("verification")
private String verification;
/**
* 注册时间
*/
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@TableField("createTime")
private Date createTime;
/**
* 手机号码
*/
@TableField("phone")
private String phone;
}
package com.cbb.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cbb.entity.Varificat;
/**
* 这是一个关于接收手机短信验证码信息的接口
*
* @author 陈斌斌
* @Date 2022年5月11日 09点25分
*
*/
public interface VerificatMapper extends BaseMapper<Varificat> {
package com.cbb.service;
import java.util.Map;
import com.cbb.entity.Varificat;
/**
* 这是一个关于接收手机短信验证码信息业务处理的接口
*
* @author 陈斌斌
* @Date 2022年5月11日 09点25分
*
*/
public interface VerificatService {
/**
* 找回密码通过手机号
*
* @param verificat
* @return
*/
Map<String, String> sendVerification(Varificat verificat);
}
package com.cbb.serviceimple;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cbb.entity.Varificat;
import com.cbb.mapper.VerificatMapper;
import com.cbb.service.VerificatService;
import com.cbb.util.Verification;
import lombok.RequiredArgsConstructor;
/**
* 这是一个关于接收手机短信验证码信息业务处理的实现类,处理业务逻辑
*
* @author 陈斌斌
* @Date 2022年5月11日 09点25分
*
*/
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VerificatServiceImple implements VerificatService {
/**
* 短信验证码工具类
*/
private final Verification verification;
/**
* 短信验证码接口
*/
private final VerificatMapper verificatMapper;
/**
* 找回密码通过手机号
*
* @param verificat
* @return
*/
public Map<String, String> sendVerification(Varificat verificat) {
Map<String, String> map = new HashMap<String, String>(0);
try {
map = verification.verificationCode(verificat.getPhone());
verificat.setVerification(map.get("randomCode").toString());
verificat.setCreateTime(new Date());
int n = verificatMapper.insert(verificat);
if (n > 0) {
map.put("code", "200");
map.put("message", "发送成功");
} else {
map.put("code", "200");
map.put("message", "发送失败");
}
} catch (ParseException e) {
e.printStackTrace();
}
return map;
}
/**
* 验证验证码与手机号是否准确
*
* @param number
* @param phone
* @return
*/
public Map<String, String> seleVerification(@Param("number") String number, @Param("phone") String phone) {
Map<String, String> map = new HashMap<String, String>(0);
QueryWrapper<Varificat> queryWrapper = new QueryWrapper<Varificat>();
if (number != null && !"".equals(number)) {
queryWrapper.eq("verification", number);
}
if (phone != null && !"".equals(phone)) {
queryWrapper.eq("phone", phone);
}
queryWrapper.orderByDesc("createTime");
Varificat v = verificatMapper.selectOne(queryWrapper);
if (v != null) {
map.put("code", "200");
map.put("message", "查询成功");
verificatMapper.delete(queryWrapper);
} else {
map.put("code", "500");
map.put("message", "验证码失效或者验证码不正确");
}
return map;
package com.cbb.controller;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cbb.entity.Varificat;
import com.cbb.service.VerificatService;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VerificationController {
private final VerificatService verificatService;
/**
* 找回密码通过手机号
*
* @param verificat
* @return
*/
@RequestMapping("sendVerification")
//封装成为对象,实际传入的是手机号
public Map<String, String> sendVerification(Varificat verificat) {
if (verificat != null) {
return verificatService.sendVerification(verificat);
} else {
return null;
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。