1. 程式人生 > 實用技巧 >Spring Boot 微信公眾號開發(三) access_token

Spring Boot 微信公眾號開發(三) access_token

一、Token

access_token是公眾號的全域性唯一介面呼叫憑據,公眾號呼叫各介面時都需使用access_token。開發者需要進行妥善儲存。access_token的儲存至少要保留512個字元空間。access_token的有效期目前為2個小時,需定時重新整理,重複獲取將導致上次獲取的access_token失效。

token的獲取參考文件

獲取的流程我們完全可以參考微信官方文件:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

流程分析:

  • 從公眾平臺獲取賬號的AppID和AppSecret;
  • token獲取並解析儲存執行體;
  • 採用定時任務每隔兩小時執行一次token獲取執行體;

二、實現:

1、引數獲取:

(1)在微信公眾號官網獲取引數,並配置進yml檔案中

(2)yml配置:

2、 http工具類:

需要匯入httpclient

		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

程式碼如下

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
 * @author yh
 * @date 2020/8/21 16:11
 * @description:
 */
public class HttpUtils {

    /**
     * @author: yh
     * @description: http get請求共用方法
     * @date: 2020/8/21
     * @param reqUrl
     * @param params
     * @return java.lang.String
     **/
    @SuppressWarnings("resource")
    public static String sendGet(String reqUrl, Map<String, String> params)
            throws Exception {
        InputStream inputStream = null;
        HttpGet request = new HttpGet();
        try {
            String url = buildUrl(reqUrl, params);
            HttpClient client = new DefaultHttpClient();

            request.setHeader("Accept-Encoding", "gzip");
            request.setURI(new URI(url));

            HttpResponse response = client.execute(request);

            inputStream = response.getEntity().getContent();
            String result = getJsonStringFromGZIP(inputStream);
            return result;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            request.releaseConnection();
        }

    }

    /**
     * @author: yh
     * @description: http post請求共用方法
     * @date: 2020/8/21
     * @param reqUrl
     * @param params
     * @return java.lang.String
     **/
    @SuppressWarnings("resource")
    public static String sendPost(String reqUrl, Map<String, String> params)
            throws Exception {
        try {
            Set<String> set = params.keySet();
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : set) {
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
            if (list.size() > 0) {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost request = new HttpPost(reqUrl);

                    request.setHeader("Accept-Encoding", "gzip");
                    request.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

                    HttpResponse response = client.execute(request);

                    InputStream inputStream = response.getEntity().getContent();
                    try {
                        String result = getJsonStringFromGZIP(inputStream);

                        return result;
                    } finally {
                        inputStream.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new Exception("網路連線失敗,請連線網路後再試");
                }
            } else {
                throw new Exception("引數不全,請稍後重試");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("傳送未知異常");
        }
    }

    /**
     * @author: yh
     * @description: http post請求json資料
     * @date: 2020/8/21
     * @param urls
     * @param params
     * @return java.lang.String
     **/
    public static String sendPostBuffer(String urls, String params)
            throws ClientProtocolException, IOException {
        HttpPost request = new HttpPost(urls);

        StringEntity se = new StringEntity(params, HTTP.UTF_8);
        request.setEntity(se);
        // 傳送請求
        @SuppressWarnings("resource")
        HttpResponse httpResponse = new DefaultHttpClient().execute(request);
        // 得到應答的字串,這也是一個 JSON 格式儲存的資料
        String retSrc = EntityUtils.toString(httpResponse.getEntity());
        request.releaseConnection();
        return retSrc;

    }

    /**
     * @author: yh
     * @description:  http請求傳送xml內容
     * @date: 2020/8/21
     * @param urlStr
     * @param xmlInfo
     * @return java.lang.String
     **/
    public static String sendXmlPost(String urlStr, String xmlInfo) {
        // xmlInfo xml具體字串

        try {
            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = new OutputStreamWriter(
                    con.getOutputStream());
            out.write(new String(xmlInfo.getBytes("utf-8")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String lines = "";
            for (String line = br.readLine(); line != null; line = br
                    .readLine()) {
                lines = lines + line;
            }
            return lines; // 返回請求結果
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "fail";
    }
    /**
     * @author: yh
     * @description:
     * @date: 2020/8/21
     * @param is
     * @return java.lang.String
     **/
    private static String getJsonStringFromGZIP(InputStream is) {
        String jsonString = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前兩個位元組
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset輸入流到開始位置
            bis.reset();
            // 判斷是否是GZIP格式
            int headerData = getShort(header);
            // Gzip 流 的前兩個位元組是 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                // LogUtil.i("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                // LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonString;
    }

    private static int getShort(byte[] data) {
        return (data[0] << 8) | data[1] & 0xFF;
    }

    /**
     * @author: yh
     * @description: 構建get方式的url
     * @date: 2020/8/21
     * @param reqUrl 基礎的url地址
     * @param params 查詢引數
     * @return java.lang.String
     **/
    public static String buildUrl(String reqUrl, Map<String, String> params) {
        StringBuilder query = new StringBuilder();
        Set<String> set = params.keySet();
        for (String key : set) {
            query.append(String.format("%s=%s&", key, params.get(key)));
        }
        return reqUrl + "?" + query.toString();
    }
}

3、配置類讀取引數

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author yh
 * @date 2020/8/21 17:24
 * @description:
 */
@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class WeChatConfiguration {

    private String appid;

    private String AppSecret;

    private String tokenUrl;

}

4、設定定時任務獲取token

import com.ytkj.operationmanual.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;

/**
 * @author yh
 * @date 2020/8/21 16:39
 * @description: 定時任務
 */
@Component
@Slf4j
public class WeChatTask {

    @Resource
    private TaskService taskService;


    @PostMapping("/getToken")
    @Scheduled(fixedDelay=2*60*60*1000)
    public void getToken() throws Exception {
        log.info("定時任務:重新獲取token");
        taskService.getToken();
    }

}

import com.alibaba.fastjson.JSONObject;
import com.ytkj.operationmanual.config.WeChatConfiguration;
import com.ytkj.operationmanual.service.TaskService;
import com.ytkj.operationmanual.util.HttpUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yh
 * @date 2020/8/21 16:43
 * @description:
 */
@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private WeChatConfiguration weChatConfiguration;
    /**
     * @author: yh
     * @description: 獲取微信token
     * @date: 2020/8/21
     * @param
     * @return void
     **/
    @Override
    public void getToken() throws Exception {

        Map<String, String> params = new HashMap<String, String>();

        params.put("grant_type", "client_credential");
        params.put("appid", weChatConfiguration.getAppid());
        params.put("secret", weChatConfiguration.getAppSecret());

        String json = HttpUtils.sendGet(weChatConfiguration.getTokenUrl(), params);
        String access_token = JSONObject.parseObject(json).getString("access_token");

        System.out.println(LocalDateTime.now() +"token為=============================="+access_token);
    }
}