微信公众号网页分享功能开发总结

    最近要做一个微信公众号页面分享功能,其中遇到了不少问题,别的先不多说了,直接上代码。

Controller层:

/**
	 * 
	 *
	 * 跳转二维码页面 .
	 *Description: 
	 *    
	 *Author: chendy
	 *Date: 2018/04/25 上午9:46:14
	 *@param session
	 *@return
	 *
*/ @RequestMapping(value="//personerErweima") public ModelAndView goErWeiMa(HttpSession session,HttpServletRequest request){ ModelAndView modelAndView = new ModelAndView(); try { UserInfoVo user = userInfoService.showUserinfoByCon(retrievalCurrentUserInfo(session).getLogId()); modelAndView.addObject("user", user); modelAndView.setViewName("/wap/userinfo/erweima");//加载页面的一些数据信息 //分享 String url = "/escq/wap/userinfo/personerErweima.html"; //当前页面的路径 String domainAddr = "http://vm3kgx.natappfree.cc"; //域名 String fenxurl=domainAddr+"/escq/wap/userinfo/logInfo/jumpJdjerweima.html"; //要分享的路径(分享出去的链接) Map params=HttpXmlClient.getShare(request,url);//获取签名 request.setAttribute("params", params); request.setAttribute("fenxurl", fenxurl); //分享结束 } catch (Exception e) { modelAndView.setViewName("wap/userinfo/login"); } return modelAndView; }
获取签名:
public class HttpXmlClient {

	@SuppressWarnings("unchecked")
	public static String getToken(){//获取access_token
		 String access_token = "";  
		    String grant_type = "client_credential";//获取access_token填写client_credential   
		   String AppId="";//第三方用户唯一凭证  测试号
		   String secret="";//第三方用户唯一凭证密钥,即appsecret  测试号 
		    //这个url链接地址和参数皆不能变  
		    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;  
		    try {  
		        URL urlGet = new URL(url);  
		        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
		        http.setRequestMethod("GET"); // 必须是get方式请求  
		        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
		        http.setDoOutput(true);  
		        http.setDoInput(true);  
		        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
		        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
		        http.connect();  
		        InputStream is = http.getInputStream();  
		        int size = is.available();  
		        byte[] jsonBytes = new byte[size];  
		        is.read(jsonBytes);  
		        String message = new String(jsonBytes, "UTF-8");  
		        Map map = (Map) JSON.parse(message);
//		        JSONObject demoJson = JSONObject.fromObject(message);  
//		        System.out.println("JSON字符串:"+demoJson);  
		        access_token = map.get("access_token");  
		        is.close();  
		    } catch (Exception e) {  
		            e.printStackTrace();  
		    }  
		    return access_token;  
	}
	
	@SuppressWarnings("unchecked")
	public static String getTicket(String access_token) {  
	    String ticket = null;  
	    String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";//这个url链接和参数不能变  
	    try {  
	        URL urlGet = new URL(url);  
	        HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();  
	        http.setRequestMethod("GET"); // 必须是get方式请求  
	        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
	        http.setDoOutput(true);  
	        http.setDoInput(true);  
	        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒  
	        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒  
	        http.connect();  
	        InputStream is = http.getInputStream();  
	        int size = is.available();  
	        byte[] jsonBytes = new byte[size];  
	        is.read(jsonBytes);  
	        String message = new String(jsonBytes, "UTF-8");  
	        Map map = (Map) JSON.parse(message);
//	        JSONObject demoJson = JSONObject.fromObject(message);  
//	        System.out.println("JSON字符串:"+demoJson);  
	        ticket = map.get("ticket");  
	        is.close();  
	    } catch (Exception e) {  
	            e.printStackTrace();  
	    }  
	    return ticket;  
	}  
	
	public static String SHA1(String decript) {  
	    try {  
	        MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");  
	        digest.update(decript.getBytes());  
	        byte messageDigest[] = digest.digest();  
	        // Create Hex String  
	        StringBuffer hexString = new StringBuffer();  
	        // 字节数组转换为 十六进制 数  
	            for (int i = 0; i < messageDigest.length; i++) {  
	                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);  
	                if (shaHex.length() < 2) {  
	                    hexString.append(0);  
	                }  
	                hexString.append(shaHex);  
	            }  
	            return hexString.toString();  
	   
	        } catch (NoSuchAlgorithmException e) {  
	            e.printStackTrace();  
	        }  
	        return "";  
	}  
	public static String CreateNoncestr() {  
	    String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
	    String res = "";  
	    for (int i = 0; i < 16; i++) {  
	        Random rd = new Random();  
	        res += chars.charAt(rd.nextInt(chars.length() - 1));  
	    }  
	    return res;  
	}
	
	public static Map getShare(HttpServletRequest request,String url){
		 //微信分享授权开始  
		  String appId ="" ;//取项目中配置的公众号id 测试号
		  String domainAddr = "http://vm3kgx.natappfree.cc";//项目中配置的网站的域名   测试域名
		  String str = request.getQueryString();  
		  Map map = new HashMap();   
		  map.put("appid", appId);   
		//  String url="http://vm3kgx.natappfree.cc/escq/wap/userinfo/personerErweima.html";
		  url=domainAddr+url;
		  map.put("url", url);
		  String  jsapi_token=SingletonUtil.getJsapiTicket(SingletonUtil.getAccessToken());
		   //生成签名  
	      SortedMap params = new TreeMap();            
	      params.put("timestamp", Long.toString(new Date().getTime()/1000));  
	      params.put("noncestr", HttpXmlClient.CreateNoncestr());  
	      params.put("jsapi_ticket",jsapi_token);  
	      System.out.println("打印数据:"+jsapi_token+"  url: "+map.get("url"));
	      params.put("url",map.get("url"));//url地址  
	      StringBuffer sb = new StringBuffer();  
	      Set es = params.entrySet();  
	      Iterator it = es.iterator();  
	      while(it.hasNext()) {  
	          Map.Entry entry = (Map.Entry)it.next();  
	          String k = (String)entry.getKey();  
	          Object v = entry.getValue();  
	          sb.append(k + "=" + v + "&");  
	      }  
	      String  signStr = sb.toString().substring(0, sb.toString().length()-1);  
	      String sign = HttpXmlClient.SHA1(signStr);//签名    
	      Map result = new HashMap();  
	      result.put("timestamp",(String)params.get("timestamp"));  
	      result.put("noncestr", (String)params.get("noncestr"));  
	      result.put("signature", sign);  
	      result.put("appId",map.get("appid"));  
	      System.out.println("打印数据:"+result);
		  return result;
		
		
	}
}
SingletonUtil:
import java.util.Date;
import java.util.Map;


public class SingletonUtil { //缓存授权信息

	public static String getAccessToken() {
		String result = "";
		SingletonAccessToken singleton = SingletonAccessToken.getInstance();
		Map map = singleton.getMap();
		String time = map.get("time");
		String accessToken = map.get("access_token");
		Long nowDate = new Date().getTime();
		if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 7000 * 1000) {
			result = accessToken;
		} else {
			String access_token=HttpXmlClient.getToken();
			map.put("time", nowDate + "");
			map.put("access_token", access_token);
			result = access_token;
			}
		return result;
	}
	
	public static String getJsapiTicket(String accessToken) {
		String result = "";
		SingletonJsapiTicket singleton = SingletonJsapiTicket.getInstance();
		Map map = singleton.getMap();
		String time = map.get("time");
		String jsapiTicket = map.get("jsapi_ticket");
		Long nowDate = new Date().getTime();
		if (jsapiTicket != null && time != null && nowDate - Long.parseLong(time) < 7000 * 1000) {
			result = jsapiTicket;
		} else {
			String jsapi_ticket=HttpXmlClient.getTicket(accessToken);  
			map.put("time", nowDate + "");
			map.put("jsapi_ticket", jsapi_ticket);
			result = jsapi_ticket;
		}
		return result;
	}
}

