admin管理员组文章数量:1558079
目录
- 第一步:用户同意授权,获取code
- 第二步:通过code换取网页授权access_token
- 第三步:刷新access_token(如果需要)
- 第四步:拉取用户信息(需scope为 snsapi_userinfo)
- 附:检验授权凭证(access_token)是否有效
建议先去查看微信开发官方文档:
https://mp.weixin.qq/wiki?t=resource/res_main&id=mp1421140842
第一步:用户同意授权,获取code
-
前台通过请求链接https://open.weixin.qq/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
可以获取到code。 -
code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
第二步:通过code换取网页授权access_token
- 获取code后,请求以下链接获取access_token: https://api.weixin.qq/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- 正确时返回的JSON数据包如下:
{
“access_token”:“ACCESS_TOKEN”,
“expires_in”:7200,
“refresh_token”:“REFRESH_TOKEN”,
“openid”:“OPENID”,
“scope”:“SCOPE”
} - controller层代码实现
/**
* 微信浏览器获取用户信息
* @param code
* @param state
* @return
*/
@GetMapping(value = "/userInfo",produces = "text/html;charset=utf-8")
public String getUserInformation(String code, String state, HttpServletRequest request) {
TbUser tbUser = new TbUser();
if (StringUtils.isEmpty(code)){
return resultError("code为空");
}
JSONObject jsonData = WeixinSign.getAccessToken(code);
String openid = jsonData.getString("openid");
String access_token = jsonData.getString("access_token");
String refresh_token = jsonData.getString("refresh_token");
HttpSession session = request.getSession();
//验证access_token是否失效
JSONObject validateData = WeixinSign.getValidateData(access_token, openid);
if (!"0".equals(validateData.getString("errcode"))){
//刷新access_token
JSONObject refreshData= WeixinSign.getRefreshToken(refresh_token);
access_token = refreshData.getString("access_token");
}
JSONObject userData = null;
try {
//拉取用户信息
userData = WeixinSign.getUserInfo(access_token, openid);
Object unionid = userData.get("unionid");
Object nickName = userData.get("nickname");
Object headimgurl = userData.get("headimgurl");
Object sex = userData.get("sex");
if (!StringUtils.isEmpty(unionid)) {
//用户是否注册过
tbUser = tbUserService.selectByUnionid(unionid.toString());
if (StringUtils.isEmpty(tbUser)) {
tbUser = new TbUser();
String userId = UUID.randomUUID().toString().replace("-", "");
tbUser.setId(userId);
if (!StringUtils.isEmpty(nickName)){
tbUser.setNickname(nickName.toString());
}
if (!StringUtils.isEmpty(headimgurl)){
tbUser.setHeadimgUrl(headimgurl.toString());
}
if (!StringUtils.isEmpty(sex)){
tbUser.setSex(new Byte(sex.toString()));
}
tbUser.setCreateTime(new Date());
tbUser.setUnionid(unionid.toString());
tbUserService.insertUser(tbUser);
}
}
} catch (Exception e) {
logger.error("获取用户信息异常:"+e.getMessage());
return resultError("获取用户信息异常");
}
Map map=new HashMap();
map.put("id",tbUser.getId());
map.put("unionid",tbUser.getUnionid());
map.put("headimgUrl",tbUser.getHeadimgUrl());
map.put("nickname",tbUser.getNickname());
map.put("sex",tbUser.getSex());
map.put("province",userData.get("province").toString());
map.put("city",userData.get("city").toString());
map.put("openid",userData.get("openid").toString());
map.put("sessionid",getSession().getId());
return resultSuccess(map);
}
- 微信工具类WeixinSign
package com.sjyx.contest.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class WeixinSign {
/**
* 网页
*/
public static String wy_appid = "wxdee18320bb16f695";
public static String wy_secret = "85a6c0d7fdb86f59c386dc99b8a5f3ec";
public static JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public static JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public static JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public static JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
}
- Http请求工具类
package com.sjyx.contest.common.utils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLDecoder;
public class HttpRequestUtil {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class); //日志记录
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
logger.error("get请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
第三步:刷新access_token(如果需要)
- 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权。
- 获取第二步的refresh_token后,请求以下链接获取access_token:
https://api.weixin.qq/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN - 正确时返回的JSON数据包如下:
{
“access_token”:“ACCESS_TOKEN”,
“expires_in”:7200,
“refresh_token”:“REFRESH_TOKEN”,
“openid”:“OPENID”,
“scope”:“SCOPE”
}
第四步:拉取用户信息(需scope为 snsapi_userinfo)
- 如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
- 请求方法
http:GET(请使用https协议) https://api.weixin.qq/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
- 参数 描述
access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid:用户的唯一标识
lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 - 正确时返回的JSON数据包如下:
{
“openid”:" OPENID",
" nickname": NICKNAME,
“sex”:“1”,
“province”:“PROVINCE”
“city”:“CITY”,
“country”:“COUNTRY”,
“headimgurl”: “http://thirdwx.qlogo/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46”,
“privilege”:[ “PRIVILEGE1” “PRIVILEGE2” ],
“unionid”: “o6_bmasdasdsad6_2sgVt7hMZOPfL”
} - 具体代码第二步已给出
附:检验授权凭证(access_token)是否有效
- 请求方法
http:GET(请使用https协议) https://api.weixin.qq/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
- 参数 描述
access_token: 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid: 用户的唯一标识 - 正确的JSON返回结果:
{ “errcode”:0,“errmsg”:“ok”}
版权声明:本文标题:微信网页开发之授权登录(java实现) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1727385845a1112340.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论