此方案用了session共享的方案,其实也可以把wechat的数据库id存在前端,看个人理解
package com.ruoyi.mobile.service.impl;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.mobile.contant.MConstant;
import com.ruoyi.mobile.form.DataForm;
import com.ruoyi.mobile.form.TokenForm;
import com.ruoyi.mobile.form.ValueNaturn;
import com.ruoyi.mobile.form.WeChatBean;
import com.ruoyi.mobile.mapper.MemberMapper;
import com.ruoyi.mobile.mapper.WechatInfoMapper;
import com.ruoyi.mobile.service.IProducerAwardLogService;
import com.ruoyi.mobile.service.IWechatInfoService;
import com.ruoyi.mobile.util.HttpClientUtils;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.domain.WechatInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 微信 服务层实现
*
* @author lsh
* @date 2019-11-18
*/
@Service
@Transactional
public class WechatInfoServiceImpl implements IWechatInfoService {
@Autowired
private HttpServletRequest request;
@Override
public Integer acceptCode(String code) throws Exception {
// 得到token资料
return acceptToken(code);
}
private String getUnionId(String openId) throws IOException {
String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
getAccessTokenUrl = getAccessTokenUrl.replace("APPID", apppId);
getAccessTokenUrl = getAccessTokenUrl.replace("APPSECRET", appSecret);
String str = HttpClientUtils.doGet(getAccessTokenUrl);
JSONObject parseObject = JSONArray.parseObject(str);
String accessToken = parseObject.getString("access_token");
String getUnionIdUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
getUnionIdUrl = getUnionIdUrl.replace("ACCESS_TOKEN", accessToken);
getUnionIdUrl = getUnionIdUrl.replace("OPENID", openId);
String res = HttpClientUtils.doGet(getUnionIdUrl);
System.out.println(res);
JSONObject jsonObject = JSONObject.parseObject(res);
/* String subscribe = jsonObject.get("subscribe").toString();
if ("0".equals(subscribe)) {
throw new BusinessException("该用户未关注公众号");
}*/
return jsonObject.get("unionid").toString();
}
@Override
public void weChatIdBindMember(Integer getid, Integer weChatId) {
WechatInfo wechatInfo = wechatInfoMapper.selectWechatInfoById(weChatId);
if (wechatInfo != null) {
wechatInfo.setmemId(getid);
wechatInfoMapper.updateWechatInfo(wechatInfo);
}
}
/**
* 通过session域里的微信id登录
*
* @param id
* @return
*/
@Override
public Map<String, Object> autoLogin(Integer id) {
WechatInfo wechatInfo = wechatInfoMapper.selectWechatInfoById(id);
Map<String, Object> map = new HashMap<>();
if (wechatInfo != null && wechatInfo.getmemId() != null) {
Member mem = memberMapper.selectMemberById(wechatInfo.getmemId());
if (mem != null) {
// 帮助用户自动登录创建token
map = memberTokenService.createMemberToken(mem.getid(), mem.getphoneNumber(), mem.getpassword());
map.put("memType", mem.getmemberType());
// 设置自动登录识别
map.put("AutoLogin", 1);
Boolean receive = producerAwardLogService.selectProducerAwardLogByMemberId(mem.getid());
map.put("receive", receive);
return R.ok(map);
} else {
wechatInfo.setmemId(null);
wechatInfo.setrenewalTime(new Date());
wechatInfoMapper.updateWechatInfo(wechatInfo);
}
}
map.put("AutoLogin", 0);
map.put("receive", false);
return map;
}
@Override
@Transactional
public R unBind(String code) throws IOException {
// 优先通过code获取entity
Integer integer = acceptToken(code);
if (integer != null) {
Integer integer1 = delWechatInfo(integer);
request.getSession().setAttribute("MOBILE_WECHAT_ID", integer1);
} else {
//如果通过code退出失败,备选方案从session取id逻辑删除
Integer mobilewechatid = (Integer) request.getSession().getAttribute("MOBILE_WECHAT_ID");
Integer integer1 = delWechatInfo(mobilewechatid);
request.getSession().setAttribute("MOBILE_WECHAT_ID", integer1);
}
return R.ok("0");
}
private Integer delWechatInfo(Integer id) {
WechatInfo wechatInfo = wechatInfoMapper.selectWechatInfoById(id);
wechatInfo.setisDel(1);
wechatInfo.setdelTime(new Date());
wechatInfoMapper.updateWechatInfo(wechatInfo);
wechatInfo.setid(null);
wechatInfo.setmemId(null);
wechatInfo.setdelTime(null);
wechatInfo.setisDel(0);
wechatInfo.setinsertTime(new Date());
wechatInfoMapper.insertWechatInfo(wechatInfo);
return wechatInfo.getid();
}
/**
* 获得token等信息
*/
private Integer acceptToken(String code) throws IOException {
String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
requestUrl = requestUrl.replace("APPID", apppId);
requestUrl = requestUrl.replace("SECRET", appSecret);
requestUrl = requestUrl.replace("CODE", code);
logger.info(requestUrl);
String httpGet = HttpClientUtils.doGet(requestUrl);
System.out.println(httpGet);
if (httpGet.contains("errcode")) {
logger.error("获得token出错,code值:" + code);
return null;
}
JSONObject jsonString = JSONObject.parseObject(httpGet);
TokenForm tokenForm = JSON.toJavaObject(jsonString, TokenForm.class);
String openid = tokenForm.getOpenid();
String unionid = tokenForm.getUnionid();
String refreshToken = tokenForm.getRefreshToken();
Integer integer = resultId(openid, unionid, refreshToken);
request.getSession().setAttribute("MOBILE_WECHAT_ID", integer);
return integer;
}
private Integer resultId(String openId, String unionId, String refreshToken) throws IOException {
WechatInfo wechatInfo = wechatInfoMapper.selectByOpenId(openId);
if (wechatInfo != null) {
wechatInfo.setrefreshToken(refreshToken);
String unionId1 = getUnionId(openId);
wechatInfo.setunionId(unionId1);
wechatInfoMapper.updateWechatInfo(wechatInfo);
return wechatInfo.getid();
} else {
wechatInfo = new WechatInfo();
// 设置刷新token
wechatInfo.setrefreshToken(refreshToken);
// 设置会员id
wechatInfo.setmemId(null);
// 设置openID
wechatInfo.setopenid(openId);
// 设置unionid
wechatInfo.setunionId(unionId);
// 设置未删除状态
wechatInfo.setisDel(MConstant.IS_DEL_FALSE);
// 设置插入人
wechatInfo.setinsertPerson("MOBILE");
// 设置插入时间
wechatInfo.setinsertTime(new Date());
wechatInfoMapper.insertWechatInfo(wechatInfo);
return wechatInfo.getid();
}
}
}
package com.ruoyi.mobile.form;
import java.io.Serializable;
import lombok.Data;
@Data
public class TokenForm implements Serializable {
/**
* 基础支持的access_token
*/
private String accessToken;
/**
* access_token接口调用凭证超时时间,单位(秒)
*/
private String expiresIn;
/**
* 用户刷新access_token
*/
private String refreshToken;
/**
* 用户唯一标识
*/
private String openid;
/**
* 用户唯一标识
*/
private String unionid;
/**
* 用户授权的作用域,使用逗号(,)分隔
*/
private String scope;
}