微信扫一扫url接口编写,微信回调接口

master
shijie 4 years ago
parent 822a0d9c1b
commit bf25ec2de9
  1. 19
      dq-financial-crms-auth/target/classes/bootstrap.properties
  2. 47
      dq-financial-crms-auth/target/classes/logback-spring.xml
  3. 10
      dq-financial-crms-auth/target/classes/mapper/crmsauth/CustomerLoginMapper.xml
  4. BIN
      dq-financial-crms-auth/target/test-classes/com/daqing/financial/crauth/DqFinancialCrmsAuthApplicationTests.class
  5. 61
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/config/WeChatConfig.java
  6. 54
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/controller/UserLoginController.java
  7. 1
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/dao/UserLoginDao.java
  8. 12
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/UserService.java
  9. 76
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/service/impl/UserServiceImpl.java
  10. 106
      dq-financial-hrms-auth/src/main/java/com/daqing/financial/hrauth/util/HttpUtils.java
  11. 5
      dq-financial-hrms-auth/src/main/resources/bootstrap.properties
  12. 3
      dq-financial-hrms-auth/src/main/resources/mapper/hrmsauth/UserLoginMapper.xml
  13. 3
      dq-govern-gateway/src/main/resources/jwt.properties

@ -1,19 +0,0 @@
#·þÎñÃû³Æ
spring.application.name=dq-financial-crms
#ÅäÖÃÖÐÐĵØÖ·
spring.cloud.nacos.config.server-addr=192.168.31.142:8848
spring.cloud.nacos.config.namespace=37d72d30-3178-4173-8b5e-269a23355ed9
#spring.cloud.nacos.config.group=prod
spring.cloud.nacos.config.ext-config[0].data-id=datasource.yml
spring.cloud.nacos.config.ext-config[0].group=dev
spring.cloud.nacos.config.ext-config[0].refresh=true
spring.cloud.nacos.config.ext-config[1].data-id=mybatis.yml
spring.cloud.nacos.config.ext-config[1].group=dev
spring.cloud.nacos.config.ext-config[1].refresh=true
spring.cloud.nacos.config.ext-config[2].data-id=other.yml
spring.cloud.nacos.config.ext-config[2].group=dev
spring.cloud.nacos.config.ext-config[2].refresh=true

@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--定义日志文件的存储地址,使用绝对路径-->
<property name="LOG_HOME" value="d:/logs/daqing/crms_auth"/>
<!-- Console 输出设置 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<charset>utf8</charset>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<fileNamePattern>${LOG_HOME}/crms_auth.%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!-- 异步输出 -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
<discardingThreshold>0</discardingThreshold>
<!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
<queueSize>512</queueSize>
<!-- 添加附加的appender,最多只能添加一个 -->
<appender-ref ref="FILE"/>
</appender>
<logger name="org.apache.ibatis.cache.decorators.LoggingCache" level="DEBUG" additivity="false">
<appender-ref ref="CONSOLE"/>
</logger>
<logger name="org.springframework.boot" level="DEBUG"/>
<root level="info">
<!--<appender-ref ref="ASYNC"/>-->
<appender-ref ref="FILE"/>
<appender-ref ref="CONSOLE"/>
</root>
</configuration>

@ -1,10 +0,0 @@
<?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.daqing.financial.crauth.dao.CustomerLoginDao">
<select id="getCustomer" parameterType="string" resultType="com.daqing.framework.domain.crms.CustomerEntity">
SELECT phone,password FROM crms_customer WHERE phone = #{phone}
</select>
</mapper>

@ -0,0 +1,61 @@
package com.daqing.financial.hrauth.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 微信配置类
*/
@Configuration
@PropertySource(value="classpath:bootstrap.properties")
@Data
public class WeChatConfig {
/**
* 公众号appid
*/
//@Value("${wxpay.appid}")
//private String appId;
/**
* 公众号秘钥
*/
//@Value("${wxpay.appsecret}")
//private String appsecret;
/**
* 开放平台appid
*/
@Value("${wxopen.appid}")
private String openAppid;
/**
* 开放平台appsecret
*/
@Value("${wxopen.appsecret}")
private String openAppsecret;
/**
* 开放平台回调url
*/
@Value("${wxopen.redirect_url}")
private String openRedirectUrl;
/**
* 微信开放平台二维码连接
*/
private String OPEN_QRCODE_URL= "https://open.weixin.qq.com/" +
"connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect";
/**
* 开放平台获取access_token地址
*/
private String OPEN_ACCESS_TOKEN_URL="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
/**
* 获取用户信息
*/
private String OPEN_USER_INFO_URL ="https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
}

