微信开发---获取公众平台,小程序,企业应用,企业自建应用的接口调用凭证access_token

文档上有说明,调用绝大多数后台接口时都需使用 access_token,开发者需要进行妥善保存.凭证的有效期目前是7200秒,且不应该频繁调取,应该进行缓存.另外建议开发者使用中控服务器统一获取和刷新 access_token,其他业务逻辑服务器所使的 access_token 均来自于该中控服务器,不应该各自去刷新,否则容易造成冲突,导致 access_token 覆盖而影响业务.

首先是小程序和公众号

   /**
     * 获取小程序/微信公众平台的 accessToken,根据所传参数 type 不同,可以获取不同平台的调用凭证
     * type = "programApp"时,获取小程序的凭证,type = "platformApp"时,获取公众号的凭证
     *
     * @return 获取成功返回值,失败返回 null
     */
    public String test(String type) {
        String token = null;
        // 缓存获取小程序的access_token
        if ("programApp".equals(type)) {
            token = redisTemplate.opsForValue().get("programAccessToken");
        }
        // 缓存获取公众平台access_token
        if ("platformApp".equals(type)) {
            token = redisTemplate.opsForValue().get("platformAccessToken");
        }

        if (StringUtils.isNotBlank(token)) {
            log.debug("----------缓存中获取到access_token-----------");
            return token;
        }
        // 缓存未获取到,从微信服务端获取,因为获取次数有限,需要将获取到的值进行缓存,注意好缓存时间,否则易造成缓存数据与微信服务端数据不一致情况
        int expires_in = 7200;
        String url = null;
        if ("programApp".equals(type)) {
            // 拼接对应的小程序唯一凭证 appID 和小程序唯一密钥 appSecret
            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
        }
        if ("platformApp".equals(type)) {
            // 拼接对应的公众号唯一凭证 appID 和唯一凭证密钥 appSecret
            url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret;
        }

        // 通过工具类发送get请求
        String result = HttpUtil.request(url);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
        token = (String) jsonObject.get("access_token");
        expires_in = (int) jsonObject.get("expires_in");
        if (StringUtils.isNotBlank(token)) {
            if ("programApp".equals(type)) {
                // 缓存小程序access_token
                redisTemplate.opsForValue().set("programAccessToken", token, expires_in, TimeUnit.SECONDS);
                log.debug("微信服务端获取到小程序access_token,缓存为programAccessToken");
                return token;
            }
            if ("platformApp".equals(type)) {
                // 缓存公众号的access_token
                redisTemplate.opsForValue().set("platformAccessToken", token, expires_in, TimeUnit.SECONDS);
                log.debug("微信服务端获取到公众号access_token,缓存为platformAccessToken");
                return token;
            }
        }
        return token;
    }

为方便,将获取方法写在了一起,可以根据自己需求,拆开使用.而企业应用与企业自建应用的凭证获取方式与上面的大同小异,主要区别就是 appidsecret, 请求的 url 不同。只需要传入对应的正确的参数,即可获取对应的凭证。

详细的可以阅读 微信官方文档 ,找到自己需要的分类然后进行阅读.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章