微信接口 微信分享带图片、标题、描述 JAVA

官方JS-SDK说明文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

1、先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。【备注:登录后可在“开发者中心”查看对应的接口权限。】

2、前台js代码:

  1>、前端页面引入JS:<script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

  2>、加入下面js

var title = "特朗普结束访华 离开北京";//分享标题
var desc = "朗普访华#[美国总统特朗普结束访华]美国总统特朗普10日上午结束对中国的国事访问,乘专机离开北京。";//分享描述
var link = "${wechatSign.pageUrl}";//分享链接
var imgUrl = "http://n.sinaimg.cn/news/transform/20171110/AvUQ-fynstfh3322960.jpg";//图片图标
         $(function(){
			wx.config({
			      debug: false,
			      appId: '${wechatSign.appid}',//公众号appid
			      timestamp:'${wechatSign.timestamp}', //生成签名时间戳
			      nonceStr:'${wechatSign.noncestr}', //生成签名随机字符串
			      signature:'${wechatSign.signature}', //签名
			      jsApiList: [
			        'checkJsApi',
			        'onMenuShareTimeline',
			        'onMenuShareAppMessage',
			        'onMenuShareQQ',
			        'onMenuShareWeibo',
			        'onMenuShareQZone'
			      ]
			  });
		});
		wx.ready(function () {
			wx.onMenuShareTimeline({
			    title: title, // 分享标题
			    desc: desc, // 分享描述
			    link: link, // 分享链接
			    imgUrl: imgUrl, // 分享图标
			    success: function () { 
			        // 用户确认分享后执行的回调函数
			        console.log("test");
			    },
			    cancel: function () { 
			        // 用户取消分享后执行的回调函数
			    }
			});
			
			wx.onMenuShareAppMessage({
			    title: title, // 分享标题
			    desc: desc, // 分享描述
			    link: link, // 分享链接
			    imgUrl: imgUrl, // 分享图标
			    //type: '', // 分享类型,music、video或link,不填默认为link
			    //dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
			    success: function () { 
			        // 用户确认分享后执行的回调函数
			    	console.log("test");
			    },
			    cancel: function () { 
			        // 用户取消分享后执行的回调函数
			    }
			});
			
			wx.onMenuShareQQ({
			    title: title, // 分享标题
			    desc: desc, // 分享描述
			    link: link, // 分享链接
			    imgUrl: imgUrl, // 分享图标
			    success: function () { 
			       // 用户确认分享后执行的回调函数
			    	console.log("test");
			    },
			    cancel: function () { 
			       // 用户取消分享后执行的回调函数
			    }
			});
			
			wx.onMenuShareWeibo({
			    title: title, // 分享标题
			    desc: desc, // 分享描述
			    link: link, // 分享链接
			    imgUrl: imgUrl, // 分享图标
			    success: function () { 
			       // 用户确认分享后执行的回调函数
			    	console.log("test");
			    },
			    cancel: function () { 
			        // 用户取消分享后执行的回调函数
			    }
			});
			
			wx.onMenuShareQZone({
			    title: title, // 分享标题
			    desc: desc, // 分享描述
			    link: link, // 分享链接
			    imgUrl: imgUrl, // 分享图标
			    success: function () { 
			       // 用户确认分享后执行的回调函数
			    },
			    cancel: function () { 
			        // 用户取消分享后执行的回调函数
			    }
			});
			
			
		})

  

后台代码:

  1>、Controller层

@RequestMapping("/default")
public String frontDefault(Model model,HttpServletRequest request){
    //获取access_token
    String access_token = getWechatService.getAccessTokenOfJssdk();
//根据token获取jsapi_ticket
String jsapi_ticket = getWechatService.getJsapiTicketOfJssdk(access_token);
Long timestamp = new Date().getTime()/1000;
			UUID uuid = UUID.randomUUID();
			String noncestr=uuid.toString();
String param = request.getQueryString();
			String pageUrl = request.getRequestURL().toString();
			if (param != "" && param != null)
			{
				pageUrl = pageUrl + "?" + param;
			}
String signature = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+pageUrl;
signature = getSha1(signature);
String appid = "wxd7a6d344bc0c6abc";//公众号appid
			Map<String,Object> wechatSign = new HashMap<String,Object>();
			wechatSign.put("timestamp", timestamp);
			wechatSign.put("noncestr", noncestr);
			wechatSign.put("signature", signature);
			wechatSign.put("appid", appid);
			wechatSign.put("pageUrl", pageUrl);
			model.addAttribute("wechatSign", wechatSign);
return  "/default.html";

}

