一、获取Code
假设我们需要网页授权的页面的地址为redirect_uri
需要获取Code的话我们第一步是跳转到授权地址,我们第一步便是获取拼接授权地址 --采用snsapi_base方式
public partial class WebAuth : System.Web.UI.Page { string Appid = "XXXXXXXXXXXXXXXXXX"; string redirect_uri = "http://www.xxxxx.com/wx/GetUserInfor.aspx"; protected void Page_Load(object sender, EventArgs e) { string url = GetCodeUrl(Appid, redirect_uri); Response.Redirect(url); } /// <summary> /// 对页面是否要用授权 用snsapi_base方式 获取Code Appid是微信应用id /// </summary> /// <returns></returns> public string GetCodeUrl(string Appid, string redirect_uri) { return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", Appid, redirect_uri); } }
当在微信中打开如下地址的时候如果授权成功,会自动跳转到页面redirect_uri?code=CODE&state=STATE,这样我们就可以获取到Code了
二、用Code换取Openid、再用Openid获取用户的基本信息
用get方法获取到json格式的数据,
{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE", "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
public partial class GetUserInfor : System.Web.UI.Page { string Appid = "wxceefad22b094e8a9"; string Appsecret = "935c3d938aa26fa4f627b4926afd4b16"; protected void Page_Load(object sender, EventArgs e) { string code = Request["code"]; string openid = CodeGetOpenid(code); Dictionary<string, object> userInfor = GetUserInfo(openid); Response.Write(userInfor["nickname"]); } /// <summary> /// 用Code换取Openid /// </summary> /// <param name="Code"></param> /// <returns></returns> public string CodeGetOpenid(string Code) { string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code); string ReText = WebRequestHelper.WebRequestPostOrGet(url, "");//post/get方法获取信息 JavaScriptSerializer Jss = new JavaScriptSerializer(); Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText); if (!DicText.ContainsKey("openid")) return ""; return DicText["openid"].ToString(); } /// <summary> /// 用openid换取用户信息 /// </summary> /// <param name="openid">微信标识id</param> /// <returns></returns> public Dictionary<string, object> GetUserInfo(string openid) { JavaScriptSerializer Jss = new JavaScriptSerializer(); string access_token = AccessToken.GetAccessToken();//获取access_token string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", access_token, openid); Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(WebRequestHelper.WebRequestPostOrGet(url, "")); return respDic; //{"subscribe":1,"openid":"oOPoPs_d7K8mVLX6--WPMSbaNl5o","nickname":"SKY","sex":1,"language":"zh_CN","city":"武汉","province":"湖北","country":"中国","headimgurl":"http://wx.qlogo.cn/mmopen/icayX4JkqCu1d3esVCQ8rSfXlgibQLKaD3z73qhbPln3ZhMh5oNw5243vpoVZFXDKMhTqxQ76OzY934nlm3iaulq60058VmEV5v/0","subscribe_time":1495188935,"remark":"","groupid":0,"tagid_list":[]} } }
WebRequestHelper.WebRequestPostOrGet 方法如下:
public class WebRequestHelper { public static string WebRequestPostOrGet(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; } catch (Exception ex) { string err = ex.Message; return string.Format("{"errcode":-2,"errmsg":"{0}"}", err); } } }
说明:以上代码本人也是在网上搜索根本别人的代码综合参考改写而来。
如需要获取“未关注公众号的用户信息”,这个本人项目中还没有遇到,仅提供参考链接:http://www.cnblogs.com/net-xiejun/p/4632711.html