微信开发获取用户OpenID_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 微信开发获取用户OpenID

微信开发获取用户OpenID

 2017/8/11 12:31:20  六月雨  程序员俱乐部  我要评论(0)
  • 摘要:第一次开发微信版网页,对最重要的获取微信OpenId,特此记录下来1.首先得有appid和appsecret11.publicclassWeiXin{23publicstaticstringappid{4get{5string_appid="wx3xxxxxxxxxxxxxxx";6return_appid;7}8}9publicstaticstringaseret{10get{11stringappsecret="b6719276d539796d94bxxxxxxxxxxxxxxx"
  • 标签:用户 开发

 第一次开发微信版网页,对最重要的获取微信OpenId,特此记录下来

1.首先得有appid和appsecret

class="code_img_closed" src="/Upload/Images/2017081112/0015B68B3C38AA5B.gif" alt="">
 1 1.    public class WeiXin {
 2 
 3         public static string appid {
 4             get {
 5                 string _appid = "wx3xxxxxxxxxxxxxxx";
 6                 return _appid;
 7             }
 8         }
 9         public static string aseret {
10             get {
11                 string appsecret = "b6719276d539796d94bxxxxxxxxxxxxxxx";
12                 return appsecret;
13             }
14         }
15 
16 }
logs_code_collapse">准备appid和appsecret

2.只获取用户的openID,以snsapi_base为scope发起的网页授权,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(下面代码中的url参数就是回调页,这里使用的是动态的,静态的可以写成:http://wx.baidu.com/controller/GetOpenId)

 1     public class ApplyVIPController : Controller
 2     {
 3 
 4         // GET: /ApplyVIP/     
 5 
 6         public ActionResult Index(string url)
 7         {
 8             string _url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect",
 9                 WeiXin.appid,
10                 url,//回调页URL
11                 Guid.NewGuid().ToString("N"));
12             return Redirect(_url);//这里微信会自动取出回调页URL,并且跳转到该url所属的页面
13         }
静默授权并且跳转回调页

3.获取code,并且通过code获取Openid

       //controller
 public string GetOpenId() {
            string code = requset.querystring["code"];
            string openid = "";
            string json = "";
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code "//通过appid,appaseret,code
    , WeiXin.appid, WeiXin.aseret, code);
            HttpQuery.Get(url, null, msg => {
                json = msg;
            });
            JObject job = (JObject)JsonConvert.DeserializeObject(json);
            openid = job["openid"].ToString();
            return openid;
        }
        
View Code

4.请求获取Openid的httpquery.get()方法

    public class HttpQuery {
        private static readonly string DefaultUserAgent =
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

        public static void Get(string url, object data, Action<string> callback) {
            IDictionary<string, string> parameters = Getparameters(data);

            if (!(parameters == null || parameters.Count == 0)) {
                url += "?";
                foreach (var item in parameters) {
                    url += item.Key + "=" + item.Value + "&";
                }
            }
            CreateGetHttpResponse(url, null, null, null, callback);
        }
        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
            CookieCollection cookies, Action<string> callback, string encoding = "utf-8") {
            if (string.IsNullOrEmpty(url)) {
                return null;
                //throw new ArgumentNullException("url");
            }
            try {
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";
                request.UserAgent = DefaultUserAgent;
                if (!string.IsNullOrEmpty(userAgent)) {
                    request.UserAgent = userAgent;
                }
                if (timeout.HasValue) {
                    request.Timeout = timeout.Value;
                }
                if (cookies != null) {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;

                StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
                    System.Text.Encoding.GetEncoding(encoding));

                string html = "";
                //获取请求到的数据
                html = reader.ReadToEnd();
                //关闭
                httpWebResponse.Close();
                reader.Close();
      
                    callback(html);
                    return httpWebResponse;
                }
            } catch {
                callback(null);
            }
            return null;
        }

}
View Code

 

发表评论
用户名: 匿名