vue显示二维码,微信扫描二维码获取用户的信息

微信扫描二维码获取用户的信息(网页授权)

一、需求解说

在vue页面显示一个普通二维码,微信用户使用微信扫一扫功能扫描二维码,后台获取到该微信用户的用户信息

二、步骤准备

1.内网穿透

当前是开发环境,所以使用内网穿透使外网能够访问到本机的内容

1.1内网穿透工具natapp

点击进入natapp官网
在这里插入图片描述
注册账号 =》 登录 =》购买免费隧道
我的隧道
在这里插入图片描述
根据自己项目的实际情况自行配置
下载natapp客户端

1.2启动natapp

1、点击下载好的natapp.exe进入命令行界面
2、使用命令启动 natapp -authtoken=1b2d363c3a5ea50d

启动成功如下图(-authtoken=后接的是natapp隧道中对应的authtoken
在这里插入图片描述

2.微信公众号测试号

2.1申请测试号

点击进入微信公众平台测试号申请页

2.2接口配置信息

在这里插入图片描述
url:域名+项目名+接口路径
配置规则与验证可查看网址https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html

后台验证代码参考:

 @RequestMapping(value = "oauth")
    public void oauth(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    

        System.out.println("========WechatController========= ");
        Enumeration pNames = request.getParameterNames();
        while (pNames.hasMoreElements()) {
    
    
            String name = (String) pNames.nextElement();
            String value = request.getParameter(name);
            // out.print(name + "=" + value);

            String log = "name =" + name + "     value =" + value;
            System.out.println(log);
        }

        String signature = request.getParameter("signature");/// 微信加密签名
        String timestamp = request.getParameter("timestamp");/// 时间戳
        String nonce = request.getParameter("nonce"); /// 随机数
        String echostr = request.getParameter("echostr"); // 随机字符串
        PrintWriter out = response.getWriter();

		//判断逻辑

        //判断信息正确后返回该内容,失败后不返回
        out.print(echostr);

        out.close();

    }

2.3配置微信网页授权网址

在这里插入图片描述
使用域名配置
在这里插入图片描述

3.vue二维码插件(qrcodejs2 )

3.1插件安装

npm install  qrcodejs2 --save

3.2插件使用

页面引入

import QRCode from "qrcodejs2"

二维码生成

//dom代码
<div v-if="qrCodeVisible">
	<div id="qrcode" @contextmenu.prevent="handleReset" style="width: 160px;height: 160px"></div>
	<p>请使用微信扫描二维码</p>
</div> 

生成方法
qrCode() {
	//服务器根目录访问路径,域名+项目名(供微信跳转链接使用)
	let pre = "http://8jt7n4.natappfree.cc/api/";
	let date = moment(new Date());
	//二维码对应的链接
	let url = pre +接口路径+ "?timestamp=" + date;
	this.$nextTick(function () {
	document.getElementById("qrcode").innerHTML = "";
		let qrcode = new QRCode("qrcode", {
			width: 150,
			height: 150,
			text: url,
			correctLevel: 3
		});
	 });
},

生成的二维码如下
在这里插入图片描述
微信扫描后将跳转到自定义链接

4.后台获取信息

4.1跳转鉴权路径

扫描二维码后进入二维码对应的接口中
//获取到教师的信息传输到跳转链接

//根据自己的实际情况进行生成跳转链接
String redirect_uri = preUrl + "WeChatManager/invoke";
//调用授权链接使微信跳转授权页
Authorization(response, redirect_uri);
private void Authorization(HttpServletResponse response, String uri) throws IOException {
    
    
	//链接需要先进行utf8编码
    try {
    
    
        uri = URLEncoder.encode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
    
    
        e.printStackTrace();
    }
	//uri为同意授权后跳转的链接
    //生成微信网页授权的url
    String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"
            + "appid=" + appId
            + "&redirect_uri=" + uri
            + "&response_type=code"
            + "&scope=snsapi_userinfo"
            + "&state=STATE#wechat_redirect";

    response.sendRedirect(url);
}

4.3同意授权获取access_token

用户同意授权后将会携带code一起跳转到自定义的重定向路径中
本项目直接跳转至后台
后台接口请求获取access_token

//根据code去请求access_token和openid等信息,请求链接如下,JsonNode接收返回信息
        String getTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + appId
                + "&secret=" + appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";
       JsonNode jsonNode = weChatRequestGet(getInfoUrl);

具体说明微信官方文档

4.4拉取用户信息

//生成获取用户信息的api链接JsonNode接收返回信息
        String getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token=" + access_token
                + "&openid=" + openid
                + "&lang=zh_CN";
       JsonNode jsonNode = weChatRequestGet(getInfoUrl);

具体说明微信官方文档

4.5自定义微信api请求weChatRequestGet方法

private JsonNode weChatRequestGet(String url) throws IOException {
    
    
        JsonNode jsonNode = null;

        HttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        ObjectMapper mapper = new ObjectMapper();

        if (entity != null) {
    
    
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonNode = mapper.readTree(result);
            System.out.println(result);
            return jsonNode;
        } else {
    
    
            return null;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_41995299/article/details/108202778