ylb-接口11实名认证

总览:
ylb-接口11实名认证_第1张图片
在这里插入图片描述
在web模块config包下,创建实名认证的一个配置类JdwxRealnameConfig:

package com.bjpowernode.front.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@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;
    }
}

在web模块下的resources/application.yml,添加配置信息(京东万象):(在realname)

#短信配置
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

在web模块下的vo包,创建RealnameVO类:

package com.bjpowernode.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;
    }
}

调用第三方接口,在web模块service包下创建RealnameServiceImpl类(不写接口,是因为只有一个功能):
1、使用封装的工具类HttpClientUtils接受用户响应的json数据(包括页面状态数、电话、姓名、身份证等)
2、使用fastjson解析json数据(result)
3、处理更新数据库

package com.bjpowernode.front.service;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.api.model.User;
import com.bjpowernode.api.service.UserService;
import com.bjpowernode.common.util.HttpClientUtils;
import com.bjpowernode.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;

@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<String, String> params = new HashMap<>();
        params.put("cardNo",idCard);
        params.put("realName",name);
        params.put("appkey",realnameConfig.getAppkey());
        try {
           // 得到响应的json数据
           // 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;
    }
}

其中:

1、调用第三方接口,一般为http协议接口,所以在common模块util包下,创建一个工具类HttpClientUtils:

package com.bjpowernode.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.*;

public class HttpClientUtils {

    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 设置连接超时时间,单位毫秒。
     */
    private static final Integer CONNECT_TIMEOUT = 6000;

    /**
     * 请求获取数据的超时时间(即响应时间),单位毫秒。
     */
    private static final Integer SOCKET_TIMEOUT = 6000;


