微信小程序之获取用户基本信息
一、使用Redis存储access-token
package com.qfjy.project.weixin.api.accessToken;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class AccessTokenRedis {
private static String REDIS_ACCESS_TOKEN_KEY="wexin:access_token";
@Autowired
private RedisTemplate<String,Object> redisTemplate;
public String getAccessTokenValue(){
if(redisTemplate.hasKey(REDIS_ACCESS_TOKEN_KEY)){
return (String) redisTemplate.opsForValue().get(REDIS_ACCESS_TOKEN_KEY);
}else{
redisTemplate.opsForValue().set(REDIS_ACCESS_TOKEN_KEY, this.getAccessTokenVal());
redisTemplate.expire(REDIS_ACCESS_TOKEN_KEY, 2, TimeUnit.HOURS);
}
return null;
}
private static String WERXIN_ACCESS_TOKEN_GET_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private String getAccessTokenVal(){
String path=WERXIN_ACCESS_TOKEN_GET_URL.replace("APPID", MenuManager.appId).replace("APPSECRET", MenuManager.appSecret);
JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);
return jsonObject.getString("access_token");
}
}
二、调用微信服务器获取信息
package com.qfjy.project.weixin.api.UserInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.api.accessToken.AccessTokenRedis;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class UserInfoUtil {
@Autowired
private AccessTokenRedis accessTokenRedis;
@Autowired
private WeiUserService weiUserService;
public void weixinUserInfoUtil(String openid){
JSONObject jsonObject=this.getWeixinUserByOpenid(openid);
WeiUser weiUser=this.getJSONObjectConvertWeiUser(jsonObject);
int num=this.addWeiUser(weiUser);
}
private static String WEIXIN_API_GET_USER_INFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
public JSONObject getWeixinUserByOpenid(String openid){
String url = WEIXIN_API_GET_USER_INFO.replace("ACCESS_TOKEN", accessTokenRedis.getAccessTokenValue()).replace("OPENID", openid);
JSONObject jsonObject = WeixinUtil.httpRequest(url,"GET", null);
log.info("获取用户基本信息"+jsonObject.toString());
return jsonObject;
}
public WeiUser getJSONObjectConvertWeiUser(JSONObject jsonObject){
ObjectMapper objectMapper=new ObjectMapper();
WeiUser weiUser=new WeiUser();
try {
weiUser= objectMapper.readValue(jsonObject.toString(),WeiUser.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return weiUser;
}
public int addWeiUser(WeiUser weiUser){
int num= weiUserService.insertSelective(weiUser);
log.info("收集到微信的个人信息存入到数据库"+num);
return num;
}
}
Quath的使用
package com.qfjy.project.ouath;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
@RequestMapping("weixin")
@Controller
@Slf4j
public class WeiXinOuath {
@GetMapping("ouath")
public void ouath(HttpServletResponse response)throws IOException {
String url="http://njqfjy.natapp1.cc/weixin/invoke";
url= URLEncoder.encode(url,"UTF-8");
String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.appId+
"&redirect_uri=" +url+
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=java2101" +
"#wechat_redirect";
response.sendRedirect(path);
}
@RequestMapping("invoke")
public String invoke(HttpServletRequest request){
String code=request.getParameter("code");
String state=request.getParameter("state");
String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" +MenuManager.appId+
"&secret=" + MenuManager.appSecret+
"&code=" +code+
"&grant_type=authorization_code";
JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);
log.info(jsonObject.toString());
String access_token=jsonObject.getString("access_token");
String openid=jsonObject.getString("openid");
String url="https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" +access_token+
"&openid=" +openid+
"&lang=zh_CN";
JSONObject jsonObject1= WeixinUtil.httpRequest(url, "GET", null);
request.setAttribute("jsonObj",jsonObject1);
return "Oauth";
}
}
package com.qfjy.project.ouath;
import com.qfjy.entity.po.User;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.api.UserInfo.UserInfoUtil;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
@RequestMapping("weixinMenu")
@Slf4j
@Controller
public class WeixinMenuOauth {
@Autowired
private WeiUserService weiUserService;
@Autowired
private UserInfoUtil userInfoUtil;
@Autowired
private UserService userService;
@GetMapping("userInfo")
public void ouath(HttpServletResponse response)throws IOException {
String url=MenuManager.REAL_URL+"weixinMenu/userInfoInvoke";
url= URLEncoder.encode(url,"UTF-8");
String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.appId+
"&redirect_uri=" +url+
"&response_type=code" +
"&scope=snsapi_base" +
"&state=java2101" +
"#wechat_redirect";
response.sendRedirect(path);
}
@RequestMapping("userInfoInvoke")
public String invoke(HttpServletRequest request){
String code=request.getParameter("code");
String state=request.getParameter("state");
String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" +MenuManager.appId+
"&secret=" + MenuManager.appSecret+
"&code=" +code+
"&grant_type=authorization_code";
JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);
log.info(jsonObject.toString());
String access_token=jsonObject.getString("access_token");
String openid=jsonObject.getString("openid");
WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);
if(weiUser==null){
log.error("系统中未收集到该用户信息"+openid);
userInfoUtil.weixinUserInfoUtil(openid);
weiUser=weiUserService.selectWeiUserByOpenid(openid);
}
User user= userService.selectUserByWid(weiUser.getId());
if(user==null){
request.setAttribute("wid", weiUser.getId());
request.setAttribute("openid", weiUser.getOpenid());
return "weixin/user/login";
}else{
request.setAttribute("user", user);
return "weixin/user/userInfo";
}
}
@GetMapping("meetingPub")
public void meetingPub(HttpServletResponse response)throws IOException {
String url=MenuManager.REAL_URL+"weixinMenu/meetingPubInvoke";
url= URLEncoder.encode(url,"UTF-8");
String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.appId+
"&redirect_uri=" +url+
"&response_type=code" +
"&scope=snsapi_base" +
"&state=java2101" +
"#wechat_redirect";
response.sendRedirect(path);
}
@RequestMapping("meetingPubInvoke")
public String meetingPubInvoke(HttpServletRequest request){
String code=request.getParameter("code");
String state=request.getParameter("state");
String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" +MenuManager.appId+
"&secret=" + MenuManager.appSecret+
"&code=" +code+
"&grant_type=authorization_code";
JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);
log.info(jsonObject.toString());
String access_token=jsonObject.getString("access_token");
String openid=jsonObject.getString("openid");
WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);
if(weiUser==null){
log.error("系统中未收集到该用户信息"+openid);
userInfoUtil.weixinUserInfoUtil(openid);
weiUser=weiUserService.selectWeiUserByOpenid(openid);
}
User user= userService.selectUserByWid(weiUser.getId());
if(user==null){
request.setAttribute("wid", weiUser.getId());
request.setAttribute("openid", weiUser.getOpenid());
return "weixin/user/login";
}else{
if(user.getRid()==1){
request.setAttribute("uid", user.getId());
return "weixin/meetingPub/meetingPubAdd";
}
else if(user.getRid()==2){
return "unauth";
}
return "unauth";
}
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Oauth2.0页面</title>
<!-- 引入 jQuery Mobile 样式 -->
<link rel="stylesheet" href="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.css">
<!-- 引入 jQuery 库 -->
<script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- 引入 jQuery Mobile 库 -->
<script src="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="https://cdn.bootcss.com/jquery-mobile/1.4.5/jquery.mobile.theme.css" rel="stylesheet">
<style type="text/css">
body {
font-family:"微软雅黑,Arial";
font-size:18px;
padding:0px;
margin:0 auto;
}
.font-blue{
color:#4E90C7!important;
}
.input-lightblue{
background-color: #E5F2FD!important;
}
.font-label{
color: black!important;
font-size: 19px!important;
}
</style>
</head>
<body>
<div data-role="page" id="pageMain" style="">
<div data-role="header" style="background-color: #4E90C7;" data-position="fixed">
<a href="#" data-icon="back" data-role="button">返回</a>
<h1>个人信息</h1>
<a href="#" data-role="button" data-icon="home">主页</a>
</div>
<div data-role="content" style="padding: 0;text-align:center;width: 100%;line-height:60px!important" >
<br/><br/>
<div >
<img th:src="${jsonObj.headimgurl}" style="border-radius:25px;"src="http://thirdwx.qlogo.cn/mmopen/mzWlopn7rjMPaUOSRkZw7K4IGGyPSLWYKNtkibibkTgBAkicddl5icj6GIOaxu2DiaecymXmECE6nxQ7vxSRdFnnlMoVo1fQa4cvN/132">
</div>
<div style="float: left;color: black;font-size:20px;width:auto;max-width:40%;padding-left: 15px;white-space: nowrap;overflow:hidden;text-overflow:ellipsis;text-algin:left;">
<span style="font-size:28px;color:#E57330" th:text="${jsonObj.nickname}">微信名称</span>
</div>
<div style="text-align: right;padding-right:10px;white-space: nowrap;">
<font style="font-size:28px;color:#E57330">
<span th:text="${jsonObj.city}">城市</span>/<span th:text="${jsonObj.province}">省份</span>
/<span th:text="${jsonObj.province}">国家</span>
</font>
</div>
</div>
</div>
</body>
</html>
下一节,获取到用户,更新用户信息