wangh_branch
王壕 3 years ago
parent f556daac82
commit e9bd79b231

@ -27,6 +27,62 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- http请求工具包依赖 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<!--base64加密解密-->
<!--shiro依赖和缓存-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!--简化代码的工具包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--mybatis-plus的springboot支持-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -1,9 +1,14 @@
package com.example.demo; package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication @SpringBootApplication
@ComponentScan("com.example.demo.controller")
@MapperScan("com.example.demo.mapper")
public class DemoApplication { public class DemoApplication {
public static void main(String[] args) { public static void main(String[] args) {

@ -0,0 +1,107 @@
package com.example.demo.common;
/**
* @Description:
* ios
* 使list
*
* 200
* 500msg
* 501beanmap
* 502token
* 555
*/
public class GlobalResult {
// 响应业务状态
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
private String ok; // 不使用
public static GlobalResult build(Integer status, String msg, Object data) {
return new GlobalResult(status, msg, data);
}
public static GlobalResult ok(Object data) {
return new GlobalResult(data);
}
public static GlobalResult ok() {
return new GlobalResult(null);
}
public static GlobalResult errorMsg(String msg) {
return new GlobalResult(500, msg, null);
}
public static GlobalResult errorMap(Object data) {
return new GlobalResult(501, "error", data);
}
public static GlobalResult errorTokenMsg(String msg) {
return new GlobalResult(502, msg, null);
}
public static GlobalResult errorException(String msg) {
return new GlobalResult(555, msg, null);
}
public GlobalResult() {
}
public GlobalResult(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public GlobalResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
public Boolean isOK() {
return this.status == 200;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
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;
}
public String getOk() {
return ok;
}
public void setOk(String ok) {
this.ok = ok;
}
}

@ -0,0 +1,135 @@
package com.example.demo.common;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}

@ -0,0 +1,78 @@
package com.example.demo.common;
;/**
* Create by eval on 2019/3/20
*/
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName WechatUtil
* @Description TODO
* @Author eval
* @Date 9:44 2019/3/20
* @Version 1.0
*/
public class WechatUtil {
public static JSONObject getSessionKeyOrOpenId(String code) {
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
Map<String, String> requestUrlParam = new HashMap<>();
// https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
//小程序appId
requestUrlParam.put("wx08c675f6ba5b2cdc", "小程序appId");
//小程序secret
requestUrlParam.put("0c28388c09ff373d391fe66d085dd39d", "小程序secret");
//小程序端返回的code
requestUrlParam.put("js_code", code);
//默认参数
requestUrlParam.put("grant_type", "authorization_code");
//发送post请求读取调用微信接口获取openid用户唯一标识
JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
return jsonObject;
}
public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
// 被加密的数据
byte[] dataByte = Base64.decode(encryptedData);
// 加密秘钥
byte[] keyByte = Base64.decode(sessionKey);
// 偏移量
byte[] ivByte = Base64.decode(iv);
try {
// 如果密钥不足16位那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyByte.length % base != 0) {
int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
keyByte = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
parameters.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
byte[] resultByte = cipher.doFinal(dataByte);
if (null != resultByte && resultByte.length > 0) {
String result = new String(resultByte, "UTF-8");
return JSON.parseObject(result);
}
} catch (Exception e) {
}
return null;
}
}

@ -1,10 +1,12 @@
package com.example.demo.controller; package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -13,6 +15,7 @@ import java.util.Map;
@RestController @RestController
@SpringBootApplication @SpringBootApplication
public class ControllerText { public class ControllerText {
@RequestMapping("getUser") @RequestMapping("getUser")
public Map<String, Object> getUser(){ public Map<String, Object> getUser(){
System.out.println("微信小程序正在调用。。。"); System.out.println("微信小程序正在调用。。。");
@ -47,4 +50,15 @@ public class ControllerText {
return "hello world"; return "hello world";
} }
@Autowired
JdbcTemplate jct;
@GetMapping("userslist")
public List<Map<String, Object>> userlist(){
String sql = "select * from user";
List<Map<String, Object>> map = jct.queryForList(sql);
System.out.println("调用sql");
return map;
}
@RequestMapping("hes")
public String get(){return "df";}
} }

@ -0,0 +1,100 @@
package com.example.demo.controller;
import com.example.demo.pojo.User;
import com.example.demo.common.GlobalResult;
import com.example.demo.mapper.UserMapper;
import com.example.demo.common.WechatUtil;
//import cn.lastwhisper.springbootwx.common.GlobalResult;
//import cn.lastwhisper.springbootwx.mapper.UserMapper;
//import cn.lastwhisper.springbootwx.pojo.User;
//import cn.lastwhisper.springbootwx.common.WechatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.UUID;
/**
* @author lastwhisper
* @desc
* @email gaojun56@163.com
*/
@Controller
public class UserController {
@Autowired
private UserMapper userMapper;
/**
*
*/
@PostMapping("wx/login")
@ResponseBody
public GlobalResult user_login(@RequestParam(value = "code", required = false) String code,
@RequestParam(value = "rawData", required = false) String rawData,
@RequestParam(value = "signature", required = false) String signature,
@RequestParam(value = "encrypteData", required = false) String encrypteData,
@RequestParam(value = "iv", required = false) String iv) {
// 用户非敏感信息rawData
// 签名signature
JSONObject rawDataJson = JSON.parseObject(rawData);
// 1.接收小程序发送的code
// 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
// 3.接收微信接口服务 获取返回的参数
String openid = SessionKeyOpenId.getString("openid");
String sessionKey = SessionKeyOpenId.getString("session_key");
// 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
if (!signature.equals(signature2)) {
return GlobalResult.build(500, "签名校验失败", null);
}
// 5.根据返回的User实体类判断用户是否是新用户是的话将用户信息存到数据库不是的话更新最新登录时间
User user = this.userMapper.selectById(openid);
// uuid生成唯一key用于维护微信小程序用户与服务端的会话
String skey = UUID.randomUUID().toString();
if (user == null) {
// 用户信息入库
String nickName = rawDataJson.getString("nickName");
String avatarUrl = rawDataJson.getString("avatarUrl");
String gender = rawDataJson.getString("gender");
String city = rawDataJson.getString("city");
String country = rawDataJson.getString("country");
String province = rawDataJson.getString("province");
user = new User();
user.setOpenId(openid);
user.setSkey(skey);
user.setCreateTime(new Date());
user.setLastVisitTime(new Date());
user.setSessionKey(sessionKey);
user.setCity(city);
user.setProvince(province);
user.setCountry(country);
user.setAvatarUrl(avatarUrl);
user.setGender(Integer.parseInt(gender));
user.setNickName(nickName);
this.userMapper.insert(user);
} else {
// 已存在,更新用户登录时间
user.setLastVisitTime(new Date());
// 重新设置会话skey
user.setSkey(skey);
this.userMapper.updateById(user);
}
//encrypteData比rowData多了appid和openid
//JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
//6. 把新的skey返回给小程序
GlobalResult result = GlobalResult.build(200, null, skey);
return result;
}
}

@ -0,0 +1,13 @@
package com.example.demo.mapper;
import com.example.demo.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @desc
*
* @author lastwhisper
* @email gaojun56@163.com
*/
public interface UserMapper extends BaseMapper<User> {
}

@ -0,0 +1,78 @@
package com.example.demo.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @author lastwhisper
* @desc
* @email gaojun56@163.com
*/
@Data
@TableName("user")
public class User {
private static final long serialVersionUID = 1L;
/**
* open_id
*/
@TableId(value = "open_id",type = IdType.INPUT)
private String openId;
/**
* skey
*/
private String skey;
/**
*
*/
@TableField("create_time")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createTime;
/**
*
*/
@TableField("last_visit_time")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date lastVisitTime;
/**
* session_key
*/
@TableField("session_key")
private String sessionKey;
/**
*
*/
@TableField("city")
private String city;
/**
*
*/
@TableField("province")
private String province;
/**
*
*/
@TableField("country")
private String country;
/**
*
*/
@TableField("avatar_url")
private String avatarUrl;
/**
*
*/
@TableField("gender")
private Integer gender;
/**
*
*/
@TableField("nick_name")
private String nickName;
}

@ -3,8 +3,12 @@ server:
spring: spring:
mvc: application:
view: name: wxlogin
prefix=/WEB-INF/jsp/:
suffix=: datasource:
jsp:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/wxlogin?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
username: root
password: root
Loading…
Cancel
Save