    /**
     * 发送get请求;不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 发送get请求;带请求参数
     *
     * @param url    请求地址
     * @param params 请求参数集合
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 发送get请求;带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
         * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        //响应结果
        String result = "";
        try {

            // 执行请求
            httpResponse = httpClient.execute(httpGet);

            // 获取返回结果
            if (httpResponse != null && httpResponse.getStatusLine() != null) {
                if (httpResponse.getEntity() != null) {
                    result = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
                }
            }
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }

        return result;
    }

    /**
     * 发送post请求;不带请求头和请求参数
     *
     * @param url 请求地址
     * @return
     * @throws Exception
     */
    public static String doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * 发送post请求;带请求参数
     *
     * @param url    请求地址
     * @param params 参数集合
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, Object> params) throws Exception {
        return doPost(url, null, params);
    }

    /**
     * 发送post请求;带请求头和请求参数
     *
     * @param url     请求地址
     * @param headers 请求头集合
     * @param params  请求参数集合
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 设置请求头
        /*httpPost.setHeader("Cookie", "");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        packageHeader(headers, httpPost);

        // 封装请求参数
        packageParam(params, httpPost);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        String result = "";
        try {

            // 执行请求
            httpResponse = httpClient.execute(httpPost);

            // 获取返回结果
            if (httpResponse != null && httpResponse.getStatusLine() != null) {
                if (httpResponse.getEntity() != null) {
                    result = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
                }
            }

        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
        return result;
    }


    /**
     * @Title:POST请求
     * @Decription:发送POST请求,data参数只支持JSON对象(com.alibaba.fastjson.JSONObject)
     * @param url  请求地址
     * @param data 只支持JSON对象(com.alibaba.fastjson.JSONObject)
     * @return String
     */
    public static String sendPost(String url, JSONObject data) throws IOException {
        // 设置默认请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");

        return doPostByJSON(url, headers, data, ENCODING);
    }

    /**
     * @Title:POST请求
     * @param url    请求地址
     * @param params Map集合(输入参数要求为JSON对象)
     * @return String
     */
    public static String sendPost(String url, Map<String, Object> params) throws IOException {
        // 设置默认请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        // 将map转成json
        JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
        return doPostByJSON(url, headers, data, ENCODING);
    }

    /**
     * @Title POST请求
     * @param url     请求地址
     * @param headers Map集合的请求头信息
     * @param data    只支持JSON对象(com.alibaba.fastjson.JSONObject)
     * @return String
     */
    public static String sendPost(String url, Map<String, String> headers, JSONObject data) throws IOException {
        return doPostByJSON(url, headers, data, ENCODING);
    }


    /**
     * @Title POST请求(默认编码:UTF-8)
     * @param url     请求地址
     * @param headers Map集合的请求头参数
     * @param params  Map集合(输入参数为JSON对象)
     * @return String
     */
    public static String sendPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        // 将map转成json
        JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
        return doPostByJSON(url, headers, data, ENCODING);
    }

    /**
     * @Title: sendPost
     * @Description: TODO(发送post请求)
     * @author 郭鑫
     * @date 2018年5月10日 下午4:36:17
     * @param url      请求地址
     * @param headers  请求头
     * @param data     请求实体
     * @param encoding 字符集
     * @return String
     * @throws IOException
     */
    private static String doPostByJSON(String url, Map<String, String> headers, JSONObject data, String encoding) throws IOException {
        // 请求返回结果
        String resultJson = null;
        // 创建Client
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送请求,返回响应对象
        CloseableHttpResponse response = null;
        // 创建HttpPost对象
        HttpPost httpPost = new HttpPost();

        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
         * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);

        try {
            // 设置请求地址
            httpPost.setURI(new URI(url));
            // 设置请求头
            packageHeader(headers, httpPost);

            // 设置实体
            httpPost.setEntity(new StringEntity(JSON.toJSONString(data)));
            // 发送请求,返回响应对象
            response = client.execute(httpPost);
            // 获取响应状态
            int status = response.getStatusLine().getStatusCode();

            if (status != HttpStatus.SC_OK) {
                System.out.println("响应失败,状态码:" + status);
            }
            // 获取响应结果
            resultJson = EntityUtils.toString(response.getEntity(), encoding);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, client);
        }
        return resultJson;
    }

    /**
     * POST请求xml参数
     * @param url
     * @param requestDataXml
     * @return String
     */
    public static String doPostByXml(String url, String requestDataXml) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";

        try {
            //创建httpClient实例
            httpClient = HttpClients.createDefault();
            //创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            //配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000)//设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)//设置连接请求超时时间
                    .setSocketTimeout(60000)//设置读取数据连接超时时间
                    .build();
            //为httpPost实例设置配置
            httpPost.setConfig(requestConfig);
            //设置请求参数
            httpPost.setEntity(new StringEntity(requestDataXml,"UTF-8"));
            //设置请求头内容
            httpPost.addHeader("Content-Type","text/xml");

            //执行post请求得到返回对象
            response = httpClient.execute(httpPost);
            //通过返回对象获取数据
            HttpEntity entity = response.getEntity();
            //将返回的数据转换为字符串
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封装请求参数
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, Object> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封装请求参数
        if (null != params && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            for (Map.Entry<String, Object> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }




    /**
     * @Title: sendGet
     * @Description: TODO(发送get请求)
     * @author wangxy
     * @date 2018年5月14日 下午2:39:01
     * @param url      请求地址
     * @param params   请求参数
     * @param encoding 编码
     * @return String
     * @throws IOException
     */
    private static String sendGet(String url, Map<String, Object> params, String encoding) throws IOException {
        // 请求结果
        String resultJson = null;
        // 创建client
        CloseableHttpClient client = HttpClients.createDefault();
        //响应对象
        CloseableHttpResponse response = null;
        // 创建HttpGet
        HttpGet httpGet = new HttpGet();
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            // 封装参数
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addParameter(key, params.get(key).toString());
                }
            }
            URI uri = builder.build();
            // 设置请求地址
            httpGet.setURI(uri);

            //设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000)//连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)//请求超时时间
                    .setSocketTimeout(60000)//数据读取超时时间
                    .build();

            // 发送请求,返回响应对象
            response = client.execute(httpGet);
            // 获取响应状态
            int status = response.getStatusLine().getStatusCode();

            if (status != HttpStatus.SC_OK) {
                System.out.println("响应失败,状态码:" + status);
            }

            // 获取响应数据
            resultJson = EntityUtils.toString(response.getEntity(), encoding);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, client);
        }
        return resultJson;
    }


    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

2、更新实名认证信息(在api模块service包下,UserService接口添加方法):

package com.bjpowernode.api.service;

import com.bjpowernode.api.model.User;
import com.bjpowernode.api.pojo.UserAccountInfo;

public interface UserService {

    /**
     * 根据手机号查询数据
     */
    User queryByPhone(String phone);

    /*用户注册*/
    int userRegister(String phone, String password);

    /*登录*/
    User userLogin(String phone, String pword);

    /*更新实名认证信息*/
    boolean modifyRealname(String phone, String name, String idCard);

    /*获取用户和资金信息*/
    UserAccountInfo queryUserAllInfo(Integer uid);

    /*查询用户*/
    User queryById(Integer uid);
}

实现这个接口方法,在dataservice模块service包下,补充UserServiceImpl,更新实名认证信息:
1、判断三个参数都不为空(if(!StringUtils.isAnyBlank(phone,name,idCard)))
2、更新数据库实名认证的信息(编写相应的mapper)

package com.bjpowernode.dataservice.service;