Token单例:
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 
 *  token的单例.
 * Description: 
 *    
 * Author: yanhongyu
 * Date: 2017-6-23上午9:34:38
 * Changelog:
 *   ----------------------------------------------------------------------------
 *   Ver   Date                     Detail
 *   ----------------------------------------------------------------------------
 *   1.0   2017-6-23上午9:34:38         new file.
 * 
*/ public class SingletonAccessToken { //缓存accessToken 和一个 时间 private Map map = new HashMap(); private SingletonAccessToken() { } private static SingletonAccessToken single = null; public static SingletonAccessToken getInstance() { if (single == null) { single = new SingletonAccessToken(); } return single; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public static SingletonAccessToken getSingle() { return single; } public static void setSingle(SingletonAccessToken single) { SingletonAccessToken.single = single; } }

Ticket单例:
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 
 *  ticket的单例.
 * Description: 
 *    
 * Author: yanhongyu
 * Date: 2017-6-23上午9:34:38
 * Changelog:
 *   ----------------------------------------------------------------------------
 *   Ver   Date                     Detail
 *   ----------------------------------------------------------------------------
 *   1.0   2017-6-23上午9:34:38         new file.
 * 
*/ public class SingletonJsapiTicket { //缓存jsapi_ticket 和一个 时间 private Map map = new HashMap(); private SingletonJsapiTicket() { } private static SingletonJsapiTicket single = null; public static SingletonJsapiTicket getInstance() { if (single == null) { single = new SingletonJsapiTicket(); } return single; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public static SingletonJsapiTicket getSingle() { return single; } public static void setSingle(SingletonJsapiTicket single) { SingletonJsapiTicket.single = single; } }

jsp页面:

    
<%--通过config接口注入权限验证配置--%>    
        

完成以上步骤,完成微信公众号网页分享功能开发,最后上图。

微信公众号网页分享功能开发总结_第1张图片


注意:

     1、签名时的url是当前网页的路径,一定要一模一样不然会导致签名无效。

     2、分享页面的域名要是安全域名下的路径

     3、分享路径和分享图片路径一定要正确,如果是404链接会导致分享失败,查代码时会发现都没问题,然而就不成功。



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