//sha1
	public String getSha1(String str) {
		if (null == str || 0 == str.length()){
	        return null;
	    }
	    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	            'a', 'b', 'c', 'd', 'e', 'f'};
	    try {
	        MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
	        mdTemp.update(str.getBytes("UTF-8"));
	         
	        byte[] md = mdTemp.digest();
	        int j = md.length;
	        char[] buf = new char[j * 2];
	        int k = 0;
	        for (int i = 0; i < j; i++) {
	            byte byte0 = md[i];
	            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
	            buf[k++] = hexDigits[byte0 & 0xf];
	        }
	        return new String(buf);
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
		return null;
	}

  2>、Service层

@Service
public class GetWechatServiceImpl  implements GetWechatService{
//绑定公众号appid
	String appid = "wxd7a6d344bc0c6abc";
//绑定公众号secret 
	String secret = "29085320d3bd472t29192cd4eecd6166";

	@Resource
    private GetWechatDao getWechatDao;
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public String getAccessTokenOfJssdk() {
		// TODO Auto-generated method stub
		String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        //查询数据库,是否存在access_token
		List<Map<String, Object>> tokenJsonList = getWechatDao.selectGlobalAccessToken();
        //存在?
		if(tokenJsonList.size() > 0) {
			Map<String, Object> jsonStr = tokenJsonList.get(0);
			System.out.println("----------"+jsonStr);
			JSONObject tokenJson = JSONObject.parseObject(JSON.toJSONString(jsonStr));
              //获取上次写入token时间
			String dateTime = tokenJson.get("validdate").toString();
			try {
				Date validdate = sdf.parse(dateTime);
                  //比较与当前时间差
				Long times = DateUtil.timeDifference(validdate);
				if(times <-5400) {//token小于1.5小时,则重新获取
					String  newTokenStr = new HttpRequestor().doGet(getTokenUrl);
					JSONObject newTokenJson = JSONObject.parseObject(newTokenStr);
					String newToken = newTokenJson.getString("access_token");
					if(newToken !=null && newToken!="") {
						//写入数据库
						getWechatDao.updateGlobalAccessToken(newToken);
						return newToken;
					}
				}else {
					return tokenJson.get("value").toString();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return null;
	}

	@Override
	public String getJsapiTicketOfJssdk(String accessToken) {
		// TODO Auto-generated method stub
		String jsapiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
		List<Map<String, Object>> ticketJsonList = getWechatDao.selectJsapiTicket();
		if(ticketJsonList.size() > 0) {
			Map<String, Object> jsonStr = ticketJsonList.get(0);
			JSONObject ticketJson = JSONObject.parseObject(JSON.toJSONString(jsonStr));
			String dateTime = ticketJson.get("validdate").toString();
			try {
				Date validdate = sdf.parse(dateTime);
				Long times = DateUtil.timeDifference(validdate);
				if(times <-5400) {//token小于1.5小时,则重新获取
					System.out.println("----------------------"+jsapiUrl);
					String  newTicketStr = new HttpRequestor().doGet(jsapiUrl);
					System.out.println("----------------------"+newTicketStr);
					JSONObject newTicketJson = JSONObject.parseObject(newTicketStr);
					String newTicket = newTicketJson.getString("ticket");
					System.out.println("----------------------"+newTicket);
					if(newTicket !=null && newTicket!="") {
						//写入数据库
						getWechatDao.updateJsapiTicket(newTicket);
						return newTicket;
					}
				}else {
					return ticketJson.get("value").toString();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		return null;
	}

}

  

 

posted @ 2017-11-10 14:53  微木Vmumu  阅读(2357)  评论(0编辑  收藏  举报