1 引入pom文件
<dependencies>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.3</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
<exclusions>
<exclusion>
<artifactId>commons-lang</artifactId>
<groupId>commons-lang</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
<exclusions>
<exclusion>
<artifactId>httpcore</artifactId>
<groupId>org.apache.httpcomponents</groupId>
</exclusion>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
2 构建登陆接口
import com.wx.auth.util.AuthUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
@WebServlet("/wxLogin")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String url = "https://open.weixin.qq.com/connect/qrconnect?appid="+AuthUtil.APPID +
"&redirect_uri="+ URLEncoder.encode(AuthUtil.REDIRECT_URL) +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=STATE#wechat_redirect";
resp.sendRedirect(url);
}
}
3 构建回调接口
import com.alibaba.fastjson.JSON;
import com.wx.auth.util.AuthUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.Map;
@WebServlet("/wxcallBack")
public class CallBackServlet extends HttpServlet {
private String dbUrl;
private String driverName;
private String userName;
private String passWord;
private Connection connection = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
/* @Override
public void init(ServletConfig config) throws ServletException {
try {
this.dbUrl = config.getInitParameter("dbUrl");
this.driverName = config.getInitParameter("driverName");
this.userName = config.getInitParameter("userName");
this.passWord = config.getInitParameter("passWord");
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String code = req.getParameter("code");
System.out.println("==code=="+code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID +
"&secret=" + AuthUtil.APPSECRET +
"&code=" + code +
"&grant_type=authorization_code";
//JSONObject jsonObject = AuthUtil.doGetJson(url);
String s = AuthUtil.doGetString(url);
System.out.println("===s=="+s);
Map map = (Map) JSON.parse(s);
String accessToken = String.valueOf(map.get("access_token"));
String openid = String.valueOf(map.get("openid"));
String unionid = String.valueOf(map.get("unionid"));
System.out.println("==accesstoken:"+accessToken+"==openid:"+openid+"==unionid:"+unionid);
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken
+ "&openid=" + openid //ozhaA1qKOBb-eczdMZilhTeg7Ctc
+ "&lang=zh_CN";
String s1 = AuthUtil.doGetString(infoUrl);
System.out.println("==s1=="+s1);
/*String openid = jsonObject.getString("openid");
String token = jsonObject.getString("access_token");
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token
+ "&openid=" + openid
+ "&lang=zh_CN";
JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
System.out.println(userInfo);
*/
//1 使用微信用户信息直接登陆,无需注册和绑定
//req.setAttribute("info", userInfo);
req.getRequestDispatcher("/index1.jsp").forward(req, resp);
//2 将微信与当前系统账号绑定
/*try {
String nickName = getNickName(openid);
if(!"".equals(nickName)){
//已经绑定
req.setAttribute("nickName",nickName);
req.getRequestDispatcher("/index2.jsp").forward(req,resp);
}else{
//未绑定
req.setAttribute("openid",openid);
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
} catch (SQLException e) {
e.printStackTrace();
}*/
}
public String getNickName(String openid) throws SQLException {
String nickName = "";
connection = DriverManager.getConnection(dbUrl,userName,passWord);
String sql = "select nickname from user where openid=?";
ps = connection.prepareStatement(sql);
ps.setString(1,openid);
rs = ps.executeQuery();
while (rs.next()){
nickName = rs.getString("NICKNAME");
}
rs.close();
ps.close();
connection.close();
return nickName;
}
public int updUser(String openid,String account,String password) throws SQLException {
connection = DriverManager.getConnection(dbUrl,userName,passWord);
String sql = "UPDATE user SET openid=? WHERE account=? AND password=?";
ps = connection.prepareStatement(sql);
ps.setString(1,openid);
ps.setString(2,account);
ps.setString(3,password);
int tmp = ps.executeUpdate();
rs = ps.executeQuery();
rs.close();
ps.close();
connection.close();
return tmp;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String account = req.getParameter("account");
String password = req.getParameter("password");
String openid = req.getParameter("openid");
try {
int tmp = updUser(openid,account,password);
if(tmp > 0){
System.out.println("绑定成功");
}else{
System.out.println("绑定失败");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
4 工具类
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class AuthUtil {
//4bafb07ab17d11ba087673e8f04474f7
public static final String APPID = "wx9e8da4139021f27a7";
public static final String APPSECRET = "4bafb07ab17sdd11ba087673e8f04474f7";
public static final String REDIRECT_URL = "http://universe.555.io:5452/WxAuth/wxcallBack";
public static JSONObject doGetJson(String url) throws IOException {
JSONObject jsonObject = null;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if(entity != null){
String result = EntityUtils.toString(entity,"utf-8");
jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}
public static String doGetString(String url) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
//HttpPost httpPost = new HttpPost(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = "";
if(entity != null){
result = EntityUtils.toString(entity,"utf-8");
//jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
return result;
}
}
5 总结
在这次实现的过程中碰到一个问题。微信的回调地址和微博的不同,微博的回调地址需要写到接口(http://xxx.xxx.com:8080/api/wbcallBack),但是微信比较坑,只需要这样写就欧克(xxx.xxx.com:8080)
快来和博主打成一片吧^_^