微信接口授权的简单实现

1、定义AccessToken 类

public class AccessToken {
	// 获取到的凭证
	private String token;
	// 凭证有效时间,单位:秒
	private int expiresIn;
    //凭证失效时间
    private long expiresTime;

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public int getExpiresIn() {
		return expiresIn;
	}

	public void setExpiresIn(int expiresIn) {
		this.expiresIn = expiresIn;
        this.expiresTime = System.currentTimeMillis()+expiresIn;
	}

    public long getExpiresTime() {
        return expiresTime;
    }

    public long getRestTime(){
        return this.expiresTime-System.currentTimeMillis();
    }
}

2、线程每过一段时间,获得一次accesstoken

/**
 * User: edwardnb
 * Date: 2015-12-10
 * Time: 2:03:03
 * To change this template use File | Settings | File Templates.
 */
public class TokenThread implements Runnable {
    private static Logger log = LoggerFactory.getLogger(TokenThread.class);
    // 第三方用户唯一凭证
    public static String appid = "";
    // 第三方用户唯一凭证密钥
    public static String appsecret = "";
    public static AccessToken accessToken = null;
    private static Map tokenList = new HashMap();

    public void run() {
        while (true) {
            try {
                accessToken = WeixinUtil.getAccessToken(appid, appsecret);
                if (null != accessToken) {
                    log.info("获取access_token成功,有效时长{}秒 token:{}", accessToken.getExpiresIn(), accessToken.getToken());
                    // 休眠7000秒
                    Thread.sleep((accessToken.getExpiresIn() - 200) * 1000);
                } else {
                    // 如果access_token为null,60秒后再获取
                    Thread.sleep(60 * 1000);
                }
            } catch (InterruptedException e) {
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException e1) {
                    log.error("{}", e1);
                }
                log.error("{}", e);
            }
        }
    }

    public static AccessToken getToken(Platform platform){
    //一个后台服务对应多个公众号
        if(platform == null || appid.equals(platform.getAppId()))
            return accessToken;
        AccessToken at = tokenList.get(platform.getAppId());
        if(at == null || at.getRestTime()<=100){
            at = TokenThread.initToken(platform);
            tokenList.put(platform.getAppId(),at);
            return at;
        }       
        return tokenList.get(platform.getAppId());
    }

    private static AccessToken initToken(Platform platform){
        return WeixinUtil.getAccessToken(platform.getAppId(), platform.getAppSecret());
    }
}  

3、与微信接口的方法封装

public class WeixinUtil {
    private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);

    // 获取access_token的接口地址(GET) 限200(次/天)
    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
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = null;

        String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

   

}

你可能感兴趣的:(工具)