微信分享签名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();
    }
}

  

posted @ 2018-06-28 19:16  森林木马  阅读(4435)  评论(1编辑  收藏  举报