1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token、openid
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
在微信开发平台里需要配置 白名单和授权目录
snsapi_base: 到第二步就结束了,获取到openid,其他操作在这个基础上(比如记录该用户访问时间次数信息)
snsapi_userinfo: 获取openid和用户资料(昵称、头像、国、省、城市、性别、权限)
controller
@GetMapping("/getUserInfoByWx")
@ApiOperation("网页授权回调地址")
public String getOpenId(HttpServletRequest request, HttpServletResponse response) {
String appid = props.getStr("appId");
String secret = props.getStr("appSecret");
String code = request.getParameter("code");//授权随机返回的唯一的code,用于获取授权access_token
String state = request.getParameter("state");//授权返回的标记
weixinutils weixinutils = new weixinutils();
//JedisUtil.setObject(accessTokey, one, 60 * 60 * 24 * 30);
// String accesstokens = (String) JedisUtil.getObject(accessToken);
Map<String, String> data = weixinutils.getUserInfoAccessToken(code, appid, secret);//获取用户openid和授权access_token
String openid = data.get("openid");
String access_token = data.get("access_token");
Map<String, String> map = weixinutils.getAutoUserInfo(access_token, openid);
//根据openid获取用户是不是已经存在,存在更新用户头像,不存在就保存用户信息
QueryWrapper<ZcWeixin> en = new QueryWrapper<>();
en.eq("userOpenId",openid);
int count = zcWeixinService.count(en);
if(count!=0){
//更新用户信息
ZcWeixin one = zcWeixinService.getOne(en);
one.setUserHead((String)map.get("headimgurl"));
one.setUserNickName((String)map.get("nickname"));
zcWeixinService.updateById(one);
}else{
//插入新用户
ZcWeixin zcUser = new ZcWeixin();
zcUser.setUserHead((String)map.get("headimgurl"));
zcUser.setUserNickName((String)map.get("nickname"));
zcUser.setCreateTime(LocalDateTime.now());
zcUser.setUserOpenId(openid);
zcWeixinService.save(zcUser);
}
request.setAttribute("openid", openid);
request.setAttribute("state", state);
return "user/wei_xin_render";
}
跳转的前端网页需要后台建立一个jsp页面,然后跳转到前端的页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<input type="hidden" id="openid" value="${requestScope.openid}"/>
<input type="hidden" id="state" value="${requestScope.state}"/>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
var openid = $("#openid").val();
var state = $("#state").val();
window.location.href="http://dcdev5.natapp1.cc/前端项目名称/index.html?openid="+openid+"&state="+state;
})
</script>
</body>
</html>
工具类
import java.util.HashMap;
import java.util.Map;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class weixinutils {
/**
* @auther: Zww
* 功能描述:
* @param: 获取全局的accessToken
* @return:
* @date: 2019/5/28 15:58
*/
public static Map<String, String> getAccessToken(String wx_appid, String wx_appsecret) {
Map<String, String> data = new HashMap();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ wx_appid + "&secret=" + wx_appsecret;
JsonObject accessTokenInfo = null;
try {
Gson token_gson = new Gson();
String result = HttpUtil.get(url);
accessTokenInfo = token_gson.fromJson(result, JsonObject.class);
data.put("access_token", accessTokenInfo.get("access_token").toString().replaceAll("\"", ""));
data.put("expires_in", accessTokenInfo.get("expires_in").toString().replaceAll("\"", ""));
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
/**
* @auther: Zww
* 功能描述:
* @param: 获取授权AccessToken
* @return:
* @date: 2019/5/28 15:39
*/
public static Map<String, String> getUserInfoAccessToken(String code,String appid,String AppSecret) {
JsonObject object = null;
Map<String, String> data = new HashMap<>();
String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appid, AppSecret, code);
String result = HttpUtil.get(url);
Gson token_gson = new Gson();
object = token_gson.fromJson(result, JsonObject.class);
data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
return data;
}
/**网页授权获取用户信息
* 获取用户信息
*
* @param accessToken 网页授权获取的 token
* @param openId
* @return
*/
public static Map<String, String> getAutoUserInfo(String accessToken, String openId) {
Map<String, String> data = new HashMap();
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
JsonObject userInfo = null;
try {
String result = HttpUtil.get(url);
Gson token_gson = new Gson();
userInfo = token_gson.fromJson(result, JsonObject.class);
data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
data.put("sex", userInfo.get("sex").toString().replaceAll("\"", ""));
data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
/**
* 获取jsapi_ticket
*
* @return
*/
public static Map<String, String> getJsApiTicket(String accessToken) {
Map<String, String> data = new HashMap();
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";
JsonObject jsApiTicket = null;
try {
String result = HttpUtil.get(url);
Gson token_gson = new Gson();
jsApiTicket = token_gson.fromJson(result, JsonObject.class);
data.put("ticket", jsApiTicket.get("ticket").toString().replaceAll("\"", ""));
data.put("expires_in", jsApiTicket.get("expires_in").toString().replaceAll("\"", ""));
} catch (Exception ex) {
ex.printStackTrace();
}
return data;
}
}