小编在此说一声,建议去看一下微信官方提供的流程图,以及其他的之后再看下面的。小编在此就不提供账号申请,那些准备工作了,直接上代码。
微信官方示例→点击打开链接
微信登录流程:
第一步:APP或者网页端,通过账号密码获取到微信返回的一个code码。code码,有效期为10分钟,10分钟不使用则自动失效,有效次数为一次,每一次的code码都是不同的。[前端或者移动端的操作]
第二步:将code码传给后台登录的接口(红色部分为需要代码)
public String appLogin(){ //从header头部里面取出设备类型,设备编号,以及登录方式 String loginMode = request.getHeader("channel"); String modeType = request.getHeader("app-idfa"); String modeCode = request.getHeader("device"); Map
//获取传过来的code String o = request.getParameter("object"); MapheaderMap = new HashMap (); headerMap.put("loginMode", loginMode); headerMap.put("modeType", modeType); headerMap.put("modeCode", modeCode); //加载配置文件 Map maps = LoadingAuthUtil.loading(); String secret = (String) maps.get("secret"); //获取传过来的code String o = request.getParameter("object"); Map oMap = (Map if(StringUtils.isEmpty(returnMap.get("accessToken")+"")||StringUtils.isEmpty(returnMap.get("isFirstLogin")+"")){ return returnJson(map, "0", ""); } String accessToken = (String) returnMap.get("accessToken"); String isFirstLogin = (String) returnMap.get("isFirstLogin"); //将openid取出来 String openid = JwtTokenUtil.getOpenidStringFromToken(accessToken, secret); //根据open_id,然后调取数据库获取信息 User user = userService.getInfoByOpenId(openid); //将加密字符串与用户信息一起传给APP端 //放进map,转成JSON map.put("authorization", accessToken); map.put("userCode", user.getUser_code()); map.put("nickName",user.getNick_name()); map.put("gender", user.getGender()); map.put("userIcon", user.getUser_image()); map.put("user_nationality", user.getUser_nationality()); map.put("province", user.getProvince()); map.put("city", user.getCity());; map.put("isFirstLogin",isFirstLogin); map.put("invitateCode", user.getInvitate_code()); map.put("shareIcon", user.getShareIcon()); map.put("invitatedCode", user.getInvitated_code()); map.put("tel", user.getUser_tel()); return returnJson(map, "0", ""); }) JSON.parse(o); String code = (String) oMap.get("code"); //调取微信的认证授权后的token Map map=new HashMap (); Map returnMap = jwtLoginService.getAccessToken(code,headerMap); oMap = (Map if(StringUtils.isEmpty(returnMap.get("accessToken")+"")||StringUtils.isEmpty(returnMap.get("isFirstLogin")+"")){ return returnJson(map, "0", ""); } String accessToken = (String) returnMap.get("accessToken"); String isFirstLogin = (String) returnMap.get("isFirstLogin"); //将openid取出来 String openid = JwtTokenUtil.getOpenidStringFromToken(accessToken, secret); //根据open_id,然后调取数据库获取信息 User user = userService.getInfoByOpenId(openid); //将加密字符串与用户信息一起传给APP端 //放进map,转成JSON map.put("authorization", accessToken); map.put("userCode", user.getUser_code()); map.put("nickName",user.getNick_name()); map.put("gender", user.getGender()); map.put("userIcon", user.getUser_image()); map.put("user_nationality", user.getUser_nationality()); map.put("province", user.getProvince()); map.put("city", user.getCity());; map.put("isFirstLogin",isFirstLogin); map.put("invitateCode", user.getInvitate_code()); map.put("shareIcon", user.getShareIcon()); map.put("invitatedCode", user.getInvitated_code()); map.put("tel", user.getUser_tel()); return returnJson(map, "0", ""); }) JSON.parse(o); String code = (String) oMap.get("code"); //调取微信的认证授权后的token Map map=new HashMap (); Map returnMap = jwtLoginService.getAccessToken(code,headerMap);
第三步:通过code调取微信的服务器获取access_token
/**
* description: 根据认证码调取微信平台获取信息
* @param code 认证码
* @return 返回json数据
*/
public Map getAccessToken(String code,Map m) {
logger.info("code:"+code);
Map returnMap =new HashMap();
//----------------------- 加载配置文件 ----------------------
Map maps =LoadingAuthUtil.loading();
String tokenUrl = (String) maps.get("tokenUrl");
String appid = (String) maps.get("appid");
String secret = (String) maps.get("secret");
//--------------------------调用微信后台服务器----------------------------
String url= tokenUrl+"appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
URI uri = URI.create(url);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response;
try {
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
sb.append(temp);
}
if(sb.toString().contains("errcode")){
logger.info(""+sb.toString());
returnMap.put("isFirstLogin", null);
returnMap.put("accessToken", null);
}else{
JSONObject object = new JSONObject().fromObject(sb.toString().trim());
logger.info("wechat info:"+object);
//获取所需要的信息
String accessToken = object.getString("access_token");
String openID = object.getString("openid");
String refreshToken = object.getString("refresh_token");
long expires_in = object.getLong("expires_in"); //获取腾讯过期时间
//token过期时间
Date expires_time=new Date(System.currentTimeMillis()+expires_in*1000);
String unionid = object.getString("unionid");
String scope = object.getString("scope");
//根据open_id(执行数据的新增和修改)
String isFirstLogin = getUserInfo(accessToken,openID);
JwtToken jwtToken = new JwtToken(openID,unionid, expires_time, accessToken, refreshToken, scope);
//根据open_id,然后调取数据库获取信息
User user = userService.getInfoByOpenId(openID);
//将用户id取出来
Long userId = user.getId();
//将用户id设置进JwtToken对象里面
jwtToken.setUserid(userId+"");
//将token加密
String authorization = JwtTokenUtil.generateAccessToken(jwtToken);
//将token存在redis里面
redisUtil.set(RedisPropertyUtil.RedisLoginTokenKey+userId, authorization);
//添加登录流水
String login_mode = (String) m.get("loginMode");
String mode_type = (String) m.get("modeType");
String mode_code = (String) m.get("modeCode");
Login lt = new Login();
lt.setUser_id(userId+"");
lt.setAuthorization(authorization);
lt.setLogin_mode(login_mode);
lt.setAccess_token(accessToken);
lt.setRefresh_token(refreshToken);
lt.setMode_type(mode_type);
lt.setMode_code(mode_code);
loginService.insert(lt);
returnMap.put("isFirstLogin", isFirstLogin);
returnMap.put("accessToken", authorization);
}
return returnMap;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
第四步:根据access_token获取用户信息
/**
* @description: 根据accessToken和open_id 获取用户信息,执行数据库判断
*/
private String getUserInfo(String accessToken,String openID){
//----------------------- 加载配置文件 ----------------------
Map maps =LoadingAuthUtil.loading();
String userInfoUrl = (String) maps.get("userInfoUrl");
String uri = userInfoUrl+"access_token=" + accessToken + "&openid=" + openID;
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(URI.create(uri));
String isFirstLogin = "0"; //默认不是第一次登录
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
builder.append(temp);
}
JSONObject object = new JSONObject().fromObject(builder.toString().trim());
//获取微信返回的用户基本信息
String nickName =object.getString("nickname");
String sex=object.getString("sex");
String province=object.getString("province");
String city=object.getString("city");
String country=object.getString("country");
String headimgurl=object.getString("headimgurl");
String unionid=object.getString("unionid");
logger.info("wechat info: "+nickName+"---"+sex+"---"+province+"---"+city+"---"+country+"---"+headimgurl+"---"+unionid+"---");
//实例化一个用户
User user=new User();
user.setNick_name(nickName);
user.setOpenid(openID);
user.setUnionid(unionid);
user.setUser_icon(headimgurl);
user.setGender(sex);
user.setUser_nationality(country);
user.setProvince(province);
user.setCity(city);
//判断是否是第一次登录
int count = userService.judgeUserByOpenId(openID);
logger.info("count:"+count);
if (count == 0) {//查询数据库是否有open_id
logger.info("first login");
//第一次登录,则生成一个唯一的邀请码
String invitateCode = InvitateCodeUtil.createCode();
int v = userService.judgeCodeByCode(invitateCode);
boolean flag= true;
while(flag){
if(v>0){//说明数据库中已经存在此邀请码,则需要重新生成再继续判断
invitateCode = InvitateCodeUtil.createCode();
v = userService.judgeCodeByCode(invitateCode);
}else{
flag = false;
}
}
//首次登录,根据邀请码自动生成一张图片
if(invitateCode != null){
//加载配置文件
Map shareMap = LoadingShareUtil.loading();
String backgroundUrl = (String) shareMap.get("backgroundUrl");
String aboveUrl = (String) shareMap.get("aboveUrl");
String compoundUrl = (String) shareMap.get("compoundUrl");
String compoundName = (String) shareMap.get("compoundName");
String text = invitateCode;
String finalUrl = (String) shareMap.get("finalUrl");
String finalName = "share_"+invitateCode+"_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".png";
String str[]={ "386", "984" };
ImageUtil.crearePicture(backgroundUrl, aboveUrl, compoundUrl, compoundName, text, finalUrl, finalName,str);
String cosIconPath = TxFileUpload.upload(finalUrl+finalName, finalName, "share");
user.setShareIcon(cosIconPath); //设置地址
}
//设置用户类型(默认是普通会员)
user.setUser_type("4");
//设置邀请码
user.setInvitate_code(invitateCode);
//如果是第一次登录则添加进数据库
userService.insert(user);
//根据openid 找到刚刚添加的user
User t = userService.getInfoByOpenId(openID);
//生成userCode
String userCode = UserCodeUtil.createUserCode(t.getId()+"");
//修改userCode编码
t.setUser_code(userCode);
//修改信息
userService.update(t);
//首次登陆要送奖励
String coin = sysConfigService.getValue("SYSTEM", "REWARD", "LOGIN_FRIST");
Map rewardMap = RewardSplitUtil.SplitReward(coin);
String rewardCoin = (String) rewardMap.get("rewardCoin");
String exerciseCoin = (String) rewardMap.get("exerciseCoin");
try {
//执行添加游戏币的服务
Map accountMap =new HashMap();
accountMap.put("userId", t.getId());
//默认充值账户
accountMap.put("accountType", 1);
accountMap.put("balance", rewardCoin);
userAccountService.addBalance(accountMap);
//执行添加练习账户的服务
Map accountMap1 =new HashMap();
accountMap1.put("userId", t.getId());
//默认充值账户
accountMap1.put("accountType", 2);
accountMap1.put("balance", exerciseCoin);
userAccountService.addBalance(accountMap1);
} catch (Exception e) {
e.printStackTrace();
}
isFirstLogin="1";
}else{//如果不是第一次登录,则执行修改的操作,更新数据库
//根据openId获取userId
User t = userService.getInfoByOpenId(openID);
user.setId(t.getId());
logger.info(t.getId()+"no first login");
userService.update(user);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return isFirstLogin;
}
小编在此就不细细说明了,有什么问题注释应该都写了,还有要问题的,可以联系QQ985548426.小编长期在线。
源码下载地址:https://download.csdn.net/download/a985548426/10752679