微信用户授权,取openid

var appid = "wxb5f2540cff5c72be";
            var secret = "3de016d0c294b82a5c74ce3fc4865271";

            var openid = Response.Cookies["openid"];
            if (openid!=null&&openid.Value!=null&&!string.IsNullOrEmpty(openid.Value.ToString()))
            {
                //........
            }
            else
            {
                //取用户openid
                var code = Request.QueryString["Code"];
                if (string.IsNullOrEmpty(code))
                {
                    var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri=http%3a%2f%2fbsbw2011.gicp.net%2flogin.aspx&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", appid);
                    Response.Redirect(url);
                }
                else
                {
                    var client = new System.Net.WebClient();
                    client.Encoding = System.Text.Encoding.UTF8;

                    var url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);
                    var data = client.DownloadString(url);

                    var serializer = new JavaScriptSerializer();
                    var obj = serializer.Deserialize<Dictionary<string, string>>(data);
                    string accessToken;
                    if (!obj.TryGetValue("access_token", out accessToken))
                        return;

                    var opentid = obj["openid"];
                    HttpCookie openidCookie = new HttpCookie("openid");
                    openidCookie.Value = opentid;
                    openidCookie.Expires = DateTime.Now.AddYears(1);
                    this.Response.Cookies.Add(openidCookie);

                    //......
                }
            }
原文地址:https://www.cnblogs.com/shenyixin/p/4633352.html