前段demo
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <script> window.location.href ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9749***5529bf8a&redirect_uri=http://wechat.***.com/page3.html&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect" </script> </body> </html>
page3.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <script> function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; } var obj = GetRequest(); console.log(obj); var code = obj.code; console.log(code); $.get("http://api2.***.com/api/OfficialAccounts/GetWeChatInfo?code="+code, function (result) { alert(result); }); </script> <p>test3</p> </body> </html>
后端代码:
/// <summary> /// 根据code获取openid与用户信息 /// </summary> /// <param name="code"></param> /// <returns></returns> public IActionResult GetWeChatInfo(string code) { string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx****bf8a&secret=8781****998a273&code=" + code + "&grant_type=authorization_code"; string result = HttpUtil.Get(url); var openInfo = JsonConvert.DeserializeAnonymousType(result, new { access_token = "", refresh_token = "", expires_in = 0, openid = "", scope = "" }); string urlStr2 = "https://api.weixin.qq.com/sns/userinfo?access_token="+openInfo.access_token+"&openid="+openInfo.openid+"&lang=zh_CN"; string result2 = HttpUtil.Get(urlStr2); var userinfo = JsonConvert.DeserializeAnonymousType(result2, new { openid="", nickname ="", sex =1, language ="", city ="", province ="", country ="", headimgurl ="", privilege =new List<dynamic>()}); return Content(result2); }