微信公众号第三方登录,简单易懂

1.准备工作

1)登录微信公众号接口测试平台设置信息,地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
登录成功后可以看到测试用的appid和appsecret,这个在代码里面会用到。

在这里插入图片描述

2)需要设置网页授权在这里插入图片描述

这边需要填域名,如果没有域名,可以用内网穿透动态解析一个域名。这边用的是NATAPP,没有账号可以注册一个:https://natapp.cn/register
注册完毕后实名认证,选择免费通道,具体操作手册可参考:https://natapp.cn/article/minecraft
在这里插入图片描述
根据操作手册就是这样:
在这里插入图片描述

然后设置域名,这边要注意的是这个地址,只需要域名部分,下图是我映射好的地址,一定不能填错,不然在微信授权登录会一直报redirect_url错误
在这里插入图片描述

另外后面回调地址用微信访问的时候,使用的微信得先扫一下这个二维码关注一下才可以

2.代码部分

1)请求微信接口的工具类

package com.example.demo.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class AuthUtil {

    public static final String APPID = "wxca86e04bc4065918";
    public static final String APPSECRET = "cb44b8fa1791d5f2ea4e8c9eb4d2b963";
    //回调地址
    public static final String backUrl="http://mt4ynq.natappfree.cc/callBack";
    public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
        JSONObject jsonObject = null;
        //首先初始化HttpClient对象
        DefaultHttpClient client = new DefaultHttpClient();
        //通过get方式进行提交
        HttpGet httpGet = new HttpGet(url);
        //通过HTTPclient的execute方法进行发送请求
        HttpResponse response = client.execute(httpGet);
        //从response里面拿自己想要的结果
        HttpEntity entity = response.getEntity();
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = jsonObject.fromObject(result);
        }
        //把链接释放掉
        httpGet.releaseConnection();
        return jsonObject;
    }
}


2)controller类(版本1)

package com.example.demo.controller.wx;


import com.example.demo.util.AuthUtil;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/front/auth")
public class WxAuthorizeController {

    /**
     * Tea微信登录接口
     * @throws IOException
     */
    @RequestMapping("/wx_login")
    public void wxLogin(HttpServletResponse response) throws IOException {
        //域名(暂时写死的)
        String sym = "http://mt4ynq.natappfree.cc";
        //这里是回调的url
        String redirect_uri = URLEncoder.encode(sym + "/front/auth/callBack", "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=APPID" +
                "&redirect_uri=REDIRECT_URI" +
                "&response_type=code" +
                "&scope=SCOPE" +
                "&state=123#wechat_redirect";
        response.sendRedirect(url.replace("APPID", "wxca86e04bc4065918").replace("REDIRECT_URI", redirect_uri).replace("SCOPE", "snsapi_userinfo"));
    }

    /**
     * Tea微信授权成功的回调函数
     *
     * @param request
     * @param response
     * @throws IOException
     */

    @RequestMapping("/callBack")
    protected void deGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
        //获取回调地址中的code
        String code = request.getParameter("code");
        //拼接url  !!!!!!!!!!根据code获取openId和access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "wxca86e04bc4065918" + "&secret="
                + "cb44b8fa1791d5f2ea4e8c9eb4d2b963" + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        //1.获取微信用户的openid
        String openid = jsonObject.getString("openid");
        //2.获取获取access_token
        String access_token = jsonObject.getString("access_token");
        //!!!!!!!!!!!再根据access_token获取用户信息
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
                + "&lang=zh_CN";
        //3.获取微信用户信息
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        //至此拿到了微信用户的所有信息,剩下的就是业务逻辑处理部分了
        //保存openid和access_token到session
        request.getSession().setAttribute("openid", openid);
        request.getSession().setAttribute("access_token", access_token);
        //去数据库查询此微信是否绑定过手机
//        UserVo user = userService.queryByOpenId(openid);
//        String mobile=user==null?"":user.getMobile();

//        if(null == mobile || "".equals(mobile)){
//            //如果无手机信息,则跳转手机绑定页面
            String wareName1=URLEncoder.encode(userInfo.get("nickname").toString(), "UTF-8");
            response.sendRedirect("/front/auth/loginSucess?name="+wareName1);
//        }else{
//            //否则直接跳转首页
//            response.sendRedirect("/front/index.html");
//        }
    }

    @RequestMapping("/loginSucess")
    public String loginSucess(@PathParam("name")String name){
        return "wechat login sucesss "+name;
    }


}

版本2的代码步骤说明更详细

版本2

package com.example.demo.controller.wx;

import com.example.demo.dao.UserMapper;
import com.example.demo.entity.User;
import com.example.demo.util.AuthUtil;
import net.sf.json.JSONObject;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class WxV2Controller {

    @Resource
    private UserMapper userMapper;

    @RequestMapping(value="/wxlogin")
    public void wx(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //第一步:引导用户进入授权页面同意授权,获取code
        StringBuilder builder = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?appid=");
        builder.append(AuthUtil.APPID);
        builder.append("&redirect_uri=");
        builder.append(URLEncoder.encode(AuthUtil.backUrl));//开发文档要求转换
        builder.append("&response_type=code");
        builder.append("&scope=snsapi_userinfo");
        builder.append("&state=STATE#wechat_redirect");
        //授权页面地址
        //将StringBuilder转换成String
        String url=builder.toString();
        //重定向到授权页面
        response.sendRedirect(url);
    }

    @RequestMapping(value="/callBack")
    public String wxcallback(@RequestParam("code") String code, Model model)throws IOException {
        System.out.println("code:" + code);
        //获取code后,请求以下链接获取access_token
        StringBuilder builder = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?appid=");
        builder.append(AuthUtil.APPID);
        builder.append("&secret=");
        builder.append(AuthUtil.APPSECRET);
        builder.append("&code=");
        builder.append(code);
        builder.append("&grant_type=authorization_code");

        //通过网络请求方法来请求上面这个接口
        //将StringBuilder转换成String
        String url=builder.toString();
        JSONObject jsonObject = AuthUtil.doGetJson(url);

        System.out.println("==========================jsonObject" + jsonObject);
        //从返回的JSON数据中取出access_token和openid,拉取用户信息时用
        String token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        // 第三步:刷新access_token(如果需要)

        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        StringBuilder builder1 = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?access_token=");
        builder1.append(token);
        builder1.append("&openid=");
        builder1.append(openid);
        builder1.append("&lang=zh_CN");
        //通过网络请求方法来请求上面这个接口
        //将StringBuilder转换成String
        String infoUrl=builder1.toString();
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

        System.out.println("userInfo=======" + userInfo);

        //第1种情况:使用微信用户信息直接登录,无需注册和绑定
//        model.addAttribute("info",userInfo);
//        return "wx/wxtest1";
//

        //第2种情况:查看数据库是否存在相对应用户
        try {
            User wxuser = userMapper.findNameByopenId(openid);
            if (wxuser != null) {
                //已绑定
                model.addAttribute("info",userInfo);
                model.addAttribute("name", wxuser.getUsername());
                return "wx/wxtest2";

            } else {
                //未绑定
                model.addAttribute("openid", openid);
                return "wx/wxtest3";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wx/fail";   //跳转到登录失败页面
    }
}


3.测试

以版本1的controller为例,可浏览器请求:
(1)http://mt4ynq.natappfree.cc/front/auth/wxLogin获取code,并根据代码里面的重定向转发请求给callback接口;
(2)callback这里面根据code请求了微信接口获取openId和access_token;
(3)再根据获取的openid和access_token获取用户信息。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值