1.以前是在前面加上隐藏的div块,图片展示,2017年3月底更换方式:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
<div style="display:none"><img id="Img1" width="100%" src="url" style="position:absolute; top:0; left:0;"></div>
2.现在按照官方api:
public service
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.util.SpyMemcache;
import net.sf.json.JSONObject;
/**
* 微信分享
* @author SKS
*/
public class WeixinShareService {
private static String AppID = "微信appid";
private static String AppSecret = "密钥";
public static final String access_token_key = "wx_gongzhong_access_token";
public static final String wx_gongzhong_jsapi_ticket_key = "wx_gongzhong_jsapi_ticket";
/**
* 根据url获得json字符串
*/
public static String getJsonStrByURL(String url){
try {
HttpURLConnection conn = null;
if(url.indexOf("?")==-1){
conn = (HttpURLConnection) new URL(url+"?nocache="+new Date().getTime()).openConnection();
}
if(url.indexOf("?")!=-1){
conn = (HttpURLConnection) new URL(url+"&nocache="+new Date().getTime()).openConnection();
}
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
StringBuffer res = new StringBuffer();
String line = null;
while((line=br.readLine())!=null){
res.append(line);
}
br.close();
conn.disconnect();
return res.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
//获取access_token
public static String getAccessToken(){
Object object = SpyMemcache.getInstance().get(access_token_key);
if(object != null){
return (String)object;
}
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+
AppID+"&secret="+AppSecret;
String atStr = getJsonStrByURL(url);
JSONObject atJson = JSONObject.fromObject(atStr);
//有效期7200秒,全局缓存access_token
SpyMemcache.getInstance().set(access_token_key, atJson.getString("access_token"), atJson.getInt("expires_in"));
return atJson.getString("access_token");
}
//获取jsapi_ticket
public static String getJsapi_ticket(String access_token){
Object object = SpyMemcache.getInstance().get(wx_gongzhong_jsapi_ticket_key);
if(object != null){
return (String)object;
}
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
String atStr = getJsonStrByURL(url);
JSONObject atJson = JSONObject.fromObject(atStr);
//有效期7200秒,全局缓存jsapi_ticket
SpyMemcache.getInstance().set(wx_gongzhong_jsapi_ticket_key, atJson.getString("ticket"), atJson.getInt("expires_in"));
return atJson.getString("ticket");
}
//获取签名
public String getSignature(String url) throws DigestException{
//url(当前网页的URL,不包含#及其后面部分)
Map<String, String> map = new HashMap<String, String>();
map.put("noncestr", getNoncestr(16));//noncestr(随机字符串)
map.put("jsapi_ticket", getJsapi_ticket(getAccessToken()));//有效的jsapi_ticket
map.put("timestamp", new Date().getTime()+"");//timestamp(时间戳)
map.put("url", url);
String string1 = formatParameters(map);
String signature = SHA1(string1);
return signature;
}
public static String getSignature2(String url,String timestamp,String noncestr) throws Exception{
//url(当前网页的URL,不包含#及其后面部分)
Map<String, String> map = new HashMap<String, String>();
map.put("noncestr", noncestr);//noncestr(随机字符串)
map.put("jsapi_ticket", getJsapi_ticket(getAccessToken()));//有效的jsapi_ticket
map.put("timestamp", timestamp);//timestamp(时间戳)
map.put("url", url);
String string1 = formatParameters(map);
String signature = SHA1(string1);
return signature;
}
/**
* SHA1 安全加密算法
* @param maps 参数key-value map集合
*/
public static String SHA1(String decrypt) throws DigestException {
try {
//指定sha1算法
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(decrypt.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();
throw new DigestException("签名错误!");
}
}
//ASCII码从小到大排序
public static String formatParameters(Map<String, String> map){
StringBuilder sb = new StringBuilder();
List<String> mapKeyList = new ArrayList<String>(map.keySet());
Object[] akeys = (Object[])mapKeyList.toArray();
Arrays.sort(akeys);
for (Object k : akeys){
String v = map.get(k);//防止参数不是字符串
sb.append(String.valueOf(k).toLowerCase() + "=" + v + "&");
}
//去掉最后一个&
if (sb.length() > 0){
sb.delete(sb.length() - 1, sb.length());
}
return sb.toString();
}
//随机字符串
public static String getNoncestr(int length) {
char[] ss = new char[length];
int i=0;
while(i<length) {
int f = (int) (Math.random()*3);
if(f==0)
ss[i] = (char) ('A'+Math.random()*26);
else if(f==1)
ss[i] = (char) ('a'+Math.random()*26);
else
ss[i] = (char) ('0'+Math.random()*10);
i++;
}
String is=new String(ss);
return is;
}
}
controller
//微信分享的参数传值
public void setwxShare(HttpServletRequest request) throws Exception{
String wxurl = "";
wxurl = request.getScheme() +"://" + request.getServerName()
+ request.getServletPath();
if (request.getQueryString() != null){
wxurl += "?" + request.getQueryString();
}
String wxtimestamp=new Date().getTime()+"";
String wxnoncestr=WeixinShareService.getNoncestr(16);
String wxsignature=WeixinShareService.getSignature2(wxurl, wxtimestamp, wxnoncestr);
//System.out.println(url+"--"+timestamp+"--"+noncestr+"---"+signature);
request.setAttribute("wxappid","微信appid");
request.setAttribute("wxurl",wxurl);
request.setAttribute("wxtimestamp",wxtimestamp);
request.setAttribute("wxnoncestr",wxnoncestr);
request.setAttribute("wxsignature",wxsignature);
}
js
<script type="text/javascript">
wx.config({
debug: false,
appId: '${wxappid}',
timestamp:'${wxtimestamp}',
nonceStr: '${wxnoncestr}',
signature: '${wxsignature}',
jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage']
});
wx.ready(function () {
wx.onMenuShareTimeline({
title:"${title!}", // 分享标题
link:"分享链接",
imgUrl:"分享图片链接"
});
wx.onMenuShareAppMessage({
title: '${title!}',
desc: '描述',
link: '分享链接',
imgUrl: '分享图片链接',
type: 'link',
dataUrl: '',
success: function () {
},
cancel: function () {
}
});
});
</script>