微信開發之獲得使用者openid
阿新 • • 發佈:2019-02-11
上篇部落格中,介紹了傳送模版訊息的內容,其中涉及到一個步驟,給不同的使用者傳送模版訊息,就是通過openid來實現的,下面主要介紹一下專案中用到的openid .
一,是什麼?
openid是公眾號的普通使用者的一個唯一的標識,只針對當前的公眾號有效。開發者可以通過openid來獲取使用者基本資訊,但是要通過使用http協議來實現,只要獲得OpenID,就可以相繼獲得使用者的一些資訊,例如:所在的城市、省份、國家等。
獲取使用者openid有兩種方式,一種是使用者傳送訊息,微信伺服器會把openid推送給開發者,另一種是通過OAUth 2.0網頁授權獲取使用者openId。專案中用到的是通過網頁授權獲取使用者openid.
二,專案中的使用?
關於openid的使用網上資料當然有很多種情況,這裡只說明專案中用到的。每個使用者關注微信服務號之後,就可以登入此係統。登入系統時會獲得一個openid。
主要引數說明:
不同的手機登入會生成不同的openid,所以如果第一次登入,就會生成一個openid.生成的openid會寫入到資料庫中,下次就可以不用登入了。
登入生成程式碼:
<span style="font-family:KaiTi_GB2312;font-size:18px;"> /// <summary> /// 獲取openid /// </summary> /// <param name="url">請求的地址</param> /// <param name="encoding">內容編碼</param> /// <returns>openid</returns> public string getOpenid() { //使用 string appid = "wx74c205d460c704e3"; string secret = "fed07031712fa9a0f3bb729b1e336472"; string code = Request.QueryString["code"].ToString(); string grant_type = "authorization_code"; string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=" + grant_type; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; string html = HttpSend.GetPageContent(url, Encoding.UTF8); string key = "\"openid\":\""; int startIndex = html.IndexOf(key); if (startIndex != -1) { int endIndex = html.IndexOf("\",", startIndex); string openid = html.Substring(startIndex + key.Length, endIndex - startIndex - key.Length); return openid; } else { return "-1"; } }</span>
<span style="font-family:KaiTi_GB2312;font-size:18px;"> public class HttpSend { /// <summary> /// GET下載頁面內容 /// </summary> /// <param name="url">請求的地址</param> /// <param name="encoding">內容編碼</param> /// <returns></returns> public static string GetPageContent(string url, Encoding encoding) { string html = null; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream ioStream = response.GetResponseStream(); StreamReader sr = new StreamReader(ioStream, encoding); html = sr.ReadToEnd(); sr.Close(); ioStream.Close(); response.Close(); } catch (Exception ex) { throw ex; } return html; } }</span>
如果使用者想用別的賬號進行登入,就可以點選“解綁”,刪除此使用者的資訊,主要程式碼基本上和獲取類似。
三,文章推薦
在查詢資料的過程中發現很多,微信專門開發的資料,寫的非常詳細。記錄一下,也方便後面的學習。
(1)微信開發獲取Openid.(2)微信平臺開發者文件,這是比較權威的微信開發相關介面文件,其實微信提供了很多的介面,方便開發者的使用。
知道的只是皮毛,還需要好好研究。