关于java微信授权登录功能,Java后台获取微信用户信息
背景:想要在微信上拉取用户头像
问题:已解决
最近用到了微信授权登录,在网上扒了一大堆帖子,大部分一样,要不就是不全,好不容易找到不错的也不太适合,就扒着老项目磕磕绊绊的搞了搞。
我用的springboot项目,前后端分离,只提供后台接口
微信官方文档https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
PS:强烈建议开发者先读下这个
先上代码,流程思路在最后
Controller
/**
* 确认请求来自微信服务器
*/
@RequestMapping(value = "/weiChat", method = RequestMethod.GET)
public void weiChatDoGet(HttpServletRequest request, HttpServletResponse response) {
wxService.ChatDoGet(request,response);
}
/**
* 微信网页登录授权
*/
@RequestMapping(value = "/portal", method = RequestMethod.GET)
@ResponseBody
public JSONObject testPortal(HttpServletRequest request) {
// 获取code参数
return wxService.saveWeiUser(request);
}
ServiceImpl
```java
static final String WX_JS_TOKEN="wx_js_token";
static final String WX_FEED_TOKEN="wx_feed_token";
@Value("${wx.appid}")
private String appKey;//微信公众上的,详情看下文档
public String getToken() {
String str="grant_type=client_credential&appid="+this.getAppKey()+"&secret="+this.getSecret();
String token=jedisBean.get(WX_FEED_TOKEN+getAppKey());
if(StringUtil.isNotEmpty(token)){
return token;
}
try {
String result = get(URL_TOKEN, str);
log.info("getToken:"+str+"::"+result);
JsonNode jsonNode=objectMapper.readTree(result);
if(jsonNode!=null){
token=jsonNode.findPath("access_token").asText();
}
if(StringUtil.isNotEmpty(token)){
jedisBean.setex(WX_FEED_TOKEN+getAppKey(), 3600, token);
}
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
@Override
public JSONObject saveWeiUser(HttpServletRequest request) {
JSONObject result = new JSONObject();
try{
// 获取code参数
String code = request.getParameter("code");
if(StringUtils.isBlank(code)) {
//org.apache.commons.lang.StringUtils
LOGGER.error("saveWeiUser: could not found parameter 'code' from request");
result.put("code", 9999);
result.put("msg", "从微信服务器获取用户授权码失败");
result.put("data", null);
return result;
}
LOGGER.info("saveWeiUser: code=" + code);
AccessToken at = WeixinUtil.getCodeAccessToken(appKey, secret, code);
if(at == null) {
result.put("code", 9999);
result.put("msg", "从微信服务器获取token失败");
result.put("data", null);
return result;
}
LOGGER.info("saveWeiUser: " + at.toString());
//拉取用户信息
WeiUser wu = WeixinUtil.getWeiUserInfo(at.getOpenid(), at.getToken());
if(wu == null) {
LOGGER.error("saveWeiUser: could not found weixin user information");
result.put("code", 9999);
result.put("msg", "从微信服务器获取用户信息失败");
result.put("data", null);
return result;
}
LOGGER.info("saveWeiUser: " + wu.toString());
//微信用户信息入库 //昵称和头像
//... ...
JSONObject data = new JSONObject();
data.put("openid", wu.getOpenid());
data.put("nickname", wu.getNickname());
data.put("headimg", wu.getHeadimgurl());
result.put("code", 0);
result.put("msg", "SUCCESS");
result.put("data", data);
return result;
} catch(Exception e) {
LOGGER.error("saveWeiUser Exception: " + e.getMessage());
result.put("code", 9999);
result.put("msg", "获取微信信息发生异常");
result.put("data", null);
return result;
}
}
@Override
public void ChatDoGet(HttpServletRequest request, HttpServletResponse response) {
// 微信加密签名
String signature = request.getParameter(“signature”);
// 时间戳
String timestamp = request.getParameter(“timestamp”);
// 随机数
String nonce = request.getParameter(“nonce”);
// 随机字符串
String echostr = request.getParameter(“echostr”);
PrintWriter out;
try {
out = response.getWriter();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(getToken(), signature, timestamp, nonce)) {
//("微信验证token token============" + token);
out.print(echostr);
}
out.close();
out = null;
} catch (IOException e) {
e.getMessage();
}
}
WeixinUtil
```java
public final static String code_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
public static AccessToken getCodeAccessToken(String appid, String appsecret, String code) {
AccessToken accessToken = null;
String requestUrl = code_access_token_url.replace("APPID", appid).replace("SECRET", appsecret).replace("CODE", code);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
//accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
accessToken.setOpenid(jsonObject.getString("openid"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
LOGGER.error(jsonObject.toString());
//LOGGER.error("getCodeAccessToken: get token fail, errcode: " + jsonObject.getString("errcode") + ", errmsg: " + jsonObject.getString("errmsg"));
}
}
return accessToken;
}
public final static String userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//拉取用户信息
public static WeiUser getWeiUserInfo(String openid, String access_token) {
WeiUser weiUser = null;
String requestUrl = userinfo_url.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
weiUser = new WeiUser();
weiUser.setOpenid(jsonObject.getString("openid"));
weiUser.setNickname(jsonObject.getString("nickname"));
weiUser.setHeadimgurl(jsonObject.getString("headimgurl"));
weiUser.setProvince(jsonObject.getString("province"));
weiUser.setSex(jsonObject.getInt("sex"));
weiUser.setCity(jsonObject.getString("city"));
} catch (JSONException e) {
weiUser = null;
// 获取token失败
LOGGER.error("getWeiUserInfo: get weiUser faile, errcode:" + jsonObject.getInt("errcode") + ", errmsg: " + jsonObject.getString("errmsg"));
}
}
return weiUser;
}
SignUtil
public class SignUtil {
/**
* 验证签名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.getMessage();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
流程思路:(用户点授权)前端发送请求到微信服务器,(这个请求的返回重定向的路径URL写在前端,前端接收)微信服务器返回一个code,前端拿到code后请求自己的服务器,根据这个code后台获取微信用户的openid,头像等信息,PS:前几天比较忙,现在才写上,可能有疏忽,有问题留言我