H5微信授权登录

H5微信授权登录

说明:最近因项目需要H5微信授权登录,流程走通之后,记录一下。

总体流程:

1.用户同意授权,获取code
2.通过code换取网页授权access_token
3.拉取用户信息(需scope为 snsapi_userinfo)

1.用户同意授权,获取code

1.1先去申请一个测试号 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
关注测试公众号,在网页服务 - 网页帐号 修改授权回调页面域名。测试阶段:先写的本地IP地址
登录事件:

wxLogin() {
		//测试号的appid
		let appID = 'wx198e8a0ccd18e67a'; // 测试使用
		let url ="回调url";
		let page =
			'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			appID +
			'&redirect_uri=' +
			url +
			'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
		window.location.href = page;
	}

用户同意授权后,页面将跳转至回调页面,并从地址返回code, redirect_uri/?code=CODE&state=STATE。
注意:获取code可以在微信开发者工具 - 公众号网址 - 地址栏 进行调试
截取code:

getCode() {
		console.log(window.location.href)
		let code = window.location.search;
		var theRequest = new Object();
		if (code.indexOf('?') != -1) {
			var str = code.substr(1);
			var strs = str.split('&');
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
			}
		}
		return theRequest;
	}

获取到code之后换取access_token,由于公众号的secret和获取到的access_token安全级别都非常高,必须只保存在服务器,不允许传给客户端。
所以前端只需获取code,code给后端传过去,获取用户信息。 第二步、第三步 由后端发起去请求微信服务器。

上一篇:牛客 字符串的全排列


下一篇:567.字符串的排列