import com.bjpowernode.api.model.FinanceAccount;
import com.bjpowernode.api.model.User;
import com.bjpowernode.api.pojo.UserAccountInfo;
import com.bjpowernode.api.service.UserService;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.dataservice.mapper.FinanceAccountMapper;
import com.bjpowernode.dataservice.mapper.UserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

@DubboService(interfaceClass = UserService.class,version = "1.0")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private FinanceAccountMapper financeAccountMapper;

    @Value("${ylb.config.password-salt}")
    private String passwordSalt;

    @Override
    public User queryByPhone(String phone) {
        User user = null;
        if(CommonUtil.checkPhone(phone)){
            user = userMapper.selectByPhone(phone);
        }
        return user;
    }

    /*用户注册*/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized int userRegister(String phone, String password) {
        int result = 0;//默认参数不正确
        if( CommonUtil.checkPhone(phone)
                && (password != null && password.length()==32)){

            //判断手机号在库中是否存在
            User queryUser = userMapper.selectByPhone(phone);
            if(queryUser == null){
                //注册密码的md5二次加密。 给原始的密码加盐(salt)
                String newPassword = DigestUtils.md5Hex( password + passwordSalt);

                //注册u_user
                User user = new User();
                user.setPhone(phone);
                user.setLoginPassword(newPassword);
                user.setAddTime(new Date());
                userMapper.insertReturnPrimaryKey(user);

                //获取主键user.getId()
                FinanceAccount account = new FinanceAccount();
                account.setUid(user.getId());
                account.setAvailableMoney(new BigDecimal("0"));
                financeAccountMapper.insertSelective(account);

                //成功result = 1
                result = 1;
            } else {
                //手机号存在
                result = 2;
            }
        }
        return result;
    }

    /*登录*/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User userLogin(String phone, String password) {

        User user = null;
        if( CommonUtil.checkPhone(phone) && (password != null && password.length() == 32)) {
            String newPassword = DigestUtils.md5Hex( password + passwordSalt);
            user = userMapper.selectLogin(phone,newPassword);
            //更新最后登录时间
            if( user != null){
                user.setLastLoginTime(new Date());
                userMapper.updateByPrimaryKeySelective(user);
            }
        }
        return user;
    }

    /*更新实名认证信息*/
    @Override
    public boolean modifyRealname(String phone, String name, String idCard) {
        int rows = 0;
        if(!StringUtils.isAnyBlank(phone,name,idCard)){
             rows  = userMapper.updateRealname(phone,name,idCard);
        }
        return rows > 0 ;
    }

    /*获取用户和资金信息*/
    @Override
    public UserAccountInfo queryUserAllInfo(Integer uid) {
        UserAccountInfo info = null;
        if( uid != null && uid > 0 ) {
            info  = userMapper.selectUserAccountById(uid);
        }
        return info ;
    }

    /*查询用户*/
    @Override
    public User queryById(Integer uid) {
        User user = null;
        if( uid != null && uid > 0 ){
            user = userMapper.selectByPrimaryKey(uid);
        }
        return user;
    }
}

其中:
1、更新数据库的实名认证信息(需要在dataservice模块mapper包下的UserMapper接口添加方法,并在resources/mappers/UserMapper.xml编写SQL语句):

    /*更新实名认证信息*/
    int updateRealname(@Param("phone") String phone, @Param("name") String name, @Param("idCard") String idCard);
  
  <update id="updateRealname">
    update u_user set name=#{name} , id_card = #{idCard} where phone = #{phone}
  update>

在web模块的usercontroller类下添加:(实名认证userRealname结果集)
1、验证请求参数(电话是否标准,姓名是否标准,身份证ID是否标准)
2、判断用户是否已经做过实名认证
3、发送短信验证码,下面代码没有,参考前面
4、调用第三方接口,判断认证结果

package com.bjpowernode.front.controller;

import com.bjpowernode.api.model.User;
import com.bjpowernode.api.pojo.UserAccountInfo;
import com.bjpowernode.common.enums.RCode;
import com.bjpowernode.common.util.CommonUtil;
import com.bjpowernode.common.util.JwtUtil;
import com.bjpowernode.front.service.RealnameServiceImpl;
import com.bjpowernode.front.service.SmsService;
import com.bjpowernode.front.view.RespResult;
import com.bjpowernode.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;

@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<String, Object> data = new HashMap<>();
                    data.put("uid",user.getId());
                    String jwtToken = jwtUtil.createJwt(data,120);

                    result = RespResult.ok();
                    result.setAccessToken(jwtToken);

                    Map<String,Object> 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<String,Object> 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;

    }
}

你可能感兴趣的:(ylb,java,数据库)