微信分享需要服务器端将分享的参数进行加密返回前端进行分享。这里我们使用的是sha1加密方式,
前端需要传递一个分享的url给我们。贴代码
public Map<String, Object> Share(HttpServletRequest req,HttpServletResponse resp) throws IOException, DigestException{
SetReqHander.setHander(resp);
HashMap<String, Object> m=new HashMap<String, Object>();
if(req.getParameter("url")==null){
m.put("status", 401);
m.put("message", "参数为空");
return m;
}
String url=req.getParameter("url");
BufferedReader in = null;
Bywxshare bywxshare = bywxshareService.get();
Date now=new Date();
String ticket=null;
if(bywxshare==null){
String cache[]=getTticket(in,ticket);
//插入表
Date outtime=new Date();
outtime.setHours(new Date().getHours()+1);
Bywxshare wxshare=new Bywxshare("1",cache[0], cache[1], outtime);
bywxshareService.insert(wxshare);
ticket=wxshare.getJsapiticket();
}else if(now.after(bywxshare.getOuttime())){
String cache[]=getTticket(in,ticket);
//修改表中记录
Date outtime=new Date();
outtime.setHours(new Date().getHours()+1);
bywxshare.setAccesstoken(cache[0]);
bywxshare.setJsapiticket(cache[1]);
bywxshare.setOuttime(outtime);
bywxshareService.update(bywxshare);
ticket=bywxshare.getJsapiticket();
}else{
ticket=bywxshare.getJsapiticket();
}
Map<String,Object> map=new HashMap<String, Object>();
String noncestr =WXUtil.getNonceStr(16);//随机字符串
String timestamp=WXUtil.getTimeStamp();//时间戳
// String encode = URLEncoder.encode(url, "utf-8");
String decode = URLDecoder.decode(url,"UTF-8");
System.out.println();
String string = "jsapi_ticket="+ticket+"&noncestr="+noncestr+"×tamp="+timestamp+"&url="+decode;
//加密签名
String sign=SHA1util.getSha1(string);
map.put("noncestr",noncestr);
map.put("timestamp",timestamp);
map.put("sign",sign);
map.put("appid",appid);
m.put("status", 200);
m.put("data", map);
return m;
}
我们处理过后将生成的签名和参数返回给前端。这里用到的工具类可以参考微信支付(2),
另外需要加密啥sha1的方法
贴出
/**
* 得到sha1加密的字符串
* @param str
* @return
*/
public static String getSha1(String str){
if(str == null || str.length()==0){
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 (Exception e) {
return null;
}
}
这里获取jsapi_ticket的方式和微信支付类同