移动端h5公众号网页登录
发表时间:2020-9-24
发布人:葵宇科技
浏览次数:68
h5访问地址是一个接口。就是 http://xxx/wx/mpauth
private String mpAppid="公众号的appid";
private String mpAppsecret="公众号的appid";
private String mpRedirecturl="http://xxx/wx/mphandle";
/**
* 1.微信公众号跳转授权
*/
@RequestMapping("/wx/mpauth")
public void toWxMpAuth(HttpServletResponse response) throws IOException {
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect";
url = url.replace("APPID",mpAppid);
url = url.replace("REDIRECT_URI",mpRedirecturl);
response.sendRedirect(url);
}
/**
* 2.公众号授权处理
* @param code
* @throws IOException
*/
@RequestMapping("/wx/mphandle")
public void mpHandle(HttpServletResponse response,String code) throws IOException {
JSONObject jsonObject = WxUtil.getOpenidByCode(mpAppid,mpAppsecret,code);
String openid = jsonObject.getString("openid");
String accessToken = jsonObject.getString("access_token");
lsUserService.operateMpLogin(response,openid,accessToken);
}
import com.lanshi.framework.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
/**
* 3.处理公众号授权登录
* @param response
* @param openid
* @param accessToken
*/
public void operateMpLogin(HttpServletResponse response, String openid, String accessToken) throws IOException {
JSONObject jsonObject = WxUtil.getUserInfoByOpenidAndAccessToken(openid,accessToken);
if(jsonObject==null){
response.sendRedirect(mpRedirecturl+"loginMobile.html"+"?errorMsg=获取token错误");
}
String unionid = jsonObject.getString("unionid");
String nickname = jsonObject.getString("nickname");
String headimgurl = jsonObject.getString("headimgurl");
String[] arr = unionid.split("_");
LsUser lsUser = lsUserDao.getUserByUnionid(arr[0]);
//以下为业务逻辑,根据需求修改
if(lsUser==null){
response.sendRedirect(mpRedirectHtml+"公众号网页名称1.html"+"?unionid="+unionid+"_"+openid);
}else{
if(lsUser.getStatus().intValue()!=10){
response.sendRedirect(mpRedirectHtml+"公众号网页名称1.html"+"?errorMsg=当前用户已经被禁用");
return;
}
lsUser.setMpOpenid(openid);
lsUser.setNickname(nickname);
lsUser.setHeadimg(headimgurl);
lsUserDao.updateById(lsUser);
response.sendRedirect(mpRedirectHtml+"公众号网页名称2.html"+"?userinfo="+JWTUtil.sign(lsUser.getId().toString()));
}
}