Fancy
2024-12-27 c62ec58c827e780c4fb039f03149884c10ba0c52
pms-parent/pms-web-wechat/src/main/java/com/dy/pmsWechat/login/WeChatService.java
@@ -3,12 +3,14 @@
import com.alibaba.fastjson2.JSONObject;
import com.dy.pmsGlobal.daoMp.MpOpenIdMapper;
import com.dy.pmsGlobal.pojoMp.MpOpenId;
import com.dy.pmsWechat.util.JwtUtil;
import com.dy.pmsWechat.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@@ -23,6 +25,12 @@
    @Value("${wechat.loginUrl}")
    private String loginUrl;
    @Value("${wechat.jwt.secret-key}")
    private String secretKey;
    @Value("${wechat.jwt.ttl}")
    private  long  ttlMillis;
    private final RestTemplateUtil restTemplateUtil;
    private MpOpenIdMapper mpOpenIdDao;
@@ -44,21 +52,21 @@
        queryParams.put("grant_type", "authorization_code");
        Map<String, String> headerParams = new HashMap<>();
        JSONObject  wxMpUser = restTemplateUtil.get(loginUrl, queryParams, headerParams);
        String openId = wxMpUser.get("openid").toString();
        //获取微信信息添加到数据库  //先根据openid查询用户信息
        MpOpenId userInfo = mpOpenIdDao.getInfoByOpenId(wxMpUser.get("openid").toString());
        MpOpenId userInfo = mpOpenIdDao.getInfoByOpenId(openId);
        if(userInfo == null){ //数据库没有时添加到数据库中
            userInfo = new MpOpenId();
            userInfo.setOpenId(wxMpUser.get("openid").toString());
            userInfo.setOpenId(openId);
            userInfo.setCreateTime(new Date());
            mpOpenIdDao.insert(userInfo);
        }
        //授权完成之后,跳转到具体的功能页面
        //生成token,按照一定规则生成字符串,可以包含用户信息
        String token= JwtHelper.createToken(userInfo.getId(),userInfo.getNickName());
        //localhost:8080/weixin?a=1&token=222
        if(returnUrl.indexOf("?")==-1){//若returnUrl中没有参数
            return "redirect:"+returnUrl+"?token="+token;
        }else{
            return "redirect:"+returnUrl+"&token="+token;
        }
        //登陆controller中生成,返回给客户端
        Map<String, Object> claims = new HashMap<>();
        claims.put("openId",openId);
        String token = JwtUtil.createJwt(secretKey,ttlMillis,claims);
        return new JSONObject().fluentPut("token",token);
    }
}