注册获取手机号验证码

This commit is contained in:
yuyang 2021-08-02 20:25:47 +08:00
parent cd31ae2335
commit acdd7da542
7 changed files with 486 additions and 3 deletions

View File

@ -29,6 +29,12 @@ import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*; import java.util.*;
/** /**
@ -148,11 +154,11 @@ public class HttpUtils {
} }
/** /**json格式的参数数据
* post请求 * post请求
* *
* @param url 请求地址 * @param url 请求地址
* @param params json格式的参数数据 * @param params
* @return * @return
* @author fengjundan * @author fengjundan
* @date 2018/6/2 * @date 2018/6/2
@ -405,5 +411,66 @@ public class HttpUtils {
return null; return null;
} }
public static String postFormData(String path, HashMap<String, String> Headers, HashMap<String, String> formMap) {
String result = "";
HttpURLConnection connection = null;
String boundary = "--------------------------132183525382215881770481";
try {
URL url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
// 不使用缓存
connection.setUseCaches(false);
if (Headers != null) {
if (Headers.size() > 0) {
for (Map.Entry<String, String> entry : Headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
}
StringBuffer formSB = new StringBuffer();
if (formMap != null) {
if (formMap.size() > 0) {
for (Map.Entry<String, String> entry : formMap.entrySet()) {
String inputName = entry.getKey();
String inputValue = entry.getValue();
formSB.append("\r\n").append("--").append(boundary).append("\r\n");
formSB.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
formSB.append(inputValue);
}
formSB.append("\r\n").append("--").append(boundary).append("--");
}
}
connection.connect();
//OutputStream out = new DataOutputStream(connection.getOutputStream());
PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
out.print(formSB.toString());
out.flush();
//获得响应状态
int resultCode = connection.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
formSB = new StringBuffer();
String readLine;
BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
formSB.append(readLine).append("\n");
}
responseReader.close();
result = formSB.toString();
} else {
result = "{\"code\":\"" + resultCode + "\"}";
}
out.close();
} catch (Exception e) {
logger.error(e.toString());
return "{\"code\":500,\"result\":\"" + "POST表单请求 " + path + " 时出现异常\"}";
} finally {
connection.disconnect();
}
return result;
}
} }

View File

@ -0,0 +1,30 @@
package com.xhpc.general.controller;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.security.annotation.PreAuthorize;
import com.xhpc.general.service.IXhpcSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author yuyang
* @date 2021/8/1 23:42
*/
@RestController
@RequestMapping("/sms")
public class XhpcSmsController extends BaseController {
@Autowired
private IXhpcSmsService xhpcSmsService;
/**
* 注册获取手机号验证码
*/
@GetMapping(value = "/getLogonPhoneCode")
public AjaxResult getLogonPhoneCode(@RequestParam("phone") String phone)
{
return AjaxResult.success(xhpcSmsService.getLogonPhoneCode(phone));
}
}

View File

