package cn.itsource.wechat.controller;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itsource.wechat.util.HttpClientUtils;
import cn.itsource.wechat.util.WeixinUtils;
import com.alibaba.fastjson.JSONObject;
@WebFilter("/*")
public class WeixinAuthFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest hRequest = (HttpServletRequest) request;
HttpServletResponse hResponse = (HttpServletResponse) response;
//如果session中已经存在微信号了,就不用获取了,否则要获取,获取到以后要存放sesion
String openId = (String) hRequest.getSession().getAttribute("openId");
if (openId == null)
{
String agent = hRequest.getHeader("User-Agent");
//只有在微信端才做里面的操作
if (agent != null && agent.toLowerCase().indexOf("micromessenger") >= 0)
{
String code = request.getParameter("code");
String state = request.getParameter("state");
//如果code不为空,scope为base,scope为userInfo代表用户已经同意
if (code != null && state != null && state.equals("1"))
{
System.out.println("1111111111111");
// 通过Code获取openid来进行授权
String url = WeixinUtils.AUTH_GET_OID.replace("APPID", WeixinUtils.APPID)
.replace("SECRET", WeixinUtils.SECRET)
.replace("CODE", code);
String json = HttpClientUtils.httpGet(url);
String openid = JSONObject.parseObject(json).getString("openid");
hRequest.getSession().setAttribute("openId", openid);
System.out.println(openid+"jjjjjjjjjjjjjjj");
}
else
{
System.out.println("2222222222222222");
//发送用户同意的请求
String path = hRequest.getRequestURL().toString();
String query = hRequest.getQueryString();
if (query != null)
{
path = path + "?" + query;
}
System.out.println(path);
String uri = WeixinUtils.AUTH_URL.replace("APPID", WeixinUtils.APPID)
.replace("REDIRECT_URI", URLEncoder.encode(path, "UTF-8"))
.replace("SCOPE", "snsapi_userinfo").replace("STATE", "1");
hResponse.sendRedirect(uri);
return;
}
}
}
chain.doFilter(hRequest, hResponse);
}
@Override
public void destroy() {
}
}
获取微信号的工具类
最新推荐文章于 2024-03-10 16:20:33 发布