@ -1,18 +1,26 @@
package com.daqing.financial.hrauth.controller; package com.daqing.financial.hrauth.controller;
import com.daqing.financial.hrauth.UserLoginControllerApi; import com.daqing.financial.hrauth.UserLoginControllerApi;
import com.daqing.financial.hrauth.config.WeChatConfig;
import com.daqing.financial.hrauth.service.UserLoginService; import com.daqing.financial.hrauth.service.UserLoginService;
import com.daqing.financial.hrauth.service.UserService;
import com.daqing.framework.domain.hrms.UserEntity;
import com.daqing.framework.domain.hrms.request.LoginRequest; import com.daqing.framework.domain.hrms.request.LoginRequest;
import com.daqing.framework.domain.hrms.request.ResetPwdRequest; import com.daqing.framework.domain.hrms.request.ResetPwdRequest;
import com.daqing.framework.domain.hrms.request.UpdatePwdRequest; import com.daqing.framework.domain.hrms.request.UpdatePwdRequest;
import com.daqing.framework.domain.hrms.request.UserLoginRequest; import com.daqing.framework.domain.hrms.request.UserLoginRequest;
import com.daqing.framework.model.response.ResponseResult; import com.daqing.framework.model.response.ResponseResult;
import com.daqing.framework.util.JwtUtils;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/** /**
@ -26,6 +34,10 @@ public class UserLoginController implements UserLoginControllerApi {
@Autowired @Autowired
private UserLoginService userLoginService; private UserLoginService userLoginService;
@Autowired
private WeChatConfig weChatConfig;
@Autowired
private UserService userService;
@PostMapping("/loginSuccess") @PostMapping("/loginSuccess")
public String loginSuccess(){ public String loginSuccess(){
@ -77,4 +89,46 @@ public class UserLoginController implements UserLoginControllerApi {
boolean result = userLoginService.updatePwd(user); boolean result = userLoginService.updatePwd(user);
return result ? ResponseResult.SUCCESS() : ResponseResult.FAIL(); return result ? ResponseResult.SUCCESS() : ResponseResult.FAIL();
} }
/**
* 拼装微信扫一扫登录url
* accessPage是指用户当前所在的页面就是用户扫码时当前所在页面
* @return
*/
@GetMapping("wxLoginUrl")
@ResponseBody
public ResponseResult loginUrl(@RequestParam(value = "accessPage",required = true)String accessPage) throws UnsupportedEncodingException {
String redirectUrl = weChatConfig.getOpenRedirectUrl(); //获取开放平台重定向地址,就是用户扫完码微信回调我们的地址
String callbackUrl = URLEncoder.encode(redirectUrl,"GBK"); //进行编码
String qrcodeUrl = String.format(weChatConfig.getOPEN_QRCODE_URL(),weChatConfig.getOpenAppid(),callbackUrl,accessPage);
return ResponseResult.SUCCESS(qrcodeUrl);
}
/**
* 微信扫码登录用户确认授权后微信回调我们服务器的接口
* 这个接口里的逻辑应该是拿到微信回传的授权code码调用微信的服务获取access_token
* 获取的access_token的返回值里有openId用openId再次调微信服务去拿用户的信息
* @param code
* @param state 用户扫码时当前所在页面
* @param response
* @throws IOException
*/
@GetMapping("/user/callback")
public void wechatUserCallback(@RequestParam(value = "code",required = true) String code,
String state, HttpServletResponse response) throws IOException {
UserEntity user = userService.saveWeChatUser(code);
if(user != null){
long times = 86400;
//生成jwt
String token = JwtUtils.createJWT(user.getId()+"","token", times);
// state 当前用户的页面地址,需要拼接 http:// 这样才不会站内跳转
response.sendRedirect(state+"?token="+token);
//response.sendRedirect(state+"?token="+token+"&head_img="+user.getHeadImg()+"&name="+URLEncoder.encode(user.getName(),"UTF-8"));
}
}
} }

@ -19,4 +19,5 @@ public interface UserLoginDao extends BaseMapper<UserEntity> {
UserEntity login(LoginRequest loginRequest); UserEntity login(LoginRequest loginRequest);
UserEntity selectByPhoneAccount(String phoneAccount); UserEntity selectByPhoneAccount(String phoneAccount);
UserEntity findByOpenid(String openId);
} }

@ -0,0 +1,12 @@
package com.daqing.financial.hrauth.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.daqing.framework.domain.hrms.UserEntity;
/**
* @auther River
* @date 2020/9/22 15:00
*/
public interface UserService extends IService<UserEntity> {
UserEntity saveWeChatUser(String code);
}