@ -0,0 +1,152 @@
package com.xhpc.general.domain;
import com.xhpc.common.core.web.domain.BaseEntity;
/**
* @author yuyang
* @date 2021/7/30 18:16
*/
public class XhpcSms extends BaseEntity {
/**
* 短信id
*/
private Long smsId;
/**
* 类型
*/
private String phone;
/**
* 编号
*/
private String code;
/**
* 模板id
*/
private String templateId;
/**
*
*/
private String accessKey;
/**
*
*/
private String secretKey;
/**
*
*/
private String regionId;
/**
* 短信内容
*/
private String content;
/**
* 状态0成功 1失败 2.空号 3.系统异常
*/
private Integer status;
/**
* 删除标志0代表存在 2代表删除
*/
private Integer delFlag;
public Long getSmsId() {
return smsId;
}
public void setSmsId(Long smsId) {
this.smsId = smsId;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
}

View File

@ -0,0 +1,12 @@
package com.xhpc.general.mapper;
import com.xhpc.general.domain.XhpcSms;
/**
* @author yuyang
* @date 2021/7/30 18:51
*/
public interface XhpcSmsMapper {
int addXhpcSms(XhpcSms xhpcSms);
}

View File

@ -0,0 +1,18 @@
package com.xhpc.general.service;
import com.xhpc.common.core.web.domain.AjaxResult;
/**
* @author yuyang
* @date 2021/7/30 18:45
*/
public interface IXhpcSmsService {
/**
* 登陆回验证码
* @param phone
* @return
*/
AjaxResult getLogonPhoneCode(String phone);
}

View File

@ -0,0 +1,109 @@
package com.xhpc.general.service;
import com.alibaba.fastjson.JSONObject;
import com.xhpc.common.core.utils.HttpUtils;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.redis.service.RedisService;
import com.xhpc.general.domain.XhpcSms;
import com.xhpc.general.mapper.XhpcSmsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author yuyang
* @date 2021/7/30 18:50
*/
@Service
public class XhpcSmsServiceImpl implements IXhpcSmsService{
public static RedisService REDIS;
public static final String URL = "http://sms.daiyicloud.com/sms/apiSend/add";
public static final String ACCOUNT ="scxhkj";
public static final String PASSWD ="6A9628548C4CBECCE80A2479CD77679F";
public static final String PRODUCTLD ="20191130000001";
@Autowired
private RedisService redisService;
@Autowired
private XhpcSmsMapper xhpcSmsMapper;
@PostConstruct
public void init(){
REDIS =redisService;
}
@Override
public AjaxResult getLogonPhoneCode(String phone) {
//调用接口
String pattern ="^([1][0-9]{10})";
Pattern compile = Pattern.compile(pattern);
Matcher m =compile.matcher(phone);
boolean isMatch = m.matches();
if(!isMatch){
return AjaxResult.error("1003","请输入正确的手机号");
}
//添加短信记录
XhpcSms xhpcSms =new XhpcSms();
try {
Long random = getRandom();
String conten ="【小华充电】您的验证码是:"+random+"有效期为5分钟。如非本人操作可不用理会。";
String req = HttpUtils.postFormData(URL, null, assembleSmsReq(phone,conten));
JSONObject json = JSONObject.parseObject(req);
xhpcSms.setCode(random+"");
xhpcSms.setPhone(phone);
xhpcSms.setContent(conten);
xhpcSms.setCreateTime(new Date());
xhpcSms.setRemark(req);
String ok = json.getString("ok");
if("true".equals(ok)){
REDIS.setCacheObject(phone,random,300L, TimeUnit.SECONDS);
xhpcSms.setStatus(0);
xhpcSmsMapper.addXhpcSms(xhpcSms);
return AjaxResult.success();
}else{
xhpcSms.setStatus(1);
xhpcSmsMapper.addXhpcSms(xhpcSms);
return AjaxResult.error(1012,"服务器繁忙,请稍后再试");
}
} catch (Exception e) {
//e.printStackTrace();
xhpcSms.setStatus(3);
xhpcSmsMapper.addXhpcSms(xhpcSms);
return AjaxResult.error(1010,"服务器繁忙,请稍后再试");
}
}
private static HashMap<String, String> assembleSmsReq(String phone,String content) {
HashMap<String, String> params = new HashMap<>();
params.put("account", ACCOUNT);
params.put("password", PASSWD);
params.put("content", content);
params.put("mobiles", phone);
params.put("productId", PRODUCTLD);
return params;
}
private Long getRandom(){
Random rnd = new Random();
Long number = Long.valueOf(rnd.nextInt(999999));
return number;
}
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xhpc.general.mapper.XhpcSmsMapper">
<resultMap id="BaseResultMap" type="com.xhpc.general.domain.XhpcSms">
<result property="smsId" column="sms_id"/>
<result property="phone" column="phone"/>
<result property="code" column="code"/>
<result property="templateId" column="template_id"/>
<result property="accessKey" column="access_key"/>
<result property="secretKey" column="secret_key"/>
<result property="regionId" column="region_id"/>
<result property="content" column="content"/>
<result property="status" column="status"/>
<result property="delFlag" column="del_flag"/>
<result property="createTime" column="create_time"/>
<result property="createBy" column="create_by"/>
<result property="updateTime" column="update_time"/>
<result property="updateBy" column="update_by"/>
<result property="remark" column="remark"/>
</resultMap>
<!-- 通用查询映射结果 -->
<insert id="addXhpcSms" parameterType="com.xhpc.general.domain.XhpcSms"
useGeneratedKeys="true" keyProperty="smsId">
insert into xhpc_sms
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="null != phone ">
phone,
</if>
<if test="null != code ">
code,
</if>
<if test="null != content ">
content,
</if>
<if test="null != status ">
status,
</if>
<if test="null != delFlag ">
del_flag,
</if>
<if test="null != createTime ">
create_time,
</if>
<if test="null != createBy and '' != createBy">
create_by,
</if>
<if test="null != updateTime ">
update_time,
</if>
<if test="null != updateBy and '' != updateBy">
update_by,
</if>
<if test="null != remark and '' != remark">
remark
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="null != phone ">
#{phone},
</if>
<if test="null != code ">
#{code},
</if>
<if test="null != content ">
#{content},
</if>
<if test="null != status ">
#{status},
</if>
<if test="null != delFlag ">
#{delFlag},
</if>
<if test="null != createTime ">
#{createTime},
</if>
<if test="null != createBy and '' != createBy">
#{createBy},
</if>
<if test="null != updateTime ">
#{updateTime},
</if>
<if test="null != updateBy and '' != updateBy">
#{updateBy},
</if>
<if test="null != remark and '' != remark">
#{remark}
</if>
</trim>
</insert>
</mapper>