微信公众号之网页授权demo
Posted zengnansheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号之网页授权demo相关的知识,希望对你有一定的参考价值。
WXConfig.java
package com.zns.config; public class WXConfig { public final static String appId = ""; public final static String appSecret = ""; }
WXUtils.java
package com.zns.utils; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.zns.config.WXConfig; public class WXUtils { /** * 获取生成的授权URL */ public static String getAuthorizeUrl(String redirectUrl) { return String.format( "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect", WXConfig.appId, redirectUrl, "snsapi_userinfo", "state_xxx"); } /** * 根据code获取access_token、openid等信息 */ public static Map<String, String> getAccessToken(String code) { JsonObject jsonObject = null; Map<String, String> map = new HashMap(); try { String url = String.format( "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", WXConfig.appId, WXConfig.appSecret, code); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String results = EntityUtils.toString(httpEntity, "utf-8"); Gson gson = new Gson(); jsonObject = gson.fromJson(results, JsonObject.class); map.put("openid", jsonObject.get("openid").toString().replaceAll(""", "")); map.put("expires_in", jsonObject.get("expires_in").toString().replaceAll(""", "")); map.put("refresh_token", jsonObject.get("refresh_token").toString().replaceAll(""", "")); map.put("access_token", jsonObject.get("access_token").toString().replaceAll(""", "")); map.put("scope", jsonObject.get("scope").toString().replaceAll(""", "")); } catch (Exception ex) { ex.printStackTrace(); } return map; } /** * 根据accessToken、openId获取用户信息 */ public static Map<String, String> getUserInfo(String accessToken, String openId) { Map<String, String> map = new HashMap(); String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId); JsonObject jsonObject = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String response = EntityUtils.toString(httpEntity, "utf-8"); Gson gson = new Gson(); jsonObject = gson.fromJson(response, JsonObject.class); map.put("openid", jsonObject.get("openid").toString().replaceAll(""", "")); map.put("nickname", jsonObject.get("nickname").toString().replaceAll(""", "")); map.put("sex", jsonObject.get("sex").toString().replaceAll(""", "")); map.put("country", jsonObject.get("country").toString().replaceAll(""", "")); map.put("province", jsonObject.get("province").toString().replaceAll(""", "")); map.put("city", jsonObject.get("city").toString().replaceAll(""", "")); map.put("headimgurl", jsonObject.get("headimgurl").toString().replaceAll(""", "")); } catch (Exception ex) { ex.printStackTrace(); } return map; } }
WechatController.java
package com.zns.controller; import java.security.MessageDigest; import java.util.Arrays; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zns.utils.WXUtils; @Controller public class WechatController { protected static Logger logger = Logger.getLogger(WechatController.class); // 自定义 token private String token = "123456"; @RequestMapping("/handle") @ResponseBody public String index(HttpServletRequest request, HttpServletResponse response) throws Exception { // 微信加密签名 String signature = request.getParameter("signature"); // 随机字符串 String echostr = request.getParameter("echostr"); // 时间戳 String timestamp = request.getParameter("timestamp"); // 随机数 String nonce = request.getParameter("nonce"); String tmpStr = getSHA1(token, timestamp, nonce); if (tmpStr.equals(signature)) { return echostr; } else { return null; } } /** * 用SHA1算法生成安全签名 * * @param token * token * @param timestamp * 时间戳 * @param nonce * 随机字符串 * @return 安全签名 */ public String getSHA1(String token, String timestamp, String nonce) throws Exception { String[] array = new String[] { token, timestamp, nonce }; StringBuffer sb = new StringBuffer(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < array.length; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuffer hexstr = new StringBuffer(); String shaHex = ""; for (int i = 0; i < digest.length; i++) { shaHex = Integer.toHexString(digest[i] & 0xFF); if (shaHex.length() < 2) { hexstr.append(0); } hexstr.append(shaHex); } return hexstr.toString(); } // 网页授权入口 @RequestMapping("/preAuth") public void preAuth(HttpServletRequest request, HttpServletResponse response) throws Exception { String redirectUrl="http://wechat.zengnansheng.com/auth"; logger.info(WXUtils.getAuthorizeUrl(redirectUrl)); response.sendRedirect(WXUtils.getAuthorizeUrl(redirectUrl)); } // 网页授权 @RequestMapping("/auth") public String auth(HttpServletRequest request, HttpServletResponse response) throws Exception { String code=request.getParameter("code"); logger.info("code:"+code); Map<String, String> accessTokenMap = WXUtils.getAccessToken(code); String openId = accessTokenMap.get("openid"); String accessToken = accessTokenMap.get("access_token"); if (!StringUtils.isEmpty(openId)) { Map<String, String> userInfoMap = WXUtils.getUserInfo(accessToken, openId); logger.info("用户信息:"+userInfoMap); //业务处理... return "重定向到新的url"; } return "重定向到失败的url"; } }
以上是关于微信公众号之网页授权demo的主要内容,如果未能解决你的问题,请参考以下文章