作者:开卷_汤娅造_673 | 来源:互联网 | 2023-09-02 10:46
controller层ApiOperation(value用户是否登录过小程序,httpMethodPOST)GetMapping(valueisLogin)pub
controller层
@ApiOperation(value = "用户是否登录过小程序", httpMethod = "POST")
@GetMapping(value = "isLogin")
public RespList isLogin(@RequestParam("code") String code) {RespList base = new RespList();System.out.println("code--->" + code);if (!StringUtils.isNotEmpty(code)) {log.info("code为空!!!!");base.setMessage("code为空!!!!");return base;}Map f = commonService.isLogin(code);base.setResult(f);base.setCode(0);return base;}@PostMapping(value = "miniLogin")
@ApiOperation(value = "小程序用户授权 注册", httpMethod = "POST")
public RespList doLogin(@RequestBody WxMiniVo wxMiniVo) {log.info("----------->Start get SessionKey");RespList respList = new RespList();Map map = commonService.miniLogin(wxMiniVo);respList.setResult(map);respList.setCode(0);System.out.println("-------返回的map----->" + map);return respList;}@PostMapping(value = "miniGetPhone")@ApiOperation(value = "小程序授权手机号", httpMethod = "POST")public RespList doGetPhone(@RequestBody WxMiniVo wxMiniVo) {log.info("----------->Start get SessionKey");Map map = commonService.getPhone(wxMiniVo.getSkey(), wxMiniVo.getEncrypteData(), wxMiniVo.getIv());RespList respList = new RespList();respList.setCode(0);respList.setResult(map);System.out.println("-------返回的map----->" + map);System.out.println("respList------>" + respList);return respList;}
service层
&#64;AutowiredStringRedisTemplate redisTemplate;public Map isLogin(String code) {Map map &#61; new HashMap();JSONObject SessionKeyOpenId &#61; MiniWxUtil.getSessionKeyOropenid(code);if (SessionKeyOpenId.get("errcode") !&#61; null) {map.put("msg", SessionKeyOpenId.get("errmsg"));return map;}String openid &#61; SessionKeyOpenId.getString("openid");String sessionKey &#61; SessionKeyOpenId.getString("session_key");//数据库根据openid查询用户CommonEntity user &#61; this.baseMapper.selectOne(new QueryWrapper().eq("open_id", openid));JSONObject sessionObj &#61; new JSONObject();boolean isLogin &#61; false;if (user !&#61; null) {//已存在sessionObj.put("userId", user.getUserId());map.put("userInfo", user);isLogin &#61; true;}//根据openid查询skey是否存在String skey_redis &#61; redisTemplate.opsForValue().get(openid);if (org.apache.commons.lang.StringUtils.isNotBlank(skey_redis)) {//存在 删除 skey 重新生成skey 将skey返回redisTemplate.delete(skey_redis);redisTemplate.delete(openid);}//缓存一份新的sessionObj.put("openId", openid);sessionObj.put("sessionKey", sessionKey);//uuid生成唯一keyString skey &#61; UUID.randomUUID().toString();//两小时过期redisTemplate.opsForValue().set(skey, sessionObj.toJSONString(), 120, TimeUnit.MINUTES);redisTemplate.opsForValue().set(openid, skey);//把新的sessionKey和oppenid返回给小程序前端map.put("skey", skey);map.put("isLogin", isLogin);return map;}public Map miniLogin(WxMiniVo wxMiniVo) {Map map &#61; new HashMap();String s &#61; redisTemplate.opsForValue().get(wxMiniVo.getSkey());JSONObject json &#61; JSONObject.parseObject(s);String sessionKey &#61; (String) json.get("sessionKey");String userId &#61; (String) json.get("userId");String openId &#61; (String) json.get("openId");CommonEntity user &#61; new CommonEntity();JSONObject userInfo &#61; MiniWxUser.getUserInfo(wxMiniVo.getEncrypteData(), sessionKey, wxMiniVo.getIv());if (userId !&#61; null) {//缓存中有user.setUserId(userId);} else {user.setUserId(UUID.randomUUID().toString());}user.setUserImg((String) userInfo.get("avatarUrl"));user.setUserName((String) userInfo.get("nickName"));user.setUserSex((Integer) userInfo.get("gender"));//性别user.setUserRole(wxMiniVo.getRole());user.setOpenId(openId);//数据库添加用户信息this.baseMapper.insert(user);map.put("userInfo", user);return map;}public Map getPhone(String skey, String encrypteData, String iv) {Map map &#61; new HashMap();String s &#61; redisTemplate.opsForValue().get(skey);JSONObject json &#61; JSONObject.parseObject(s);String key &#61; (String) json.get("sessionKey");String userId &#61; (String) json.get("userId");JSONObject userInfo &#61; MiniWxUser.getUserInfo(encrypteData, key, iv);String phoneNumber &#61; (String) userInfo.get("phoneNumber");CommonEntity commonEntity &#61; new CommonEntity();commonEntity.setUserPhone(phoneNumber);commonEntity.setUserId(userId);int x &#61; this.baseMapper.updateById(commonEntity);if (x <0) {map.put("msg", "操作有误!");}map.put("phone", phoneNumber);return map;}
工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;import java.util.HashMap;
import java.util.Map;
&#64;Component
&#64;Slf4j
public class MiniWxUtil {
// &#64;Value("${spring.cloud.wx.app-secret}")private static String appSecret&#61;"xxxx";// &#64;Value("${spring.cloud.wx.app-id}")private static String appId&#61;"xxxx";public static JSONObject getSessionKeyOropenid(String code) {//微信端登录code值String wxCode &#61; code;String requestUrl &#61; "https://api.weixin.qq.com/sns/jscode2session"; //请求地址 https://api.weixin.qq.com/sns/jscode2sessionMap requestUrlParam &#61; new HashMap();requestUrlParam.put("appid", appId); //开发者设置中的appIdrequestUrlParam.put("secret", appSecret); //开发者设置中的appSecretrequestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的coderequestUrlParam.put("grant_type", "authorization_code"); //默认参数log.info(requestUrlParam.toString());//发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识JSONObject jsonObject &#61; JSON.parseObject(UrlUtil.sendPost(requestUrl, requestUrlParam));return jsonObject;}}
实体类
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;&#64;Data
public class WxMiniVo {private String skey;private String encrypteData;private String iv;&#64;ApiModelProperty(notes &#61; "角色 0为选工 1为技客")private Integer role;
}
有问题评论!!!✌