Vue displays the QR code, and WeChat scans the QR code to obtain the user's information.

Scan the QR code on WeChat to obtain user information (webpage authorization)

1. Requirements explanation

A common QR code is displayed on the vue page. The WeChat user uses the WeChat scan function to scan the QR code, and the user information of the WeChat user is obtained in the background.

2. Step preparation

1.Intranet penetration

It is currently a development environment, so intranet penetration is used to enable the external network to access the content of this machine.

1.1 Intranet penetration tool natapp

Click to enternatapp official website
Insert image description here
Register account=》 Login=》Purchase free tunnel
My tunnel< /span> Download natapp client
Insert image description here
Configure it yourself according to the actual situation of your project

1.2 Start natapp

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

The startup is successful as shown below (-authtoken= is followed by the corresponding authtoken in the natapp tunnel
Insert image description here

2. WeChat public account test account

2.1 Apply for a test number

Click to enter the WeChat public platform test account application page

2.2 Interface configuration information

Insert image description here
url: domain name + project name + interface path
Configuration rules and verification can be viewed at https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview. html

Background verification code reference:

 @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 Configure WeChat web page authorization URL

Insert image description here
Use domain name configuration
Insert image description here

3.vue QR code plug-in (qrcodejs2)

3.1 Plug-in installation

npm install  qrcodejs2 --save

3.2 Plug-in usage

Page introduction

import QRCode from "qrcodejs2"

QR code generation

//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
		});
	 });
},

The generated QR code is as follows
Insert image description here
After scanning on WeChat, it will jump to the custom link

4. Obtain information in the background

4.1 Jump authentication path

Scan the QR code and enter the interface corresponding to the QR code
//Get the teacher’s information and transfer it to the jump link

//根据自己的实际情况进行生成跳转链接
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 Agree to authorize to obtain access_token

After the user agrees to the authorization, he will jump to the customized redirection path with the code
This project jumps directly to the backend
Backend Interface request to obtain 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);

Specific instructionsWeChat official documents

4.4 Pull user information

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

Specific instructionsWeChat official documents

4.5 Customize WeChat api request weChatRequestGet method

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;
        }
    }

Guess you like

Origin blog.csdn.net/qq_41995299/article/details/108202778