@ -0,0 +1,76 @@
package com.daqing.financial.hrauth.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daqing.financial.hrauth.config.WeChatConfig;
import com.daqing.financial.hrauth.dao.UserLoginDao;
import com.daqing.financial.hrauth.service.UserService;
import com.daqing.financial.hrauth.util.HttpUtils;
import com.daqing.framework.domain.hrms.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
@Service
public class UserServiceImpl extends ServiceImpl<UserLoginDao, UserEntity> implements UserService {
@Autowired
private WeChatConfig weChatConfig;
@Resource
private UserLoginDao userMapper;
@Override
public UserEntity saveWeChatUser(String code) {
String accessTokenUrl = String.format(weChatConfig.getOPEN_ACCESS_TOKEN_URL(),weChatConfig.getOpenAppid(),weChatConfig.getOpenAppsecret(),code);
//获取access_token
Map<String ,Object> baseMap = HttpUtils.doGet(accessTokenUrl);
if(baseMap == null || baseMap.isEmpty()){ return null; }
String accessToken = (String)baseMap.get("access_token");
String openId = (String) baseMap.get("openid");
UserEntity dbUser = userMapper.findByOpenid(openId);
if(dbUser!=null) { //更新用户,直接返回
return dbUser;
}
//获取用户基本信息
String userInfoUrl = String.format(weChatConfig.getOPEN_USER_INFO_URL(),accessToken,openId);
Map<String ,Object> baseUserMap = HttpUtils.doGet(userInfoUrl);
if(baseUserMap == null || baseUserMap.isEmpty()){
return null;
}
/* String nickname = (String)baseUserMap.get("nickname");
Double sexTemp = (Double) baseUserMap.get("sex");
int sex = sexTemp.intValue();
String province = (String)baseUserMap.get("province");
String city = (String)baseUserMap.get("city");
String country = (String)baseUserMap.get("country");
String headimgurl = (String)baseUserMap.get("headimgurl");
StringBuilder sb = new StringBuilder(country).append("||").append(province).append("||").append(city);
String finalAddress = sb.toString();
try {
//解决乱码
nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
UserEntity user = new UserEntity();
user.setWechatId(openId);
user.setCreateTime(new Date());
userMapper.insert(user);
return user;
}
}

@ -0,0 +1,106 @@
package com.daqing.financial.hrauth.util;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.HashMap;
import java.util.Map;
/**
* 封装http get post
*/
public class HttpUtils {
private static final Gson gson = new Gson();
/**
* get方法
* @param url
* @return
*/
public static Map<String,Object> doGet(String url){
Map<String,Object> map = new HashMap<>();
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) //连接超时
.setConnectionRequestTimeout(5000)//请求超时
.setSocketTimeout(5000)
.setRedirectsEnabled(true) //允许自动重定向
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
String jsonResult = EntityUtils.toString( httpResponse.getEntity());
map = gson.fromJson(jsonResult,map.getClass());
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
httpClient.close();
}catch (Exception e){
e.printStackTrace();
}
}
return map;
}
/**
* 封装post
* @return
*/
public static String doPost(String url, String data,int timeout){
CloseableHttpClient httpClient = HttpClients.createDefault();
//超时设置
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout) //连接超时
.setConnectionRequestTimeout(timeout)//请求超时
.setSocketTimeout(timeout)
.setRedirectsEnabled(true) //允许自动重定向
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type","text/html; chartset=UTF-8");
if(data != null && data instanceof String){ //使用字符串传参
StringEntity stringEntity = new StringEntity(data,"UTF-8");
httpPost.setEntity(stringEntity);
}
try{
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpResponse.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(httpEntity);
return result;
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
httpClient.close();
}catch (Exception e){
e.printStackTrace();
}
}
return null;
}
}

@ -27,6 +27,11 @@ spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0 spring.redis.jedis.pool.min-idle=0
#微信开放平台配置
wxopen.appid=wx3b7bca679da34921
wxopen.appsecret=c8de113c18052b4e2173d913511e486d
#回调地址
wxopen.redirect_url=http://www.occupationlab.com/apiHrmsAuth/hrms/auth/userlogin/user/callback
# 正式环境(prod) # 正式环境(prod)
#spring.application.name=dq-financial-hrms-auth #spring.application.name=dq-financial-hrms-auth

@ -37,5 +37,8 @@
<select id="selectByPhoneAccount" resultType="com.daqing.framework.domain.hrms.UserEntity"> <select id="selectByPhoneAccount" resultType="com.daqing.framework.domain.hrms.UserEntity">
SELECT id,account,password FROM hrms_user WHERE phone_account = #{phoneAccount} SELECT id,account,password FROM hrms_user WHERE phone_account = #{phoneAccount}
</select> </select>
<select id="findByOpenid" parameterType="string" resultType="com.daqing.framework.domain.hrms.UserEntity">
select id from hrms_user where wechat_id = #{openId}
</select>
</mapper> </mapper>

@ -4,4 +4,5 @@ jwt.ignoreUrlList=/apiHrmsAuth/hrms/auth/userlogin/getBackPwd,\
/api-crms/sweagger-ui.html,\ /api-crms/sweagger-ui.html,\
/api-crms/crms/customer/excelTemplate,\ /api-crms/crms/customer/excelTemplate,\
/api-crms/crms/customer/excelExport,\ /api-crms/crms/customer/excelExport,\
/api-crms/crms/customer/excelImport /api-crms/crms/customer/excelImport,\
/apiHrmsAuth/hrms/auth/userlogin/wxLoginUrl
Loading…
Cancel
Save