微信公众号授权

公众平台配置比较重要,将直接决定你是否可以成功!我从看文档到研究完实现效果,花了两天时间,所以想把过程详细记录下,希望可以对各位有直接性辅助的效果!

公众平台配置

首先打开微信公众平台,以微信公众号账号登陆进去,进入首页——开发者工具——公众平台测试账号
在这里插入图片描述
扫码,你会得到一个测试账号的appID和appsecret
然后页面往下拉:体验接口权限表——网页服务——网页帐号——网页授权获取用户基本信息,点击后面的修改,在里面配自己本机的IP或者你有域名配域名,我这里配的IP地址。配置这个是后面填redirect_url的时候,会校验你这边的域名,必须要一致。
在这里插入图片描述
不要看我说的那么轻松,这个我昨天加今天一个半个上午才搞通,遇到问题都是很搞人的。

前端发起授权获取code

创建一个授权页 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>

这里:AppID不用我说你填你的测试号AppID
redirect_uri这里你看官网是有说明的,首先网址是要urlcode转码的,中间的域名要填你之前配置在“网页授权获取用户基本信息”配置的域名。其他的没什么好说明的。

创建一个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;
				// }
			}
		});

这里urldata是外部引入的一个js,他的作用就是截取url里的参数。

导入一个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;
};

然后你去微信开发者工具(因为网页跳转没有用),打开访问auth.html界面,他会跳到index.html带code参数,然后再截取下来,发送给后端进行校验。

后台Java,写的很烂很烂,千万别喷

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

HttpClientUtils工具请自取

做个宣传

技术交流群,免费提供jerbrant系列 idea webstorm等工具自动化开启包
技术交流分享②群:272712006
技术交流分享③群:1093476453
bilibili学习教程地址:https://space.bilibili.com/439411741/video
简书地址:https://www.jianshu.com/p/133af2e4fe3f

猜你喜欢

转载自blog.csdn.net/Curtisjia/article/details/106065111