java微信网页授权获取用户信息以及JSSDK自定义分享等功能

接上文,项目搭建后,还需要一个配置文件,方便以后反复修改。

创建weixinProperties.properties属性文件,位置在上一节已经截图过。此处略过。


java微信网页授权获取用户信息以及JSSDK自定义分享等功能_第1张图片

第一个是申请公众号,tx给你的公众号id,第二个是公众号密码,第三个是项目域名,这个以后经常用到,可改为你自己的域名。

接下来是控制器的编写。

以一个为例:位置随便放的,为了便于管理,Controller建议放在一个包内。

ComminController.java类

import java.io.IOException;
	import java.sql.SQLException;
	import java.util.Arrays;

	import javax.annotation.Resource;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	import net.sf.json.JSONObject;

	import org.lvyouju.dao.UserDao;
	import org.lvyouju.dao.UserDaoImpl;
	import org.lvyouju.entity.SignPackage;
	import org.lvyouju.entity.User;
	import org.lvyouju.web.util.AouthUtil;
	import org.lvyouju.web.util.CommonUtil;
	import org.lvyouju.web.util.SignUtil;
	import org.lvyouju.web.util.TokenUtil;
	import org.springframework.context.ApplicationContext;
	import org.springframework.context.support.ClassPathXmlApplicationContext;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
	import org.springframework.web.bind.annotation.RequestMapping;

	@Controller
	@RequestMapping(value="/lvyouju")
	public class CommonController {
		static{
			TokenUtil.appid = CommonUtil.weixinProperties.getString("wx.appid");
			TokenUtil.appsecret = CommonUtil.weixinProperties.getString("wx.appsecret");

			if ("".equals(TokenUtil.appid)|| "".equals(TokenUtil.appsecret)) {
				System.out.println("appid and appsecret configuration error, please check carefully.");
			} else {
				// 启动定时获取access_token的线程
				new Thread(new TokenUtil()).start();
			}
		}
		@RequestMapping(value="/lvyou")
		public void reposition(HttpServletRequest request,HttpServletResponse response) throws IOException{
			String info=request.getParameter("info");
			if("1".equals(info)){
				response.sendRedirect(AouthUtil.aouthReposition("lvyouju/home.do","1"));
			}else if("2".equals(info)){
				response.sendRedirect(AouthUtil.aouthReposition("lvyouju/home.do","2"));
			}
		}
		@RequestMapping("/home")
	public String toGeermoList(HttpServletRequest request,HttpServletResponse response,Model model) throws SQLException{
		SignPackage signPackage= SignUtil.sign(request);
		@SuppressWarnings("resource")
		ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
		//UserDao userDao = app.getBean("userDao", UserDao.class);
               String state = request.getParameter("state");
               JSONObject json = CommonUtil.getUserInfo(request);
               if(json.containsKey("errcode")){
                    response.sendRedirect(AouthUtil.aouthReposition("lvyouju/home.do",state));
               }else{
                    String openid = json.getString("openid");//获取到的用户openid
                    String refresh_token = json.getString("refresh_token");
                    String access_token = json.getString("access_token");
                    String checkTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
                    JSONObject checkResult = CommonUtil.httpRequest(checkTokenUrl, "GET", null);//检测access_token是否失效
                    if(!"ok".equals(checkResult.getString("errmsg"))){
                        String refreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
                    +CommonUtil.weixinProperties.getString("wx.appid")+"&grant_type=refresh_token&refresh_token="+refresh_token;
                        json = CommonUtil.httpRequest(refreshUrl, "GET", null);
                        refresh_token = json.getString("refresh_token");
                        access_token = json.getString("access_token");
                    }
                    String userInfoURL = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+
                                         "&openid="+openid+"&lang=zh_CN";
                    JSONObject userInfoJson = CommonUtil.httpRequest(userInfoURL, "GET", null);//获取到的用户详细信息
                    request.setAttribute("signPackage", signPackage);
		    return "pages/home/homeList";
        	}
       }
接下来是网页授权oAuth2.0的代码:

其实也不难,关键是对官方文档的理解:

AouthUtil.java类

public class AouthUtil {
	//aouth2.0重定向静默授权
	public static String aouthReposition(String requestUrl,String state){
		StringBuilder sb = new StringBuilder();
		sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
		String appid = CommonUtil.weixinProperties.getString("wx.appid");
		sb.append(appid);
		sb.append("&redirect_uri=");
		// 获取服务器域名
		String serviceUrl = CommonUtil.weixinProperties.getString("wx.url");
		sb.append(serviceUrl);
		sb.append(requestUrl);
		// 如要获取用户详细信息snsapi_base须改为snsapi_userinfo
		sb.append("&response_type=code&scope=snsapi_userinfo&state=");
		sb.append(state);
		sb.append("#wechat_redirect");
		return sb.toString();
	}
}
CommonUtil.java类

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.ResourceBundle;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.lvyouju.entity.AccessToken;
import org.lvyouju.entity.JsapiTicket;

public class CommonUtil {
	public static ResourceBundle weixinProperties = ResourceBundle
			.getBundle("weixinProperties");
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public final static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	public static JSONObject getUserInfo(HttpServletRequest request)
			throws Exception {
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		String appid = weixinProperties.getString("wx.appid");// 读取属性配置文件
		String appsecret = weixinProperties.getString("wx.appsecret");
		// 微信官方提供的url规范
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ appid + "&secret=" + appsecret + "&code=" + code
				+ "&grant_type=authorization_code";
		JSONObject json = httpRequest(url, "GET", null);
		state=state+"2";
		json.put("state1", state);
		return json;
	}

	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) throws Exception {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			throw ce;
		} catch (Exception e) {
			throw e;
		}
		return jsonObject;
	}

	public static AccessToken getAccessToken(String appid, String appsecret) throws Exception {
		AccessToken accessToken = null;

		String requestUrl = access_token_url.replace("APPID", appid).replace(
				"APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				accessToken = null;
			}
		}
		return accessToken;
	}

	public static JsapiTicket getJsapiTicket(String tocken) throws Exception {
		JsapiTicket jsapiTicket = null;
		String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", tocken);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		// 如果请求成功
		if (null != jsonObject) {
			try {
				jsapiTicket = new JsapiTicket();
				jsapiTicket.setTicket(jsonObject.getString("ticket"));
				jsapiTicket.setExpiresIn(jsonObject.getInt("expires_in"));
			} catch (JSONException e) {
				jsapiTicket = null;
				// 获取token失败
				e.printStackTrace();
			}
		}
		return jsapiTicket;
	}
}
到这为止,网页授权和jssdk分享的java代码部分全部写完。

接下来是网页jsp页面的书写。

你可能感兴趣的:(java,微信)