首先准备好常量类,当然也可以写到配置文件里
/**
*
* 功能描述: 公用封装方法
* date: 2017-7-24 下午5:18:58
* lk
*/
public interface Constant {
// 凭证获取(GET)
public final static String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
// 用户同意授权,获取code
public final static String WX_OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
// 用户同意授权,回调url
public final static String WX_REDIRECT_URL = "回调url";
// 拉去用户信息url
public final static String WX_SNSAPI_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//微信openId
public final static String WX_OPEN_ID = "公众好id";
//微信appSecret
public final static String WX_APP_SECRET = "appSecret";
}
然后需要几个工具类
/**
*
* 功能描述: 公用封装方法
* date: 2017-7-24 下午5:18:58
* lk
*/
public class CommonMethod {
/**
* 获取接口访问凭证
*
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static Token getToken(String appid, String appsecret, String code) {
Token token = null;
String requestUrl = Constant.TOKEN_URL.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
// 发起GET请求获取凭证
net.sf.json.JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
if (null != jsonObject) {
try {
token = new Token();
token.setAccessToken(jsonObject.getString("access_token"));
token.setExpiresIn(jsonObject.getInt("expires_in"));
token.setOpenId(jsonObject.getString("openid"));
} catch (JSONException e) {
token = null;
// 获取token失败
System.out.println("获取token失败");
e.printStackTrace();
//log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return token;
}
/**
* URL编码(utf-8)
*
* @param source
* @return
*/
public static String urlEncodeUTF8(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static net.sf.json.JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
net.sf.json.JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
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);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
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 = net.sf.json.JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
System.out.println("连接超时:{}");
ce.printStackTrace();
} catch (Exception e) {
System.out.println("https请求异常:{}");
e.printStackTrace();
}
return jsonObject;
}
}
Token类
public class Token {
// 接口访问凭证
private String accessToken;
// 凭证有效期,单位:秒
private int expiresIn;
private String openId;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
}
下面写下调用流程
第一步请求获取code,原本想在代码中直接跳转的但未成功,就决定使用返回一个页面在页面中进行跳转
@RequestMapping("/index")
public String home(HttpServletRequest request) {
// 请求获取用户授权
String requestUrl = Constant.WX_OAUTH_URL
.replace("APPID", Constant.WX_OPEN_ID)
.replace("REDIRECT_URI",
CommonMethod.urlEncodeUTF8(Constant.WX_REDIRECT_URL))
.replace("SCOPE", "snsapi_base").replace("STATE", "123");
request.setAttribute("url", requestUrl);
return "url";
}
现在是返回的jsp代码
下面是接收回调的action
@RequestMapping("/showIndex")
public String getIndex(HttpServletRequest request) {
String code = request.getParameter("code");
// 获取TOKEN
Token accessToken = CommonMethod.getToken(Constant.WX_OPEN_ID,
Constant.WX_APP_SECRET, code);
if (!OAuth(request, accessToken.getAccessToken(),
accessToken.getOpenId())) {
//此处编写业务逻辑
return "error";
}
//此处编写业务逻辑
} public boolean OAuth(HttpServletRequest request, String accessToken, String openId) { TBaseMember member = null; // 拼接请求地址 String requestUrl = Constant.WX_SNSAPI_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId); // 获取用户信息 JSONObject jsonObject = CommonMethod.httpsRequest(requestUrl, "GET", null); if (null != jsonObject) { try { // 根据openid查询判断用户是否存在 TBaseMember tbm = memberService.selectMemberByOpenId(jsonObject .getString("openid")); if (null != tbm) { request.getSession().setAttribute("member", tbm); } else { member = new TBaseMember(); member.setmId(AutoGenerationCode.getUUId()); member.setmState("01"); member.setIsValid("01"); member.setCreateDate(new Date()); member.setmOpenid(jsonObject.getString("openid")); member.setExt2(jsonObject.getString("nickname")); member.setmSex("0" + jsonObject.getInt("sex")); member.setExt1(jsonObject.getString("headimgurl")); memberService.insertSelective(member); request.getSession().setAttribute("member", member); } return true; } catch (Exception e) { e.printStackTrace(); /* * if ("0".equals(member.getExt4())) { * System.out.println("用户{}已取消关注"); } else { int errorCode = * jsonObject.getInt("errcode"); String errorMsg = * jsonObject.getString("errmsg"); System.out.println("获取用户信息失败" * + errorMsg); } */ return false; } } return false; } 至此用户信息就保存到数据库和session中