微信開發---獲取公衆平臺,小程序,企業應用,企業自建應用的接口調用憑證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 不同。只需要傳入對應的正確的參數,即可獲取對應的憑證。

詳細的可以閱讀 微信官方文檔 ,找到自己需要的分類然後進行閱讀.

 

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