public class WXUtil {
private static String appid = "";
private static String secret = "";
private static String token_url = "https://api.weixin.qq.com/cgi-bin/token";
private static String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
public static String wx_jsapiticket = "";
// public static String wx_accesstoken = "";
// public static String wx_jsapiticket = "sM4AOVdWfPE4DxkXGEs8VKn28rHes_cWG6CZiaKmN5FAV6H24W2R5m9KG6ndDlxULINyBD3HL1_vv-TrO5LJfQ";
private static Log log = LogFactory.getLog(WXUtil.class);
public static void getWxDate(HttpServletRequest request){
try{
String jsapi_ticket = wx_jsapiticket;
String noncestr = WXUtil.getRandomString(16);
String timestamp = String.valueOf(System.currentTimeMillis()/1000);
String urlData = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"×tamp="+timestamp+"&url="+CommonUtil.getBasePath(request);
String signature = WXUtil.getSha1(urlData);
request.setAttribute("wx_noncestr", noncestr);
request.setAttribute("wx_timestamp", timestamp);
request.setAttribute("wx_signature", signature);
}catch(Exception e){
log.error("微信页面初始化失败======>"+e.getMessage());
e.printStackTrace();
}
}
public static String getAppsecrect() throws Exception{
String appsecrect = "";
String urlDate = "grant_type=client_credential&appid="+appid+"&secret="+secret;
String json = CommonUtil.postURL(urlDate, token_url);
appsecrect = CommonUtil.viewJsonKey(json,"access_token");
log.info(new Timestamp(System.currentTimeMillis())+"getAppsecrect 微信获取access_token=====>"+json);
if(appsecrect == null || "".equals(appsecrect)){
throw new Exception("getAppsecrect access_token失败=====>"+json);
}
// wx_accesstoken=appsecrect;//server端微信模板使用
return appsecrect;
}
public static String getJsApiTicket() throws Exception{
log.info("请求微信ticket=====>");
String token = WXUtil.getAppsecrect();
String urlDate = "access_token="+token+"&type=jsapi";
String json = CommonUtil.postURL(urlDate, ticket_url); //活动产品
wx_jsapiticket = CommonUtil.viewJsonKey(json,"ticket");
log.info(new Timestamp(System.currentTimeMillis())+" getJsApiTicket 微信获取ticket=====>"+json);
if(wx_jsapiticket == null || "".equals(wx_jsapiticket)){
throw new Exception("getJsApiTicket ticket失败=====>"+json);
}
return wx_jsapiticket;
}
/**
* sha1签名
* @param url
* @return
*/
public static String getSha1(String url){
try {
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
digest.update(url.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 String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static void main(String args[]){
try{
String jsapiticket = WXUtil.getJsApiTicket();
System.out.println("jsapiticket======>"+jsapiticket);
}catch(Exception e){
}
}
/**
* 静默授权通过返回的code获取用户微信id
* @param request
* @param response
* @param code
* @return
* @throws UnsupportedEncodingException
*/
public static String getWXinfo(HttpServletRequest request,HttpServletResponse response,String code) throws UnsupportedEncodingException{
String get_access_token_url="https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=APPID" +
"&secret=SECRET&" +
"code=CODE&grant_type=authorization_code";
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
get_access_token_url=get_access_token_url.replace("APPID",appid);
get_access_token_url=get_access_token_url.replace("SECRET", secret);
get_access_token_url=get_access_token_url.replace("CODE", code);
String json=HttpUtil.getUrl(get_access_token_url);
JSONObject jsonObject=JSONObject.fromObject(json);
String openid=jsonObject.getString("openid");
try{
WXUtil.getWxDate(request);
}catch(Exception e){
e.printStackTrace();
}
return openid;
}
}