/**
* 微信授權(quán)access_token
* @author wangcl
*
*/
public class AccessToken {
private String access_token;
private int expires_in;
private long expires_time;
private String jsapi_ticket;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public int getExpires_in() {
return expires_in;
}
public void setExpires_in(int expires_in) {
this.expires_in = expires_in;
}
public long getExpires_time() {
return expires_time;
}
public void setExpires_time(long expires_time) {
this.expires_time = expires_time;
}
public AccessToken( ) {
}
public AccessToken(String access_token, int expires_in,String jsapi_ticket) {
this.access_token = access_token;
this.expires_in = expires_in;
this.expires_time = System.currentTimeMillis() / 1000;
this.jsapi_ticket = jsapi_ticket;
}
public boolean isExpires() {
if (access_token != null && expires_in > 0) {
long currentTime = System.currentTimeMillis() / 1000;
if (expires_in > (currentTime - expires_time + 30)) {
return true;
}
}
return false;
}
public String getJsapi_ticket() {
return jsapi_ticket;
}
public void setJsapi_ticket(String jsapi_ticket) {
this.jsapi_ticket = jsapi_ticket;
}
}
//加密
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
/*
'============================================================================
'api說明:
'createSHA1Sign創(chuàng)建簽名SHA1
'getSha1()Sha1簽名
'============================================================================
'*/
public class Sha1Util {
public static String getNonceStr() {
Random random = new Random();
return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8");
}
public static String getTimeStamp() {
return String.valueOf(System.currentTimeMillis() / 1000);
}
//創(chuàng)建簽名SHA1
public static String createSHA1Sign(SortedMap<String, String> signParams) throws Exception {
StringBuffer sb = new StringBuffer();
Set es = signParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + v + "&");
//要采用URLENCODER的原始值瓢娜!
}
String params = sb.substring(0, sb.lastIndexOf("&"));
// System.out.println("sha1之前:" + params);
// System.out.println("SHA1簽名為:"+getSha1(params));
return getSha1(params);
}
//Sha1簽名
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
}
public class WxAuth {
HttpServletRequest request;
HttpServletResponse response;
String openId, accessToken,nickname,headimgurl;
String unionId, code = null;
public WxAuth(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
public String wxAuth() {
code = request.getParameter("code");
String openId = request.getParameter("openid");
// System.out.println("In wxAuth.............:code="+code);
if (!CommonUtils.isEmptyString(code)) {
if (getAccessToken(code)) {
// System.out.println("In wxAuth.............:getAccesstoke:code="+code);
if (!CommonUtils.isEmptyString(openId)) {
return openId;
}
}
}
reAuth();
return null;
}
/**
* 根據(jù)code獲取accesstoken
* @param code
* @return
*/
private boolean getAccessToken(String code) {
openId = null;
accessToken = null;
unionId = null; // 不管如何先清空數(shù)據(jù)
String accessUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Consts.APPID + "&secret=" + Consts.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
JSONObject jsonObject = CommonUtils.httpsRequest(accessUrl, "GET", null);
if (null != jsonObject) {
try {
openId = jsonObject.getString("openid");
accessToken = jsonObject.getString("access_token");
unionId = jsonObject.getString("unionid");
} catch (Exception e) {
}
}
if (!CommonUtils.isEmptyString(openId)) {
request.getSession().setAttribute(Consts.SESSION_OPENID, openId);
String UnionURL = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&openid=" + openId + "&access_token=" + accessToken;
JSONObject jsonObject2 = CommonUtils.httpsRequest(UnionURL, "GET", null);
// System.out.println("In WxAuth.........:getUserInfo");
if (null != jsonObject2) {
try {
nickname = jsonObject2.getString("nickname");
headimgurl = jsonObject2.getString("headimgurl");
System.out.println("In WxAuth.........:getUserInfo: nickname = "+nickname+".....headimgurl = "+headimgurl);
} catch (Exception e) {
}
}
return true;
}
return false;
}
/**
* 跳轉(zhuǎn)微信授權(quán)
*/
public void reAuth() {
// 清空session椭懊,重新獲取授權(quán)
request.getSession().setAttribute(Consts.SESSION_OPENID, "");
request.getSession().setAttribute("accesstoken", "");
request.getSession().setAttribute("wxauth", 1);
try {
response.sendRedirect("./wxsq?reurl=" + CommonUtils.getFullURLWithParam(request));// 返回到配置文件中定義的路徑
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class WeiXinEntity {
// 獲取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";
//微信模板消息發(fā)送
public final static String template_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
// 獲取jsapi_ticket_url的接口地址(GET) 限200(次/天)
public final static String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
public static AccessToken accessToken;
//微信模板消息發(fā)送
public int sendTemplate(String jsonmsg){
int result = -1;
AccessToken token = getAccessToken();
if (accessToken != null && accessToken.isExpires()) {
// 拼裝url
String url = template_url.replace("ACCESS_TOKEN", token.getAccess_token());
// 調(diào)用接口創(chuàng)建菜單
JsonObject jsonObject = CommonUtils.httpRequest(url, "POST", jsonmsg);
// 請(qǐng)求成功
if (null != jsonObject) {
result = jsonObject.get("errcode").getAsInt();
}
}
return result;
}
/**
* 取得微信access_token
*
* @return
*/
public AccessToken getAccessToken() {
if (accessToken != null && accessToken.isExpires()) {
return this.accessToken;
}
String requestUrl = access_token_url.replace("APPID", Consts.APPID).replace("APPSECRET", Consts.APPSECRET);
JsonObject jsonObject = CommonUtils.httpRequest(requestUrl, "GET", null);
// 請(qǐng)求成功
if (null != jsonObject) {
try {
String access_token = jsonObject.get("access_token").getAsString();
String jsapi_ticketurl = jsapi_ticket_url.replace("ACCESS_TOKEN", access_token);
JsonObject tickObject = CommonUtils.httpRequest(jsapi_ticketurl, "GET", null);
String jsapi_ticke = tickObject.get("ticket").getAsString();
accessToken = new AccessToken(jsonObject.get("access_token").getAsString(), jsonObject.get("expires_in").getAsInt(),jsapi_ticke);
} catch (Exception e) {
accessToken = null;
}
}
return this.accessToken;
}
public String getJsTicket() {
AccessToken token = getAccessToken();
if (accessToken != null && accessToken.isExpires()) {
return token.getJsapi_ticket();
}
return null;
}
}
/**
* 發(fā)送https請(qǐng)求
*
* @param requestUrl 請(qǐng)求地址
* @param requestMethod 請(qǐng)求方式(GET谣光、POST)
* @param outputStr 提交的數(shù)據(jù)
* @return JSONObject(通過JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 創(chuàng)建SSLContext對(duì)象证九,并使用我們指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 設(shè)置請(qǐng)求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 當(dāng)outputStr不為null時(shí)向輸出流寫數(shù)據(jù)
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意編碼格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 從輸入流讀取返回內(nèi)容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 釋放資源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
} catch (Exception e) {
}
return jsonObject;
}
/**
* 獲取當(dāng)前時(shí)間 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一個(gè)指定長(zhǎng)度大小的隨機(jī)正整數(shù).
*
* @param length
* int 設(shè)定所取出隨機(jī)數(shù)的長(zhǎng)度。length小于11
* @return int 返回生成的隨機(jī)數(shù)啡莉。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 發(fā)起https請(qǐng)求
*
* @param requestUrl
* 請(qǐng)求地址
* @param requestMethod
* 請(qǐng)求方式(GET局骤、POST)
* @param outputStr
* 提交的數(shù)據(jù)
* @return JSONObject(通過JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
*/
public static JsonObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JsonObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 創(chuàng)建SSLContext對(duì)象
TrustManager[] tm = { (TrustManager) new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 設(shè)置請(qǐng)求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 當(dāng)有數(shù)據(jù)需要提交時(shí)
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 編碼格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉(zhuǎn)換成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
JsonParser jp = new JsonParser();
jsonObject = (JsonObject) jp.parse(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}