简单实现微信授权登录测试代码

发布时间:2024年01月09日

阅读微信开放平台开发手册!!!

根据手册参考以下代码(简单明白大概实现流程即可):

package top.lxcxl.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lxcxl.entity.User;
import top.lxcxl.service.UserService;
import top.lxcxl.util.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/wechat")
public class WeChatLoginController {
@Autowired
private UserService userService;
    // 处理微信登录请求
    @GetMapping("/loginpre")
    public Result weChatLoginPre(HttpServletResponse response) throws IOException {
        //回调地址要在公网,且要经过URLEncoder处理
        String redirectUrl = "http://71a6437a.r20.cpolar.top/login";
        String uRL = URLEncoder.encode(redirectUrl, "UTF-8");
        String url= "https://open.weixin.qq.com/connect/qrconnect?appid=wx607881abe510da51" +
                "&redirect_uri=" +uRL+
                "&response_type=code&scope=snsapi_login" +
                "#wechat_redirect";
        //hutool生成在线二维码,输出到前台
        QrCodeUtil.generate(url, 300, 300, "png", response.getOutputStream());
        return Result.success("生成成功");
    }
    
    @PostMapping("/login")
    public Result login(String code) throws IOException {
    //登录
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=wx607881abe510da51&secret=80d4fccfcdfd894394d53c1e95eab9b1&code="+code+
                "&grant_type=authorization_code";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //发送http请求到微信验证
        CloseableHttpResponse execute = httpClient.execute(new HttpGet(url));
        String token = execute.getEntity().getContent().toString();
        //将微信验证后返回的json转换成map集合
        Map<String,String> map = JSON.parseObject(token, Map.class);
        //获取accessToken 
        String accessToken = map.get("access_token");
        String openid = map.get("openid");
        String getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?" +
                "access_token="+accessToken +
                "&openid="+openid;
                //发送http请求获取微信后台返回的用户信息
        HttpResponse getInfo = httpClient.execute(new HttpGet(getInfoUrl));
        String info = getInfo.getEntity().getContent().toString();
        Map<String,String> infoMap = JSON.parseObject(info, Map.class);
        //将用户信息封装进User,保存到数据库
        User user = new User();
            user.setId(openid);
            user.setName(infoMap.get("nickname"));
            user.setAvatar(infoMap.get("headimgurl"));
            user.setSex(infoMap.get("sex"));
            user.setCountry(infoMap.get("country"));
            user.setProvince(infoMap.get("province"));
            userService.insert(user);
        return Result.success(user);
    }
}
文章来源:https://blog.csdn.net/lx5210521/article/details/135471410
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。