第一次開發微信版網頁,對最重要的獲取微信OpenId,特此記錄下來 1.首先得有appid和appsecret 1 1. public class WeiXin { 2 3 public static string appid { 4 get { 5 string _appid = "wx3xxxx ...
第一次開發微信版網頁,對最重要的獲取微信OpenId,特此記錄下來
1.首先得有appid和appsecret
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 }準備AppId和Appsecret
2.只獲取用戶的openID,,在確保微信公眾賬號擁有授權作用域(scope參數)的許可權的前提下(服務號獲得高級介面後,預設擁有scope參數中的snsapi_base和snsapi_userinfo),引導關註者打開如下頁面,以snsapi_base為scope發起的網頁授權,並且是靜默授權並自動跳轉到回調頁的。用戶感知的就是直接進入了回調頁(下麵代碼中的url參數就是回調頁,靜態的可以寫成:string url = https://wx.baidu.com/controller/GetOpenId,註意URL需要進行HttpUtility.UrlEncode(url)編碼,還有回調頁的功能變數名稱需要和微信公眾號裡面設置的回調功能變數名稱相同)
1 public class ApplyVIPController : Controller 2 2 { 3 3 4 4 // GET: /ApplyVIP/ 5 5 6 6 public ActionResult Index(string url) 7 7 { 8 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 9 WeiXin.appid, 10 10 url,//回調頁URL 11 11 Guid.NewGuid().ToString("N")); 12 12 return Redirect(_url);//這裡微信會自動取出回調頁URL,並且跳轉到該url所屬的頁面 13 13 }靜默授權並且跳轉回調頁
3.獲取code,並且通過code獲取Openid,正確時返回的JSON數據包如下:{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" },這裡面就包含了所需要的OPENID
1 //controller 2 public string GetOpenId() { 3 string code = requset.querystring["code"]; 4 string openid = ""; 5 string json = ""; 6 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 7 , WeiXin.appid, WeiXin.aseret, code); 8 HttpQuery.Get(url, null, msg => { 9 json = msg; 10 }); 11 JObject job = (JObject)JsonConvert.DeserializeObject(json); 12 openid = job["openid"].ToString(); 13 return openid; 14 }獲取到openID
4.請求獲取Openid的httpquery.get()方法
1 public class HttpQuery { 2 private static readonly string DefaultUserAgent = 3 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 4 5 public static void Get(string url, object data, Action<string> callback) { 6 IDictionary<string, string> parameters = Getparameters(data); 7 8 if (!(parameters == null || parameters.Count == 0)) { 9 url += "?"; 10 foreach (var item in parameters) { 11 url += item.Key + "=" + item.Value + "&"; 12 } 13 } 14 CreateGetHttpResponse(url, null, null, null, callback); 15 } 16 /// <summary> 17 /// 創建GET方式的HTTP請求 18 /// </summary> 19 /// <param name="url">請求的URL</param> 20 /// <param name="timeout">請求的超時時間</param> 21 /// <param name="userAgent">請求的客戶端瀏覽器信息,可以為空</param> 22 /// <param name="cookies">隨同HTTP請求發送的Cookie信息,如果不需要身份驗證可以為空</param> 23 /// <returns></returns> 24 private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, 25 CookieCollection cookies, Action<string> callback, string encoding = "utf-8") { 26 if (string.IsNullOrEmpty(url)) { 27 return null; 28 //throw new ArgumentNullException("url"); 29 } 30 try { 31 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 32 request.Method = "GET"; 33 request.UserAgent = DefaultUserAgent; 34 if (!string.IsNullOrEmpty(userAgent)) { 35 request.UserAgent = userAgent; 36 } 37 if (timeout.HasValue) { 38 request.Timeout = timeout.Value; 39 } 40 if (cookies != null) { 41 request.CookieContainer = new CookieContainer(); 42 request.CookieContainer.Add(cookies); 43 } 44 45 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse; 46 47 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(), 48 System.Text.Encoding.GetEncoding(encoding)); 49 50 string html = ""; 51 //獲取請求到的數據 52 html = reader.ReadToEnd(); 53 //關閉 54 httpWebResponse.Close(); 55 reader.Close(); 56 57 callback(html); 58 return httpWebResponse; 59 } 60 } catch { 61 callback(null); 62 } 63 return null; 64 } 65 66 }Http GET請求