微信web开发获取用户openid

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder"%>
<%@ page import="com.geong.util.HttpUtil"%>
<%@ page import="com.geong.util.PropertiesUtil"%>
<%@ page import="com.geong.util.GetWechatParmas"%>
<%@ page import="javax.xml.ws.Response"%>
<%@ page import="net.sf.json.JSONObject" %>
<%
//需要配置跳转地址
String jumpUrl =request.getContextPath()+"/page/story/storyindex.jsp";
//以下为自动处理,不需要更改
String code = request.getParameter("code");
String rpath = PropertiesUtil.getProperty("yu")+request.getRequestURI();
String oauth2Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+PropertiesUtil.getProperty("appid")
+"&redirect_uri="+URLEncoder.encode(rpath,"UTF-8")+"&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
if(code==null){
response.sendRedirect(oauth2Url);
}else{
String url  =  "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+PropertiesUtil.getProperty("appid")
+"&secret="+PropertiesUtil.getProperty("secret")+"&code="+code+"&grant_type=authorization_code";
String openidResult = HttpUtil.get(url,true);
  JSONObject fromObjectopenid = JSONObject.fromObject(openidResult.toString());
  if(fromObjectopenid.toString().indexOf("openid")>-1){
  String openid = fromObjectopenid.get("openid").toString(); 
session.setAttribute("openid",openid);
response.sendRedirect(jumpUrl);
  }else{
  response.sendRedirect(oauth2Url);
  }
}
%>


  • 发表于 2017-09-12 13:18
  • 阅读 ( 20554 )
  • 分类:Java基础

1 条评论

请先 登录 后评论
不写代码的码农
Leo

1 篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除