package com.sinaif.util;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
public class WXhandler {
private static Logger logger = Logger.getLogger(WXhandler.class);
public static String appId = "wx*******";
public static String appSecret = "12fbe0f6d**************2fb50675e";
public static String prelinkUrl = "http://www.sina.com";
public static String getAccessToken() {
String access_token = "";
String grant_type = "client_credential";//获取access_token填写client_credential
String AppId=appId;//第三方用户唯一凭证
String secret=appSecret;//第三方用户唯一凭证密钥,即appsecret
//这个url链接地址和参数皆不能变
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
System.out.println("JSON字符串:"+demoJson);
access_token = demoJson.getString("access_token");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return access_token;
}
//第二步、获取jsapi_ticket
//Java代码 收藏代码
public static String getTicket(String access_token) {
String ticket = null;
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";//这个url链接和参数不能变
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.parseObject(message);
System.out.println("JSON字符串:"+demoJson);
ticket = demoJson.getString("ticket");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return ticket;
}
public static String SHA1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static Map<String, String> getShareMap(String linkUrl) {
//1 获取accessToken
String accessToken = getAccessToken();
//2 获取Ticket
String jsapi_ticket = getTicket(accessToken);
String noncestr = "abcdefg";
long timestamp = System.currentTimeMillis() / 1000;
Map<String, String> map = new HashMap<String, String>();
// 下面四项为签名算法所需项
//String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"×tamp="+timestamp+"&url="+linkUrl;
map.put("noncestr", noncestr);
map.put("timestamp", timestamp + "");
map.put("url", linkUrl);
map.put("jsapi_ticket", jsapi_ticket);
String sign = getJsSdkSign(map);
// String sign = SHA1(str);
// 补充填充其它
map.put("sign", sign);
map.put("appId", appId);
return map;
}
public static String getJsSdkSign(Map<String, String> map) {
ArrayList<String> list = new ArrayList<String>();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != "") {
list.add(entry.getKey() + "=" + entry.getValue() + "&");
}
}
int size = list.size();
String[] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
System.out.println("========= encript");
System.out.println(result);
result = result.substring(0, result.length()-1);
String sign = DigestUtils.sha1Hex(result);
return sign;
}
/**
* 获取鉴权url
* @param req
* @return
*/
public static String reqUrl(HttpServletRequest req){
String share_link = prelinkUrl+req.getRequestURI();
if (StringUtils.isNotBlank(req.getQueryString())) {
share_link += "?" + req.getQueryString();
logger.info("share_link"+share_link);
}
return share_link;
}
}
//-------------------------------------------------------------------------------------------------------
@RequestMapping(value = "/login")
public String login(HttpServletRequest request, HttpServletResponse response, String openId) throws ApiException {
String link = WXhandler.reqUrl(request); //获取路径 和参数 注意 带上参数
Map<String, String> map = WXhandler.getShareMap(link);
if (openId == null) {
openId = "";
}
request.setAttribute("openId", openId);
request.setAttribute("map", map);
return "login";
}