Record the openId and token obtained by wechat (java implementation)

  • I've been writing wechat related interfaces recently. I'm really.... hey
  • First write a url request tool class
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    
    public static String sendGet(String url, String charset, int timeout) {
            String result = "";
            try {
                URL u = new URL(url);
                try {
                    URLConnection conn = u.openConnection();
                    conn.connect();
                    conn.setConnectTimeout(timeout);
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                    String line = "";
                    while ((line = in.readLine()) != null) {
    
                        result = result + line;
                    }
                    in.close();
                } catch (IOException e) {
                    return result;
                }
            } catch (MalformedURLException e) {
                return result;
            }
    
            return result;
        }
  • Get token (because the token will expire in 2 hours, I started a scheduled task. The token will be automatically obtained in 2 hours after the project is started, and it will be added to the cache. It needs to be put into the server for testing, otherwise it can't be done... What measures should wechat security take)
    //address
     public static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=SECRET";
    import net.sf.json.JSONObject; 
    public static String getAccessToken(String appId, String secret) {
            String backData = sendGet(TOKEN_URL.replace("APP_ID", appId).replace("SECRET", secret), "utf-8", 10000);
            log.info("============>Obtain accessToken{}", JSON.toJSONString(backData));
            String accessToken = (String) JSONObject.fromObject(backData).get("access_token");
            return accessToken;
        }
    
    • maven configuration

      
      <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib-ext-spring -->
              <dependency>
                  <groupId>net.sf.json-lib</groupId>
                  <artifactId>json-lib-ext-spring</artifactId>
                  <version>1.0.2</version>
              </dependency>
  • Get ticket

     public static String getJSApiTicket(String acessToken) {
            //Get token
            String urlStr = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + acessToken + "&type=jsapi";
            String backData = sendGet(urlStr, "utf-8", 10000);
            String ticket = (String) JSONObject.fromObject(backData).get("ticket");
            return ticket;
        }
  • Get public number openid

    //Write your own app ID and SECRET
    public static final String PUBLIC_NUMBER_OPEN_ID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APP_ID&secret=SECRET&code=CODE&grant_type=authorization_code";
    
    public static Map<String, Object> getPublicNumberOpenId(String code) {
            Map<String, Object> returnMap = new HashMap<>();
            //Get token
            log.info("==========>Obtain unionID,code Yes," + code);
            String backData = sendGet(PUBLIC_NUMBER_OPEN_ID_URL.replace("CODE", code), "utf-8", 10000);
            log.info("==========>Obtain openID: " + backData);
            String openId = (String) JSONObject.fromObject(backData).get("openid");
            returnMap.put("openId", openId);
            return returnMap;
        }
  • Get small program openid

    //Change app ID and SECRET to their own
    public static final String SMALL_PROGRAM_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APP_ID&secret=SECRET&js_code=CODE&grant_type=authorization_code";
    
    public static Map<String, Object> getSmallProgramOpenId(String code) {
            Map<String, Object> returnMap = new HashMap<>();
            //Get token
            log.info("==========>Obtain unionID,code Yes," + code);
            String backData = sendGet(SMALL_PROGRAM_OPEN_ID_URL.replace("CODE", code), "utf-8", 10000);
            log.info("==========>Obtain openID: " + backData);
            String openId = (String) JSONObject.fromObject(backData).get("openid");
            returnMap.put("openId", openId);
            return returnMap;
        }
  • In the next section, I will write about the function of custom message reply

Keywords: Programming JSON Java Spring Maven

Added by shaunrigby on Fri, 13 Dec 2019 21:14:44 +0200