最近公司开发了一个APP需要做一个微信授权登录功能。
首先需要在微信开放平台申请一个账号,然后创建你要开发的移动应用,提交申请,审核通过之后你会的到AppId和AppSerect。记得把这两个值保存起来。
微信的授权登录是通过两步来完成。
首先客户端通过AppId获取一个code传给后端,后端拿到code之后获取access_token和openid。具体代码如下:
private static final String AppId = "AppId";
private static final String AppSecret = "AooSecreet";
//获取用户信息请求链接
public final static String GetUserUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
//获取accessToken和openid的链接
public final static String CODE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID" +
"&secret=SECRET&code=CODE&grant_type=authorization_code";
@RequestMapping(value = "/code", method = RequestMethod.GET)
@ResponseBody
public WxVM getSessionKey(HttpServletRequest request, HttpServletResponse response) throws Exception {
WxVM wxVM = new WxVM();
String code = request.getParameter("code");//获取code值
String codeUrl = CODE_URL.replace("APPID",AppId).replace("SECRET",AppSecret)
.replace("CODE",code);
JSONObject jsonObject = AccessTokenUtil.httpRequest(codeUrl, "GET", null);
// System.out.println("json:" + jsonObject);
String openid = jsonObject.getString("openid");
RedisUtil.set("access_token:" + openid, jsonObject.getString("access_token"), 2 * 60 * 60);
if (jsonObject == null) {
wxVM.setFlag(false);
wxVM.setDesc("微信授权失败");
return wxVM;
}
Object openid = jsonObject.getString("openid");
wxVM.setFlag(true);
wxVM.setDesc("微信授权成功");
wxVM.setOpenid(openid);
return wxVM;
}
第二步是获取用户敏感信息
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public LoginVM dealUserInfo(@RequestBody WxRequestEntity wxRequestEntity, HttpServletRequest request) throws Exception {
LoginVM loginVM = new LoginVM();
String requestUrl = GetUserUrl.replace("ACCESS_TOKEN", accessToken)
.replace("OPENID", wxRequestEntity.getOpenid());
JSONObject userJson= AccessTokenUtil.httpRequest(requestUrl, "GET", null);
System.out.println("openJson: "+userJson);
String nickname=userJson.getString("nickname");
Integer sex=userJson.getInt("sex");
String headimgurl=userJson.getString("headimgurl");
CameraUserDO cameraUserDO = new CameraUserDO();
Date date = new Date();
cameraUserDO.setOpenid(wxRequestEntity.getOpenid());
cameraUserDO.setAvatarUrl(headimgurl);
cameraUserDO.setNickName(nickname);
cameraUserDO.setGender(Integer.valueOf(sex));
cameraUserDO.setLoginTime(date);
loginVM.setCameraUserDO(cameraUserDO)
return loginVM;
}
}
代码用所用到的工具类:
import com.xiaoniu.camera.client.entity.MyX509TrustManager;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
public class AccessTokenUtil {
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
"&appid=wx5a2cd5c9c9742507&secret=3cfdd3b3f0a9553a9709c8b473e21c27";
private static Logger log = LoggerFactory.getLogger(AccessTokenUtil.class);
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
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 httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}
public static String getAccessTokenUtil() {
String accessToken = null;
JSONObject jsonObject = httpRequest(ACCESS_TOKEN_URL, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = jsonObject.getString("access_token");
} catch (JSONException e) {
accessToken = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject
.getString("errmsg"));
}
}
return accessToken;
}
}