工具類(一)-----微信工具類

前些天做微信授權登錄用到了一些關於調用微信接口的東西,寫了個工具類分享給大家,如有問題歡迎大家批評指正!!!

package com.iyiqiba.utility;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.iyiqiba.common.WChartUser;
import com.iyiqiba.common.OAuthAccessToken;

/**
 * 微信工具類
 * @author ZSQ 2017年6月4日20:49:34
 *
 */
public class WChartUtils {

    private static Logger log = LoggerFactory.getLogger(WChartUtils.class);

    public final static String APPID = "wx6a42b00945e04c";

    public final static String APPSECRET = "05e78940a491423c47185e7ccb8ee"; 

    //獲取用戶詳細信息
    public final static String SCOPE_INFO = "snsapi_userinfo";

    //近獲取用戶open_id
    public final static String SCOPE_BASE = "snsapi_base";

    //微信請求接口地址  
    //獲取access_token 接口地址   Get
    public final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    //獲取網頁授權登錄access_token 接口地址Get
    public final static String OAUTH_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    //獲取授權登錄用戶信息 接口地址Get
    public final static String OAUTH_WCHAT_USER_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    public final static String OAUTH_LOGIN_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";

    //access_token有效時間 時間有時間是7200 爲了防止延時導致獲取access_token的間斷
    public static long expires_in = 7100;

    //上次獲取access_token時間
    private static Long lastGetAccessTokenTime = 0L;

    //當前access_token值
    private static String access_token = null;

    /***
     * 獲取access_token 
     * @return access_token
     * @throws IOException
     */
    public static String getAccessToken() throws IOException{
        if (access_token == null) {//當前沒有獲取access_token
            access_token = refreshAccessToken();
        }else {//已經獲取過access_token
            Long curTime = System.currentTimeMillis();
            if ((curTime-lastGetAccessTokenTime)/1000 >= expires_in) {
                access_token = refreshAccessToken();
            }
        }       
        return access_token;
    }

    /***
     * 刷新access_token 
     * @return access_token
     * @throws IOException
     */
    public static String refreshAccessToken() throws IOException{
        lastGetAccessTokenTime = System.currentTimeMillis();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);  
        String result = HttpsRequest.sendGet(url);
        JSONObject json = JSONObject.parseObject(result);
        String token = (String) json.get("access_token");       
        if (token == null) {
            String errorCode = (String) json.get("errcode");
            String errorMsg = (String) json.get("errmsg");
            log.error("獲取access_token失敗:錯誤代碼:" + errorCode + "錯誤信息:" + errorMsg);
        }   
        return token;
    }

    /**
     * 獲取授權登錄access_token
     * @param code
     * @return
     * @throws IOException
     */
    public static OAuthAccessToken getOAuthAccessToken(String code) throws IOException{
        String url = OAUTH_ACCESS_TOKEN_URL.replace("APPID", APPID).replace("SECRET", APPSECRET).replace("CODE", code); 
        String result = HttpsRequest.sendGet(url);
        JSONObject json= JSONObject.parseObject(result);
        String token = json.getString("access_token");

        if(token == null){
            String errorCode = json.getString("errcode");
            String errorMsg = json.getString("errmsg");
            System.out.println(json.toString());
            log.error("獲取授權登錄access_token失敗:錯誤代碼:" + errorCode + "錯誤信息:" + errorMsg);
            return null;
        }       

        OAuthAccessToken accessToken = (OAuthAccessToken) JSONObject.parseObject(result, OAuthAccessToken.class);
        return accessToken;
    }

    /**
     * 獲取用戶信息 
     * @return 
     * @throws IOException
     */
    public static WChartUser getOAuthUserInfo(String code) throws IOException{
        OAuthAccessToken accessToken = WChartUtils.getOAuthAccessToken(code);
        if (accessToken == null) {
            return null;
        }
        String token = accessToken.getAccess_token();
        String openid = accessToken.getOpenid();
        String url = OAUTH_WCHAT_USER_URL.replace("ACCESS_TOKEN", token).replace("OPENID", openid);
        String result = HttpsRequest.sendGet(url);
        JSONObject jsonObject = JSONObject.parseObject(result);
        openid = jsonObject.getString("openid");

        if(openid == null){
            String errorCode = jsonObject.getString("errcode");
            String errorMsg = jsonObject.getString("errmsg");
            System.out.println(jsonObject.toString());
            log.error("獲取access_token失敗:錯誤代碼:" + errorCode + "錯誤信息:" + errorMsg);
            return null;
        }

        WChartUser user = JSONObject.parseObject(result, WChartUser.class);
        return user;
    }   

    public static String getOAuthLoginUrl(String redirectUrl, String scope){
        return OAUTH_LOGIN_URL.replace("APPID", APPID).replace("REDIRECT_URI", redirectUrl)
                .replace("SCOPE", scope);
    } 

    public static void main(String []args) throws Exception{
        //WChartUtils.getOAuthUserInfo("123");
//      String result = "{ \"access_token\":\"ACCESS_TOKEN\", \"expires_in\":7200, \"refresh_token\":\"REFRESH_TOKEN\", \"openid\":\"OPENID\", \"scope\":\"SCOPE\" }";
//      System.out.println(result);
//      OAuthAccessToken accessToken = JSONObject.parseObject(result, OAuthAccessToken.class);
//      System.out.println(accessToken.getOpenid());
//      System.out.println(accessToken.getAccess_token());
        System.out.println(WChartUtils.getAccessToken());
    }   
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章