WeChat official account authorization

The public platform configuration is more important and will directly determine whether you can succeed! It took me two days from looking at the document to studying the effect, so I want to record the process in detail, and hope that it will have a direct effect on you!

Public platform configuration

First open the WeChat public platform, log in with the WeChat public account account, and enter the homepage-Developer Tools-Public platform test account
Insert picture description here
Scan the code, you will get the appID and appsecret of a test account, and
then the page will drop down: Experience interface permission table- —Web service — web account — web authorization to obtain basic user information, click on the following modification, and configure your own IP in it or you have a domain name and domain name, and I configure the IP address here. When configuring this to fill in the redirect_url later, the domain name on your side will be verified, and it must be consistent.
Insert picture description here
Don't look at what I said so easily. I only figured it out yesterday plus one and a half mornings today. Any problems encountered are very messy.

The front end initiates authorization to obtain code

Create an authorization page auth.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	</body>
	<script type="text/javascript" src="js/jquery.min.js"></script>
	
	<script>
		$(document).ready(function(){
     
     
			window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcde95b1e2e57959c&redirect_uri=http%3A%2F%2F192.168.124.46%2Findex.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		})
	</script>
</html>

Here: AppID doesn’t need me to say you fill in your test number AppID
redirect_uri. Here you see the official website has instructions. First, the URL needs to be transcoded by urlcode, and the domain name in the middle needs to be filled in before you configure it in the "Web Authorization to Obtain Basic User Information" configuration Domain name. There is nothing else to explain.

Create an index.html:

var _code = '';
		var flag = true;
		$(window).load(function() {
			var code = urldata("code");
			if (code != '' && code != null) {
				_code = code;
				console.log('授权成功:' + _code);
				$.ajax({
					url: '/rest/wx/code',
					type: "POST",
					data: {
						code: _code
					},
					success: function() {
						alert("发送成功!");
					}
				})
			} else {
				console.log("发送失败!");
				//本页面发送请求
				// if (flag) {
				// 	window.location.href =
				// 		"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcde95b1e2e57959c&redirect_uri=http%3A%2F%2F192.168.124.46%2Findex.html&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
				// 	flag = false;
				// }
			}
		});

Here urldata is a js introduced from the outside, and its role is to intercept the parameters in the url.

Import a geturldata.js

function urldata(aa) {
    
    
	var params = new GetRequest();
	var bb = decodeURI(params[aa]);
	if (bb == null || bb == 'undefined' || bb == undefined || bb == 'null') {
    
    
		bb = '';
	}
	return bb;
}

function GetRequest() {
    
    
 var vars = {
    
    }, hash;
 var index_jinhao = window.location.href.indexOf('#');
 var str = window.location.href.slice(window.location.href.indexOf('?') + 1);
 if (index_jinhao != -1) {
    
    
  str = window.location.href.slice(window.location.href.indexOf('?') + 1,
   window.location.href.indexOf('#'));
 }
 var hashes = str.split('&');
 for (var i = 0; i < hashes.length; i++) {
    
    
  hash = hashes[i].split('=');
  vars[hash[0]] = hash[1];
 }
 return vars;
};

Then you go to the WeChat developer tool (because web page jump is useless), open the access auth.html interface, he will jump to index.html with code parameter, and then intercept it and send it to the backend for verification.

Backstage Java, bad writing, don't spray

    @RequestMapping(value = "/code", method = RequestMethod.POST)
    public String getCode(String code) {
    
    
        System.out.println(code);
        if (StringUtils.isNotEmpty(code)) {
    
    
            HashMap<String, Object> map = new HashMap<>();
            map.put("appid", ParamUtils.APPID);
            map.put("secret", ParamUtils.SECRET);
            map.put("code", code);
            map.put("grant_type", "authorization_code");
            String s = HttpClientUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", map);

            JSONObject jsonObject = JSONObject.parseObject(s);
//            System.out.println(jsonObject);
//            Object access_token = jsonObject.get("access_token");
//            Object expires_in = jsonObject.get("expires_in");
//            Object refresh_token = jsonObject.get("refresh_token");
//            Object openid = jsonObject.get("openid");
//            System.out.println("access_token: "+access_token+'\n'+"expires_in: "+expires_in+'\n'
//            +"refresh_token: "+refresh_token+"\n"+"openid: "+openid);

            String access_token = jsonObject.getString("access_token");
            String expires_in = jsonObject.getString("expires_in");
            String refresh_token = jsonObject.getString("refresh_token");
            String openid = jsonObject.getString("openid");
            System.out.println("access_token: " + access_token + '\n' + "expires_in: " + expires_in + '\n'
                    + "refresh_token: " + refresh_token + "\n" + "openid: " + openid);
            if (StringUtils.isNotEmpty(access_token) && StringUtils.isNotEmpty(openid)) {
    
    
                String url = "https://api.weixin.qq.com/sns/userinfo";
                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("access_token", access_token);
                map1.put("openid", openid);
                map1.put("lang", "zh_CN");
                String s1 = HttpClientUtils.doGet(url, map1);
                System.out.println(s1);
                return s1;
            }
        }
        return code;
    }

Please pick up the HttpClientUtils tool

Make a publicity

Technical exchange group, provide free automatic opening package for tools such as jerbrant series idea webstorm.
Technical exchange sharing ②group: 272712006
technical exchange sharing ③group: 1093476453
bilibili learning tutorial address: https://space.bilibili.com/439411741/video
简书 address : Https://www.jianshu.com/p/133af2e4fe3f

Guess you like

Origin blog.csdn.net/Curtisjia/article/details/106065111
Recommended