微信分享签名Java代码实现
最近写了一个小微信签名功能,记录一下希望用到的朋友可以参考下。
RestController @RequestMapping("/api/wx") public class WeixinAction { private static final Logger logger = LoggerFactory.getLogger(WeixinAction.class); private static final String appId = "appId"; @Autowired RestTemplate restTemplate; @Autowired RedisClient redisClient; @RequestMapping("/WeixinAction_getWXConfigSignature") public String getWXConfigSignature(@RequestBody JSONObject reqJson) { String url = reqJson.getString("url"); logger.info("原始URL: " + url); long timeStampSec = System.currentTimeMillis() / 1000; String timestamp = String.format("%010d", timeStampSec); String nonceStr = getRandomStr(8); String[] urls = url.split("#"); String newUrl = urls[0]; logger.info("随机串:"+nonceStr+", 获取签名URL: " + newUrl); JSONObject respJson = new JSONObject(); String[] signArr = new String[]{"url=" + newUrl, "jsapi_ticket=" + getWXJsapiTicket(), "noncestr=" + nonceStr, "timestamp=" + timestamp}; Arrays.sort(signArr); String signStr = StringUtils.join(signArr, "&"); String resSign = DigestUtils.sha1Hex(signStr); logger.info("返回的签名:" + resSign); respJson.put("appId", appId); respJson.put("timestamp", timestamp); respJson.put("nonceStr", nonceStr); respJson.put("signature", resSign); logger.info(respJson.toJSONString()); JsonObject jsonObject = BaseCode.retCode(ResultCode.success); jsonObject.putValue("resp", respJson); return jsonObject.toString(); } private String getWXJsapiTicket() { String ticket = redisClient.getStr(appId); if (StringUtils.isBlank(ticket)) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getWXaccessToken() + "&type=jsapi"; String resp = restTemplate.getForObject(url, String.class); JSONObject resJson = JSONObject.parseObject(resp); logger.info("获取到ticket:" + resJson.getString("ticket")); redisClient.setStr(appId, resJson.getString("ticket"), SystemConstants.ONE_HOURS * 2); return resJson.getString("ticket"); } return ticket; } private String getWXaccessToken() { String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret=secret"; String resp = restTemplate.getForObject(url, String.class); JSONObject resJson = JSONObject.parseObject(resp); logger.info("获取到access_token:" + resJson.getString("access_token")); return resJson.getString("access_token"); } public static String getRandomStr(int length) { String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; int randomNum; char randomChar; Random random = new Random(); // StringBuffer类型的可以append增加字符 StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { // 可生成[0,n)之间的整数,获得随机位置 randomNum = random.nextInt(base.length()); // 获得随机位置对应的字符 randomChar = base.charAt(randomNum); // 组成一个随机字符串 str.append(randomChar); } return str.toString(); } }
作者:森林木马
-------------------------------------------
特此声明:所有评论和私信都会在第一时间回复。也欢迎朋友们指正错误,共同进步!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
个性签名:好记性不如勤随笔,好随笔还请多关注!