Java接入微信分享需要做什么?
微信分享官方地址:https://qydev.weixin.qq.com/wiki/index.php?title=%E5%BE%AE%E4%BF%A1JS%E6%8E%A5%E5%8F%A3
access_token和ticket一定要做缓存,微信每天有最大次数限制,超过之后将无法调用
- 获取access_token
access_token有效期是7200,这里使用redis做缓存,缓存时间为7000(秒)
String accessTokenCache = (String) redisUtil.get("access_token"); if (accessTokenCache != null) { return accessTokenCache; }
Map<String, Object> accessMap = new HashMap<>(8); accessMap.put("appid", 你的appid); accessMap.put("secret", 你的秘钥); accessMap.put("grant_type", "client_credential"); //这个url链接地址和参数皆不能变 String access_result = restTemplate.getForObject(
"https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}",
String.class, accessMap);
AccessTokenBO accessTokenBO = JSON.parseObject(access_result,AccessTokenBO.class);
reidsUtil.set("access_token",accessToeknBO.getAccessToken,7000);
- 获取ticket
String ticketCache = (String) redisUtil.get("ticket"); if (ticketCache != null) { return ticketCache; }
// 上面获取accessToken的方法 String accessToken = getAccessToken(); Map<String, Object> ticketMap = new HashMap<>(8); ticketMap.put("access_token", access_token); String ticket_result = restTemplate.getForObject(SHARE_GET_TICKET, String.class, ticketMap); TicketBO bo = JSON.parseObject(ticket_result,TicketBO.class);
redisUtil.set("ticket", ticket, 7000);
- 前端传url获取微信分享配置
这个url必须和页面 #前的参数一模一样,不能多也不能少,微信分享的link可以是其他地址,和url在同一域名下就好
public WxShareConfigVO getWxShareConfigVO(String url) { url = URLDecoder.decode(url, "UTF-8"); WxShareConfigVO vo = new WxShareConfigVO(); String noncestr = create_nonce_str(); String timestamp = create_timestamp(); String jsapi_ticket = getShareTicket();
// 这个参数顺序也不能变的 String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url;
String signature = "";
try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(string1.getBytes("UTF-8")); signature = byteToHex(crypt.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
vo.setTimestamp(timestamp); vo.setNonceStr(noncestr); vo.setSignature(signature); vo.setAppid(你的appid)
return vo; }
private String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; }
private String create_nonce_str() { return UUID.randomUUID().toString().replaceAll("-", ""); }
private String create_timestamp() { return Long.toString(System.currentTimeMillis() / 1000); }