標籤:
package com.wanhua.weixin.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wanhua.weixin.util.WXConst;
import com.wanhua.weixin.util.WXHttpUtil;
/**
* 網頁授權token
*
* @author enway
*
*/
public class OauthToken {
// 網頁授權介面調用憑證,注意:此access_token與基礎支援的access_token不同
public String access_token;
// 憑證有效時間,單位:秒
public long expires_in;
// 使用者重新整理access_token
public String refresh_token;
// 使用者唯一標識
public String openid;
// 使用者授權的範圍,使用逗號(,)分隔
public String scope;
public int errcode;
public String errmsg;
/**
* 擷取網頁授權介面的憑證
*
* @param code
* @return
* @throws Exception
*/
public static OauthToken getOauthToken(String code) throws Exception {
// 請求的url
String urlStr = String.format(WXConst.URL_GET_OAUTH_TOKEN, code);
// 請求的結果
String result = WXHttpUtil.MsgHttpsRequest(urlStr, "POST", null);
// 網頁授權token
OauthToken oauthToken = JSON.parseObject(result, OauthToken.class);
if (oauthToken.errcode != 0) {
throw new Exception("擷取憑證失敗");
}
return oauthToken;
}
/**
* 檢驗授權憑證(access_token)是否有效
*
* @param access_token
* @param openid
* @return
*/
public static boolean verifyOauthToken(String access_token, String openid) {
// 請求的url
String urlStr = String.format(WXConst.URL_VERIFY_OAUTH_TOKEN, access_token, openid);
try {
// 請求的結果
String result = WXHttpUtil.MsgHttpsRequest(urlStr, "POST", null);
System.out.println("verify Oauth Token==>" + result);
// 將請求結果轉換成json格式資料
JSONObject jsonObject = JSON.parseObject(result);
// 請求結果的狀態代碼
int code = jsonObject.getInteger("errcode");
// 請求成功
if (code == 0) {
return true;
} else {
// 請求失敗
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
網頁授權token