可以用下面的工具类,现在weixin4j更方便
String appId = "";
String appSecret = "";
Map access_token_map = GetWxToken.instance().getWxWebToken(appId, appSecret, code);
// 获取微信用户openId
String openid = CommUtil.null2String(access_token_map.get("openid"));
System.out.println("OpenId" + openid);
// 微信网页授权SCOPE分为snsapi_base、snsapi_userinfo,前者是用户无感知的静默授权只能拿到openid;而后者需要用户确认,能拿到更多的用户信息。
String scope = CommUtil.null2String(access_token_map.get("scope"));
System.out.println("scope===================================>" + scope);
// 微信token
String access_token = CommUtil.null2String(access_token_map.get("access_token"));
// 判断用户授予权限
if (scope.equals("snsapi_userinfo")) {
System.out.println("进入判断用户授权");
Map params = new HashMap();
params.put("openid", openid);
System.out.println("============================================================新增用户");
Map wxUserInfo = GetWxToken.instance().getWxUserInfo(access_token, openid);//微信用户信息
//完成之后页面跳转
}
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.nutz.json.Json;
import org.springframework.stereotype.Component;
@Component
public class GetWxToken {
private static GetWxToken getAccessToken = new GetWxToken();// 创建单例
private static String accessToken = "";// 存放token
private static String jsapi_ticket = "";// 存放jsapi_ticket
private static Date date = null;// 超时时间
// 以下为微信商城获取的token信息。
private static String wx_accessToken = "";// 存放token
private static Map wx_map;//网页授权map
private static Map wx_user;//授权微信用户
private static Date wx_date = null;// 超时时间
private static Map wx_unionid;//授权微信unionid
// 获取单例
public static GetWxToken instance() {
return getAccessToken;
}
public static int null2Int(Object s) {
int v = 0;
if (s != null)
try {
v = Integer.parseInt(s.toString());
} catch (Exception e) {
}
return v;
}
public static Map cal_time_space(Date begin, Date end) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long l = end.getTime() - begin.getTime();
long day = l / (24 * 60 * 60 * 1000);
long hour = (l / (60 * 60 * 1000) - day * 24);
long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
long second = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
Map map = new HashMap();
map.put("day", day);
map.put("hour", hour);
map.put("min", min);
map.put("second", second);
return map;
}
public static String null2String(Object s) {
return s == null ? "" : s.toString().trim();
}
// 获取微商城accessToken
public String getWxToken(String appId,String appSecret,HttpServletRequest request) {
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ appId + "&secret=" + appSecret;
ServletContext serc = request.getSession().getServletContext();
if(serc.getAttribute("access_token") != null && serc.getAttribute("access_token") !=""){
if(serc.getAttribute("access_token_date") != null && serc.getAttribute("access_token_date") !=""){
Date date = (Date) serc.getAttribute("access_token_date");
Map time_space = cal_time_space(date,new Date());
int a = null2Int(time_space.get("day"))*86400+
null2Int(time_space.get("hour"))*3600+
null2Int(time_space.get("min"))*60+
null2Int(time_space.get("second"));
if(a > 7200){
getWxAccessToken(url,request);
}else{
this.accessToken = serc.getAttribute("access_token").toString();
}
}else{
getWxAccessToken(url,request);
}
}else{
getWxAccessToken(url,request);
}
System.out.println("wx_accessToken----》"+this.accessToken);
return this.accessToken;
}
public void getWxAccessToken(String url,HttpServletRequest request){
ServletContext serc = request.getSession().getServletContext();
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秒
System.setProperty("jsse.enableSNIExtension", "false");
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");
Map map = Json.fromJson(HashMap.class, message);
String token = null2String(map.get("access_token"));
is.close();
if (token != null && !token.equals("")) {
this.accessToken = token;
// 设置20分钟后重新获取token
Calendar cal = Calendar.getInstance();
//cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 20);
this.wx_date = cal.getTime();
}
serc.setAttribute("access_token",this.accessToken);
serc.setAttribute("access_token_date",this.wx_date);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取微商城网页授权accessToken
public Map getWxWebToken(String appId,String appSecret,String code) {
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
+"appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
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秒
System.setProperty("jsse.enableSNIExtension", "false");
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");
this.wx_map = Json.fromJson(HashMap.class, message);
String token = null2String(this.wx_map.get("access_token"));
is.close();
if (token != null && !token.equals("")) {
this.wx_accessToken = token;
// 设置20分钟后重新获取token
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 20);
this.wx_date = cal.getTime();
}
} catch (Exception e) {
e.printStackTrace();
}
return wx_map;
}
// 获取微信jsapi_ticket
public String getJsapiToken(String access_token,HttpServletRequest request) {
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
ServletContext serc = request.getSession().getServletContext();
if(serc.getAttribute("jsapi_ticket") != null && serc.getAttribute("jsapi_ticket") !=""){
if(serc.getAttribute("jsapi_ticket_date") != null && serc.getAttribute("jsapi_ticket_date") !=""){
Date date = (Date) serc.getAttribute("jsapi_ticket_date");
Map time_space =cal_time_space(date,new Date());
int a = null2Int(time_space.get("day"))*86400+
null2Int(time_space.get("hour"))*3600+
null2Int(time_space.get("min"))*60+
null2Int(time_space.get("second"));
if(a > 7200){
getWxJsapiTicket(url,request);
}else{
this.jsapi_ticket = serc.getAttribute("jsapi_ticket").toString();
}
}else{
getWxJsapiTicket(url,request);
}
}else{
getWxJsapiTicket(url,request);
}
System.out.println("jsapi_ticket----》"+this.jsapi_ticket);
return this.jsapi_ticket;
}
public void getWxJsapiTicket(String url,HttpServletRequest request){
ServletContext serc = request.getSession().getServletContext();
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秒
System.setProperty("jsse.enableSNIExtension", "false");
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");
Map map = Json.fromJson(HashMap.class, message);
String jsapi_ticket = null2String(map.get("ticket"));
is.close();
if (jsapi_ticket != null && !jsapi_ticket.equals("")) {
this.jsapi_ticket = jsapi_ticket;
// 设置20分钟后重新获取token
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 20);
this.wx_date = cal.getTime();
}
serc.setAttribute("jsapi_ticket",this.jsapi_ticket);
serc.setAttribute("jsapi_ticket_date",this.wx_date);
} catch (Exception e) {
e.printStackTrace();
}
}
// 拉取用户信息
public Map getWxUserInfo(String access_token,String openid) {
String url = "https://api.weixin.qq.com/sns/userinfo?"
+"access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
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秒
System.setProperty("jsse.enableSNIExtension", "false");
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");
this.wx_user = Json.fromJson(HashMap.class, message);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return wx_user;
}
}