微信开封平台——保存用户信息(4)

UserServiceImpl

@Override
public User saveWeChatUser(String code) {

    String accessTokenUrl = String.format(WeChatConfig.getOpenAccessTokenUrl(),weChatConfig.getOpenAppid(),weChatConfig.getOpenAppsecret(),code);

    //获取access_token
    Map<String ,Object> baseMap =  HttpUtils.doGet(accessTokenUrl);

    if(baseMap == null || baseMap.isEmpty()){ return  null; }
    String accessToken = (String)baseMap.get("access_token");
    String openId  = (String) baseMap.get("openid");

    User dbUser = userMapper.findByopenid(openId);

    if(dbUser!=null) { //更新用户,直接返回
        return dbUser;
    }

    //获取用户基本信息
    String userInfoUrl = String.format(WeChatConfig.getOpenUserInfoUrl(),accessToken,openId);
        //获取access_token
    Map<String ,Object> baseUserMap =  HttpUtils.doGet(userInfoUrl);

    if(baseUserMap == null || baseUserMap.isEmpty()){ return  null; }
    String nickname = (String)baseUserMap.get("nickname");

    Double sexTemp  = (Double) baseUserMap.get("sex");
    int sex = sexTemp.intValue();
    String province = (String)baseUserMap.get("province");
    String city = (String)baseUserMap.get("city");
    String country = (String)baseUserMap.get("country");
    String headimgurl = (String)baseUserMap.get("headimgurl");
    StringBuilder sb = new StringBuilder(country).append("||").append(province).append("||").append(city);
    String finalAddress = sb.toString();
    try {
        //解决乱码
        nickname = new String(nickname.getBytes("ISO-8859-1"), "UTF-8");
        finalAddress = new String(finalAddress.getBytes("ISO-8859-1"), "UTF-8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    System.out.println(""+finalAddress);
//在这里根据User进行数据的插入
    User user = new User();
    user.setName(nickname);
    user.setHeadImg(headimgurl);
    user.setCity(finalAddress);
    user.setOpenid(openId);
    user.setSex(sex);
    user.setCreateTime(new Date());
    userMapper.save(user);
    return user;
}

dao

根据数据库的类型进行设置mapper

public interface UserMapper {


    /**
     * 根据主键id查找
     * @param userId
     * @return
     */
    @Select("select * from user where id = #{id}")
    User findByid(@Param("id") int userId);

    /**
     * 根据openid找用户
     * @param openid
     * @return
     */
    @Select("select * from user where openid = #{openid}")
    User findByopenid(@Param("openid") String openid);


    /**
     * 保存用户新
     * @param user
     * @return
     */
    @Insert("INSERT INTO `user` ( `openid`, `name`, `head_img`, `phone`, `sign`, `sex`, `city`, `create_time`)" +
            "VALUES" +
            "(#{openid},#{name},#{headImg},#{phone},#{sign},#{sex},#{city},#{createTime});")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
    int save(User user);


}

 controller

验证扫码同意之后跳转到这里

@GetMapping("/user/callback")
public void wechatUserCallback(@RequestParam(value = "code",required = true) String code,
                               String state, HttpServletResponse response){


    User user = userService.saveWeChatUser(code);  //因为这所以返回值为user类
    if(user != null){
        //生成jwt

    }

到这里数据就插入到了数据库

生成JWT回写给用户:

    @GetMapping("/")
    public void wechatUserCallback(@RequestParam(value = "code",required = true)String code,
                                   String state, HttpServletResponse response) throws IOException {

        User user = userService.saveWechatUser(code);
        /**
         * user有信息
         * 生成jwt
         * 重定向返回给前端
         */
        if (user!=null){
            String jwt= JwtUtils.geneJsonWebToken(user);

/**
 * state 要拼接http: 这样才能够进行重定向
 */
            response.sendRedirect(state+"?token="+jwt+"&head_img="+user.getHeadImg()+"&name="+URLEncoder.encode(user.getName(),"UTF-8"));
        }


    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智达教育‍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值