pom.xml
4.0.0
com.spring
spring-parent
1.0.0
com.spring
micr-web
1.0.0
1.8
com.spring
micr-api
1.0.0
org.apache.dubbo
dubbo-spring-boot-starter
org.apache.dubbo
dubbo-dependencies-zookeeper
pom
io.springfox
springfox-swagger2
io.springfox
springfox-swagger-ui
com.github.xiaoymin
swagger-bootstrap-ui
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-test
test
com.spring
micr-common
1.0.0
compile
org.springframework.boot
spring-boot-maven-plugin
application.yml
spring:
application:
name: spring-web
mvc:
pathmatch:
matching-strategy: ant_path_matcher
redis:
host: localhost
port: 6379
#端口号
server:
port: 8000
servlet:
context-path: /api
encoding:
enabled: true
charset: utf-8
force: true
#dubbo配置
dubbo:
registry:
address: zookeeper://localhost:2181
scan:
base-packages: com.bjpowernode.front
consumer:
check: false
timeout: 50000
retries: 0
#短信配置
jdwx:
sms:
url: https://way.jd.com/chuangxin/dxjk
appkey: 3680fa919b771148da626bbcbd459475
content: 【大富科技】你的验证码是:%s,3分钟内有效,请勿泄露给他人
login-text: 【大富科技】登录验证码是:%s,3分钟内有效,请勿泄露给他人
realname:
url: https://way.jd.com/youhuoBeijing/test
appkey: 3680fa919b771148da626bbcbd459475
jwt:
secret: 342903934cb944808920b642616b3e76
WebApplication
package com.spring.front;
import com.spring.common.util.JwtUtil;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
//启动swagger 和 ui
@EnableSwaggerBootstrapUI
@EnableSwagger2
//启动dubbo服务
@EnableDubbo
@SpringBootApplication
public class WebApplication {
@Value("${jwt.secret}")
private String secertKey;
//创建JwtUtil
@Bean
public JwtUtil jwtUtil(){
JwtUtil jwtUtil = new JwtUtil(secertKey);
return jwtUtil;
}
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
config.JdwxRealnameConfig
package com.spring.front.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Package:com.spring.front.config
*/
@Component
@ConfigurationProperties(prefix = "jdwx.realname")
public class JdwxRealnameConfig {
private String url;
private String appkey;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
}
config.JdwxSmsConfig
package com.spring.front.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Package:com.spring.front.config
*/
@Component
@ConfigurationProperties(prefix = "jdwx.sms")
public class JdwxSmsConfig {
private String url;
private String appkey;
private String content;
private String loginText;
public String getLoginText() {
return loginText;
}
public void setLoginText(String loginText) {
this.loginText = loginText;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
controller.BaseController
package com.spring.front.controller;
import com.spring.api.service.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
/**
* Package:com.spring.front.controller
*/
public class BaseController {
//声明公共的方法,属性的等
@Resource
protected StringRedisTemplate stringRedisTemplate;
//平台信息服务
@DubboReference(interfaceClass = PlatBaseInfoService.class,version = "1.0")
protected PlatBaseInfoService platBaseInfoService;
//产品服务
@DubboReference(interfaceClass = ProductService.class,version = "1.0")
protected ProductService productService;
//投资服务
@DubboReference(interfaceClass = InvestService.class,version = "1.0")
protected InvestService investService;
//用户服务
@DubboReference(interfaceClass = UserService.class,version = "1.0")
protected UserService userService;
//充值服务
@DubboReference(interfaceClass = RechargeService.class,version = "1.0")
protected RechargeService rechargeService;
}
controller.InvestController
package com.spring.front.controller;
import com.spring.api.model.User;
import com.spring.common.constants.RedisKey;
import com.spring.common.util.CommonUtil;
import com.spring.front.view.RespResult;
import com.spring.front.view.invest.RankView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Package:com.spring.front.controller
* 有关投资功能
*/
@Api(tags = "投资理财产品")
@RestController
public class InvestController extends BaseController {
/*投资排行榜*/
@ApiOperation(value = "投资排行榜", notes = "显式投资金额最高的3位用户信息")
@GetMapping("/v1/invest/rank")
public RespResult showInvestRank() {
//从redis查询数据
Set> sets = stringRedisTemplate
.boundZSetOps(RedisKey.KEY_INVEST_RANK).reverseRangeWithScores(0, 2);
List rankList = new ArrayList<>();
//遍历set集合
sets.forEach(tuple -> {
//tuple.getValue();//手机号
//tuple.getScore();//投资金额
rankList.add(new RankView(CommonUtil.tuoMinPhone(tuple.getValue()), tuple.getScore()));
});
RespResult result = RespResult.ok();
result.setList(rankList);
return result;
}
/*购买理财产品, 更新投资排行榜*/
@ApiOperation(value = "投资理财产品")
@PostMapping("/v1/invest/product")
public RespResult investProduct(
@RequestHeader("uid") Integer uid,
@RequestParam("productId") Integer productId,
@RequestParam("money") BigDecimal money){
RespResult result = RespResult.fail();
//1.检查基本参数
if( (uid != null && uid > 0) && (productId != null && productId > 0)
&&( money != null && money.intValue() % 100 == 0 && money.intValue() >= 100)){
int investResult = investService.investProduct(uid,productId,money);
switch (investResult){
case 0:
result.setMsg("投资数据不正确");
break;
case 1:
result = RespResult.ok();
modifyInvestRank(uid,money);
break;
case 2:
result.setMsg("资金账号不存在");
break;
case 3:
result.setMsg("资金不足");
break;
case 4:
result.setMsg("理财产品不存在");
break;
}
}
return result;
}
/*更新投资排行榜*/
private void modifyInvestRank(Integer uid,BigDecimal money){
User user = userService.queryById(uid);
if(user != null){
//更新redis中的投资排行榜
String key = RedisKey.KEY_INVEST_RANK;
stringRedisTemplate.boundZSetOps(key).incrementScore(
user.getPhone(),money.doubleValue());
}
}
}
controller.PlatInfoController
package com.spring.front.controller;
import com.spring.api.pojo.BaseInfo;
import com.spring.front.view.RespResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Package:com.spring.front.controller
*/
@Api(tags = "平台信息功能")
@RestController
@RequestMapping("/v1")
public class PlatInfoController extends BaseController {
/*平台基本信息*/
@ApiOperation(value = "平台三项基本信息",notes = "注册人数,平均的利率,总投资金额")
@GetMapping("/plat/info")
public RespResult queryPlatBaseInfo(){
//调用远程服务
BaseInfo baseInfo = platBaseInfoService.queryPlatBaseInfo();
RespResult result = new RespResult();
result.setCode(1000); //表示成功
result.setMsg("查询平台信息成功");
result.setData(baseInfo);
return result;
}
}
controller.ProductController
package com.spring.front.controller;
import com.spring.api.model.ProductInfo;
import com.spring.api.pojo.BidInfoProduct;
import com.spring.api.pojo.MultiProduct;
import com.spring.common.enums.RCode;
import com.spring.common.util.CommonUtil;
import com.spring.front.view.PageInfo;
import com.spring.front.view.RespResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Package:com.spring.front.controller
*/
@Api(tags = "理财产品功能")
@RestController
@RequestMapping("/v1")
public class ProductController extends BaseController {
@ApiOperation(value = "首页三类产品列表",notes = "一个新手宝,三个优选,三个散标产品")
@GetMapping("/product/index")
public RespResult queryProductIndex(){
RespResult result = RespResult.ok();
MultiProduct multiProduct = productService.queryIndexPageProducts();
result.setData(multiProduct);
return result;
}
/*按产品类型分页查询*/
@ApiOperation(value = "产品分页查询",notes = "按产品类型分页查询")
@GetMapping("/product/list")
public RespResult queryProductByType(@RequestParam("ptype") Integer pType,
@RequestParam(value = "pageNo",required = false,defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize",required = false,defaultValue = "9") Integer pageSize){
RespResult result = RespResult.fail();
if(pType != null && (pType == 0 || pType == 1 || pType == 2)){
pageNo = CommonUtil.defaultPageNo(pageNo);
pageSize = CommonUtil.defaultPageSize(pageSize);
//分页处理,记录总数
Integer recordNums = productService.queryRecordNumsByType(pType);
if( recordNums > 0 ){
//产品集合
List productInfos = productService.queryByTypeLimit(pType,pageNo,pageSize);
//构建PageInfo
PageInfo page = new PageInfo(pageNo,pageSize,recordNums);
result = RespResult.ok();
result.setList(productInfos);
result.setPage(page);
}
} else {
//请求参数有误
result.setRCode(RCode.REQUEST_PRODUCT_TYPE_ERR);
}
return result;
}
/*查询某个产品的详情和投资记录*/
@ApiOperation(value = "产品详情",notes = "查询某个产品的详细信息和投资5条记录")
@GetMapping("/product/info")
public RespResult queryProductDetail(@RequestParam("productId") Integer id){
RespResult result = RespResult.fail();
if( id != null && id > 0 ){
//调用产品查询
ProductInfo productInfo = productService.queryById(id);
if( productInfo != null){
//查询投资记录
List bidInfoList = investService.queryBidListByProductId(id,1,5);
//查询成功
result = RespResult.ok();
result.setData(productInfo);
result.setList(bidInfoList);
} else {
result.setRCode(RCode.PRODUCT_OFFLINE);
}
}
return result;
}
}
controller.RechargeController
package com.spring.front.controller;
import com.spring.api.model.RechargeRecord;
import com.spring.front.view.RespResult;
import com.spring.front.view.recharge.ResultView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* Package:com.spring.front.controller
*/
@Api(tags = "充值业务")
@RestController
public class RechargeController extends BaseController {
/*查询充值流水*/
@ApiOperation(value = "查询某个用户的充值记录")
@GetMapping("/v1/recharge/records")
public RespResult queryRechargePage(@RequestHeader("uid") Integer uid,
@RequestParam(required = false,defaultValue = "1") Integer pageNo,
@RequestParam(required = false,defaultValue = "6") Integer pageSize){
RespResult result = RespResult.fail();
if( uid != null && uid > 0 ){
List records = rechargeService.queryByUid(uid, pageNo, pageSize);
result = RespResult.ok();
result.setList( toView(records));
//没有做分页。
}
return result;
}
private List toView(List src){
List target = new ArrayList<>();
src.forEach( record -> {
target.add( new ResultView(record));
});
return target;
}
}
controller.SmsController
package com.spring.front.controller;
import com.spring.common.constants.RedisKey;
import com.spring.common.enums.RCode;
import com.spring.common.util.CommonUtil;
import com.spring.front.service.SmsService;
import com.spring.front.view.RespResult;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* Package:com.spring.front.controller
*/
@Api(tags = "短信业务")
@RestController
@RequestMapping("/v1/sms")
public class SmsController extends BaseController {
@Resource(name = "smsCodeRegisterImpl")
private SmsService smsService;
@Resource(name = "smsCodeLoginImpl")
private SmsService loginSmsService;
/**发送注册验证码短信*/
@GetMapping("/code/register")
public RespResult sendCodeRegister(@RequestParam String phone){
RespResult result = RespResult.fail();
if(CommonUtil.checkPhone(phone)){
//判断redis中是否有这个手机号的验证码
String key = RedisKey.KEY_SMS_CODE_REG + phone;
if(stringRedisTemplate.hasKey(key)){
result = RespResult.ok();
result.setRCode(RCode.SMS_CODE_CAN_USE);
} else {
boolean isSuccess = smsService.sendSms(phone);
if( isSuccess ){
result = RespResult.ok();
}
}
} else {
result.setRCode(RCode.PHONE_FORMAT_ERR);
}
return result;
}
/**发送登录验证码短信*/
@GetMapping("/code/login")
public RespResult sendCodeLogin(@RequestParam String phone){
RespResult result = RespResult.fail();
if(CommonUtil.checkPhone(phone)){
//判断redis中是否有这个手机号的验证码
String key = RedisKey.KEY_SMS_CODE_LOGIN + phone;
if(stringRedisTemplate.hasKey(key)){
result = RespResult.ok();
result.setRCode(RCode.SMS_CODE_CAN_USE);
} else {
boolean isSuccess = loginSmsService.sendSms(phone);
if( isSuccess ){
result = RespResult.ok();
}
}
} else {
result.setRCode(RCode.PHONE_FORMAT_ERR);
}
return result;
}
}
controller.UserController
package com.spring.front.controller;
import com.spring.api.model.User;
import com.spring.api.pojo.UserAccountInfo;
import com.spring.common.enums.RCode;
import com.spring.common.util.CommonUtil;
import com.spring.common.util.JwtUtil;
import com.spring.front.service.RealnameServiceImpl;
import com.spring.front.service.SmsService;
import com.spring.front.view.RespResult;
import com.spring.front.vo.RealnameVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.jute.compiler.generated.Rcc;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.management.relation.Relation;
import java.util.HashMap;
import java.util.Map;
/**
* Package:com.spring.front.controller
*/
@Api(tags = "用户功能")
@RestController
@RequestMapping("/v1/user")
public class UserController extends BaseController {
@Resource(name = "smsCodeRegisterImpl")
private SmsService smsService;
@Resource(name = "smsCodeLoginImpl")
private SmsService loginSmsService;
@Resource
private RealnameServiceImpl realnameService;
@Resource
private JwtUtil jwtUtil;
/**手机号注册用户*/
@ApiOperation(value = "手机号注册用户")
@PostMapping("/register")
public RespResult userRegister(@RequestParam String phone,
@RequestParam String pword,
@RequestParam String scode){
RespResult result = RespResult.fail();
//1.检查参数
if( CommonUtil.checkPhone(phone)){
if(pword !=null && pword.length() == 32 ){
//检查短信验证码
if( smsService.checkSmsCode(phone,scode)){
//可以注册
int registerResult = userService.userRegister(phone,pword);
if( registerResult == 1 ){
result = RespResult.ok();
} else if( registerResult == 2 ){
result.setRCode(RCode.PHONE_EXISTS);
} else {
result.setRCode(RCode.REQUEST_PARAM_ERR);
}
} else {
//短信验证码无效
result.setRCode(RCode.SMS_CODE_INVALID);
}
} else {
result.setRCode(RCode.REQUEST_PARAM_ERR);
}
} else {
//手机号格式不正确
result.setRCode(RCode.PHONE_FORMAT_ERR);
}
return result;
}
/** 手机号是否存在 */
@ApiOperation(value = "手机号是否注册过",notes = "在注册功能中,判断手机号是否可以注册")
@ApiImplicitParam(name = "phone",value = "手机号")
@GetMapping("/phone/exists")
public RespResult phoneExists(@RequestParam("phone") String phone){
RespResult result = new RespResult();
result.setRCode(RCode.PHONE_EXISTS);
//1.检查请求参数是否符合要求
if(CommonUtil.checkPhone(phone)){
//可以执行逻辑 ,查询数据库,调用数据服务
User user = userService.queryByPhone(phone);
if( user == null ){
//可以注册
result = RespResult.ok();
}
//把查询到的手机号放入redis。 然后检查手机号是否存在,可以查询redis
} else {
result.setRCode(RCode.PHONE_FORMAT_ERR);
}
return result;
}
/** 登录,获取token-jwt*/
@ApiOperation(value = "用户登录-获取访问token")
@PostMapping("/login")
public RespResult userLogin(@RequestParam String phone,
@RequestParam String pword,
@RequestParam String scode) throws Exception{
RespResult result = RespResult.fail();
if(CommonUtil.checkPhone(phone) && (pword != null && pword.length() == 32) ){
if(loginSmsService.checkSmsCode(phone,scode)){
//访问data-service
User user = userService.userLogin(phone,pword);
if( user != null){
//登录成功,生成token
Map data = new HashMap<>();
data.put("uid",user.getId());
String jwtToken = jwtUtil.createJwt(data,120);
result = RespResult.ok();
result.setAccessToken(jwtToken);
Map userInfo = new HashMap<>();
userInfo.put("uid",user.getId());
userInfo.put("phone",user.getPhone());
userInfo.put("name",user.getName());
result.setData(userInfo);
} else {
result.setRCode(RCode.PHONE_LOGIN_PASSWORD_INVALID);
}
} else {
result.setRCode(RCode.SMS_CODE_INVALID);
}
} else {
result.setRCode(RCode.REQUEST_PARAM_ERR);
}
return result;
}
/** 实名认证 vo: value object*/
@ApiOperation(value = "实名认证",notes = "提供手机号和姓名,身份证号。 认证姓名和身份证号是否一致")
@PostMapping("/realname")
public RespResult userRealname(@RequestBody RealnameVO realnameVO){
RespResult result = RespResult.fail();
result.setRCode(RCode.REQUEST_PARAM_ERR);
//1验证请求参数
if( CommonUtil.checkPhone(realnameVO.getPhone())){
if(StringUtils.isNotBlank(realnameVO.getName()) &&
StringUtils.isNotBlank(realnameVO.getIdCard())){
//判断用户已经做过
User user = userService.queryByPhone(realnameVO.getPhone());
if( user != null ){
if( StringUtils.isNotBlank(user.getName())){
result.setRCode(RCode.REALNAME_RETRY);
} else {
//有短信验证码,先不写
//调用第三方接口,判断认证结果
boolean realnameResult = realnameService.handleRealname(
realnameVO.getPhone(),realnameVO.getName(),
realnameVO.getIdCard());
if( realnameResult == true ){
result = RespResult.ok();
} else {
result.setRCode(RCode.REALNAME_FAIL);
}
}
}
}
}
return result;
}
/** 用户中心 */
@ApiOperation(value = "用户中心")
@GetMapping("/usercenter")
public RespResult userCenter(@RequestHeader(value = "uid",required = false) Integer uid){
RespResult result = RespResult.fail();
if( uid != null && uid > 0 ){
UserAccountInfo userAccountInfo = userService.queryUserAllInfo(uid);
if( userAccountInfo != null ){
result = RespResult.ok();
Map data = new HashMap<>();
data.put("name",userAccountInfo.getName());
data.put("phone",userAccountInfo.getPhone());
data.put("headerUrl",userAccountInfo.getHeaderImage());
data.put("money",userAccountInfo.getAvailableMoney());
if( userAccountInfo.getLastLoginTime() != null){
data.put("loginTime", DateFormatUtils.format(
userAccountInfo.getLastLoginTime(),"yyyy-MM-dd HH:mm:ss"));
} else {
data.put("loginTime","-");
}
result.setData(data);
}
}
return result;
}
}
interceptor.TokenInterceptor
package com.spring.front.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.spring.common.enums.RCode;
import com.spring.common.util.JwtUtil;
import com.spring.front.view.RespResult;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Package:com.spring.front.interceptor
*/
public class TokenInterceptor implements HandlerInterceptor {
private String secret = "";
public TokenInterceptor(String secret) {
this.secret = secret;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//1.如果是OPTIONS,放行
if( "OPTIONS".equalsIgnoreCase(request.getMethod())){
return true;
}
boolean requestSend = false;
try{
//2.获取token的,进行验证
String headerUid = request.getHeader("uid");
String headerToken = request.getHeader("Authorization");
if(StringUtils.isNotBlank(headerToken)){
//Bearer eyxxxxx
String jwt = headerToken.substring(7);
//读jwt
JwtUtil jwtUtil = new JwtUtil(secret);
Claims claims = jwtUtil.readJwt(jwt);
//获取jwt中的数据,uid
Integer jwtUid = claims.get("uid",Integer.class);
if( headerUid.equals( String.valueOf(jwtUid))){
//token和发起请求用户是同一个。 请求可以被处理
requestSend = true;
}
}
}catch (Exception e){
requestSend = false;
e.printStackTrace();
}
//token没有验证通过,需要给vue错误提示
if( requestSend == false ){
//返回json数据给前端
RespResult result = RespResult.fail();
result.setRCode(RCode.TOKEN_INVALID);
//使用HttpServletResponse输出 json
String respJson = JSONObject.toJSONString(result);
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(respJson);
out.flush();
out.close();
}
return requestSend;
}
}
service.impl.SmsCodeLoginImpl
package com.spring.front.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.spring.common.constants.RedisKey;
import com.spring.front.config.JdwxSmsConfig;
import com.spring.front.service.SmsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* Package:com.spring.front.service.impl
*
* 登录发送短信验证码
*/
@Service(value = "smsCodeLoginImpl")
public class SmsCodeLoginImpl implements SmsService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private JdwxSmsConfig smsConfig;
@Override
public boolean sendSms(String phone) {
boolean send = false;
// 设置短信内容
String random = RandomStringUtils.randomNumeric(4);
System.out.println("登录验证码的随机数 random="+random);
//更新content中的 %s 【大富科技】登录验证码是:%s,3分钟内有效,请勿泄露给他人
String content = String.format(smsConfig.getLoginText(), random);
//使用HttpClient发送 get 请求给第三方。
CloseableHttpClient client = HttpClients.createDefault();
//https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=
//【创信】你的验证码是:5873,3分钟内有效!&appkey=您申请的APPKEY
String url = smsConfig.getUrl()+"?mobile="+phone
+"&content=" + content
+"&appkey="+smsConfig.getAppkey();
HttpGet get = new HttpGet(url);
try{
//CloseableHttpResponse response = client.execute(get);
// if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
//得到返回的数据,json
//String text = EntityUtils.toString(response.getEntity());
String text="{\n" +
" \"code\": \"10000\",\n" +
" \"charge\": false,\n" +
" \"remain\": 1305,\n" +
" \"msg\": \"查询成功\",\n" +
" \"result\": {\n" +
" \"ReturnStatus\": \"Success\",\n" +
" \"Message\": \"ok\",\n" +
" \"RemainPoint\": 420842,\n" +
" \"TaskID\": 18424321,\n" +
" \"SuccessCounts\": 1\n" +
" }\n" +
"}";
//解析json
if(StringUtils.isNotBlank(text)){
// fastjson
JSONObject jsonObject = JSONObject.parseObject(text);
if("10000".equals(jsonObject.getString("code"))){ //第三方接口调用成功
//读取result中的key:ReturnStatus
if("Success".equalsIgnoreCase(
jsonObject.getJSONObject("result").getString("ReturnStatus"))){
//短信发送成功
send = true;
//把短信验证码,存到redis
String key = RedisKey.KEY_SMS_CODE_LOGIN + phone;
stringRedisTemplate.boundValueOps(key).set(random,3 , TimeUnit.MINUTES);
}
}
}
// }
}catch (Exception e){
e.printStackTrace();
}
return send;
}
@Override
public boolean checkSmsCode(String phone, String code) {
String key = RedisKey.KEY_SMS_CODE_LOGIN + phone;
if( stringRedisTemplate.hasKey(key)){
String querySmsCode = stringRedisTemplate.boundValueOps(key).get();
if( code.equals(querySmsCode)){
return true;
}
}
return false;
}
}
service.impl.SmsCodeRegisterImpl
package com.spring.front.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.spring.common.constants.RedisKey;
import com.spring.front.config.JdwxSmsConfig;
import com.spring.front.service.SmsService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* Package:com.spring.front.service.impl
*
* 注册发送短信验证码
*/
@Service(value = "smsCodeRegisterImpl")
public class SmsCodeRegisterImpl implements SmsService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private JdwxSmsConfig smsConfig;
@Override
public boolean sendSms(String phone) {
boolean send = false;
// 设置短信内容
String random = RandomStringUtils.randomNumeric(4);
System.out.println("注册验证码的随机数 random="+random);
//更新content中的 %s 【大富科技】你的验证码是:%s,3分钟内有效,请勿泄露给他人
String content = String.format(smsConfig.getContent(), random);
//使用HttpClient发送 get 请求给第三方。
CloseableHttpClient client = HttpClients.createDefault();
//https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=
//【创信】你的验证码是:5873,3分钟内有效!&appkey=您申请的APPKEY
String url = smsConfig.getUrl()+"?mobile="+phone
+"&content=" + content
+"&appkey="+smsConfig.getAppkey();
HttpGet get = new HttpGet(url);
try{
CloseableHttpResponse response = client.execute(get);
if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
//得到返回的数据,json
//String text = EntityUtils.toString(response.getEntity());
String text="{\n" +
" \"code\": \"10000\",\n" +
" \"charge\": false,\n" +
" \"remain\": 1305,\n" +
" \"msg\": \"查询成功\",\n" +
" \"result\": {\n" +
" \"ReturnStatus\": \"Success\",\n" +
" \"Message\": \"ok\",\n" +
" \"RemainPoint\": 420842,\n" +
" \"TaskID\": 18424321,\n" +
" \"SuccessCounts\": 1\n" +
" }\n" +
"}";
//解析json
if(StringUtils.isNotBlank(text)){
// fastjson
JSONObject jsonObject = JSONObject.parseObject(text);
if("10000".equals(jsonObject.getString("code"))){ //第三方接口调用成功
//读取result中的key:ReturnStatus
if("Success".equalsIgnoreCase(
jsonObject.getJSONObject("result").getString("ReturnStatus"))){
//短信发送成功
send = true;
//把短信验证码,存到redis
String key = RedisKey.KEY_SMS_CODE_REG + phone;
stringRedisTemplate.boundValueOps(key).set(random,3 , TimeUnit.MINUTES);
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return send;
}
@Override
public boolean checkSmsCode(String phone, String code) {
String key = RedisKey.KEY_SMS_CODE_REG + phone;
if( stringRedisTemplate.hasKey(key)){
String querySmsCode = stringRedisTemplate.boundValueOps(key).get();
if( code.equals(querySmsCode)){
return true;
}
}
return false;
}
}
service.RealnameServiceImpl
package com.spring.front.service;
import com.alibaba.fastjson.JSONObject;
import com.spring.api.model.User;
import com.spring.api.service.UserService;
import com.spring.common.util.HttpClientUtils;
import com.spring.front.config.JdwxRealnameConfig;
import com.fasterxml.jackson.databind.node.POJONode;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* Package:com.spring.front.service
*/
@Service
public class RealnameServiceImpl {
@Resource
private JdwxRealnameConfig realnameConfig;
@DubboReference(interfaceClass = UserService.class,version = "1.0")
private UserService userService;
/*true:认证通过*/
public boolean handleRealname(String phone,String name,String idCard){
boolean realname = false;
Map params = new HashMap<>();
params.put("cardNo",idCard);
params.put("realName",name);
params.put("appkey",realnameConfig.getAppkey());
try {
// String resp = HttpClientUtils.doGet(realnameConfig.getUrl(),params);
String resp="{\n" +
" \"code\": \"10000\",\n" +
" \"charge\": false,\n" +
" \"remain\": 1305,\n" +
" \"msg\": \"查询成功\",\n" +
" \"result\": {\n" +
" \"error_code\": 0,\n" +
" \"reason\": \"成功\",\n" +
" \"result\": {\n" +
" \"realname\": \""+name+"\",\n" +
" \"idcard\": \"350721197702134399\",\n" +
" \"isok\": true\n" +
" }\n" +
" }\n" +
"}";
if(StringUtils.isNotBlank(resp)){
JSONObject respObject = JSONObject.parseObject(resp);
if( "10000".equalsIgnoreCase(respObject.getString("code"))){
//解析result
realname = respObject.getJSONObject("result")
.getJSONObject("result")
.getBooleanValue("isok");
//处理更新数据库
boolean modifyResult = userService.modifyRealname(phone,name,idCard);
realname = modifyResult;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return realname;
}
}
service.SmsService
package com.spring.front.service;
/**
* Package:com.spring.front.service
*/
public interface SmsService {
/**
* @param phone 手机号
* @return true:发送成功,false 其他情况
*/
boolean sendSms(String phone);
/**
* @param phone 手机号
* @param code 提交参数中的验证码
* @return
*/
boolean checkSmsCode(String phone,String code);
}
settings.JacksonConfiguration
package com.spring.front.settings;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
/**
* Package:com.spring.front.settings
*/
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
//设置null序列化时 为""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer
settings.SwaggerConfigurationSettings
package com.spring.front.settings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* Package:com.spring.config
*/
@Configuration
public class SwaggerConfigruationSettinngs {
//创建Docket对象
@Bean
public Docket docket(){
//1创建Docket对象
Docket docket = new Docket(DocumentationType.SWAGGER_2);
//2创建Api信息, 接口文档的总体描述
ApiInfo apiInfo = new ApiInfoBuilder()
.title("动力节点金融项目")
.version("1.0")
.description("前后端分离的项目,前端Vue,后端Spring Boot + Dubbo分布式项目")
.build();
//3.设置使用ApiInfo
docket = docket.apiInfo(apiInfo);
//4.设置参与文档生成的包
docket = docket.select().apis(RequestHandlerSelectors.
basePackage("com.bjpowernode.front.controller")).build();
return docket;
}
}
settings.WebMvcConfiguration
package com.spring.front.settings;
import com.spring.front.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* Package:com.spring.front.settings
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Value("${jwt.secret}")
private String jwtSecret;
@Override
public void addInterceptors(InterceptorRegistry registry) {
TokenInterceptor tokenInterceptor = new TokenInterceptor(jwtSecret);
String [] addPath = {"/v1/user/realname"};
registry.addInterceptor(tokenInterceptor)
.addPathPatterns(addPath);
}
/*处理跨域*/
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println("===========addCorsMappings===========");
//addMapping 处理的请求地址, 拦截这些地址,使用跨域处理逻辑
registry.addMapping("/**")
.allowedOriginPatterns("http://localhost:8080") //可跨域的域名,可以为 *
//支持跨域请求的,http方式
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
//支持跨域的请求头, 在请求头包含哪些数据时,可以支持跨域功能
.allowedHeaders("*");
}
}
view.invest.RankView
package com.spring.front.view.invest;
/**
* Package:com.spring.front.view.invest
*
* 存储投资排行榜的数据
*/
public class RankView {
private String phone;
private Double money;
public RankView(String phone, Double money) {
this.phone = phone;
this.money = money;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
view.recharge.ResultView
package com.spring.front.view.recharge;
import com.spring.api.model.RechargeRecord;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.math.BigDecimal;
/**
* Package:com.spring.front.view.recharge
*/
public class ResultView {
private Integer id;
private String result = "未知";
private String rechargeDate = "-";
private BigDecimal rechargeMoney;
public ResultView(RechargeRecord record) {
this.id = record.getId();
this.rechargeMoney = record.getRechargeMoney();
if (record.getRechargeTime() != null) {
rechargeDate = DateFormatUtils.format(record.getRechargeTime(), "yyyy-MM-dd");
}
switch (record.getRechargeStatus()) {
case 0:
result = "充值中";
break;
case 1:
result = "成功";
break;
case 2:
result = "失败";
}
}
public Integer getId() {
return id;
}
public String getResult() {
return result;
}
public String getRechargeDate() {
return rechargeDate;
}
public BigDecimal getRechargeMoney() {
return rechargeMoney;
}
}
view.PageInfo
package com.spring.front.view;
/**
* Package:com.spring.front.view
* 分页数据类
*/
public class PageInfo {
//页号
private Integer pageNo;
//每页大小
private Integer pageSize;
//总页数
private Integer totalPage;
//总记录数
private Integer totalRecord;
public PageInfo() {
}
public PageInfo(Integer pageNo, Integer pageSize, Integer totalRecord) {
this.pageNo = pageNo;
this.pageSize = pageSize;
this.totalRecord = totalRecord;
//计算总页数
if( this.totalRecord % this.pageSize == 0 ){
this.totalPage = this.totalRecord / this.pageSize;
} else {
this.totalPage = this.totalRecord / this.pageSize + 1;
}
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(Integer totalRecord) {
this.totalRecord = totalRecord;
}
}
view.RespResult
package com.spring.front.view;
import com.spring.common.enums.RCode;
import com.sun.javaws.jnl.RContentDesc;
import java.sql.ResultSet;
import java.util.List;
/**
* Package:com.spring.front.view
*
* 同一的应答结果。 controller方法的返回值都是它
*/
public class RespResult {
//应答码,自定义的数字
private int code;
//code的文字说明,一般做提示给用户看
private String msg;
//访问token
private String accessToken;
//单个数据
private Object data;
//集合数据
private List list;
//分页
private PageInfo page;
//表示成功的RespResult对象
public static RespResult ok(){
RespResult result = new RespResult();
result.setRCode(RCode.SUCC);
return result;
}
//表示失败的RespResult对象
public static RespResult fail(){
RespResult result = new RespResult();
result.setRCode(RCode.UNKOWN);
return result;
}
public void setRCode(RCode rcode){
this.code = rcode.getCode();
this.msg = rcode.getText();
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public PageInfo getPage() {
return page;
}
public void setPage(PageInfo page) {
this.page = page;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
vo.RealnameVO
package com.spring.front.vo;
/**
* Package:com.spring.front.vo
*/
public class RealnameVO {
private String phone;
private String name;
private String idCard;
private String code;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}