12年的時候寫了些關於微信開發的內容,當時看好這個東西,惋惜當時騰訊開放的權限太少,以後的一年多時間沒有太關注了。html
如今又要從新開始微信開發的陣容了,微信只是個入口,微網站纔是趨勢。web
我是個水貨,因此寫的都是比較入門的,給初學者點啓發用的。json
這裏有3個文件,一個頁面展現(不貼代碼了,就兩個文本框和提交按鈕)和後臺代碼,一個方法類,一個實體類緩存
後臺代碼微信
protected void btnConfirm_Click(object sender, EventArgs e) { string name = txtName.Text; string pass = txtPass.Text; if (WeiXinLogin.ExecLogin(name, pass)) { Response.Write("登錄成功"); Response.Redirect("SendMessage.aspx"); } else { Response.Write("登錄失敗"); } }
方法類cookie
public static bool ExecLogin(string name, string pass) { bool result = false; string password = GetMd5Str32(pass).ToUpper(); string padata = "username=" + name + "&pwd=" + password + "&imgcode=&f=json"; string url = "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN";//請求登陸的URL try { CookieContainer cc = new CookieContainer();//接收緩存 byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 轉化 HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url); //新建一個WebRequest對象用來請求或者響應url webRequest2.CookieContainer = cc; //保存cookie webRequest2.Method = "POST"; //請求方式是POST webRequest2.ContentType = "application/x-www-form-urlencoded"; //請求的內容格式爲application/x-www-form-urlencoded webRequest2.Referer = "https://mp.weixin.qq.com/";//request的referer地址,網絡上的版本由於這句沒寫因此會出現invalid referrer webRequest2.ContentLength = byteArray.Length; Stream newStream = webRequest2.GetRequestStream(); //返回用於將數據寫入 Internet 資源的 Stream。 // Send the data. newStream.Write(byteArray, 0, byteArray.Length); //寫入參數 newStream.Close(); HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse(); StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default); string text2 = sr2.ReadToEnd(); HttpContext.Current.Response.Write("text2:" + text2 + "<br/>"); //此處用到了newtonsoft來序列化 WeiXinRetInfo retinfo = Newtonsoft.Json.JsonConvert.DeserializeObject<WeiXinRetInfo>(text2); string token = string.Empty; if (retinfo.redirect_url != null && retinfo.redirect_url.Length > 0) { token = retinfo.redirect_url.Split(new char[] { '&' })[2].Split(new char[] { '=' })[1].ToString();//取得令牌 LoginInfo.LoginCookie = cc; LoginInfo.CreateDate = DateTime.Now; LoginInfo.Token = token; result = true; } } catch (Exception ex) { HttpContext.Current.Response.Write("ex:" + ex.ToString()); //throw new Exception(ex.StackTrace); } return result; }
實體類網絡
public class WeiXinRetInfo//網絡上是另外一個版本,微信更新後換結構了 { public base_resp base_resp { get; set; } public string redirect_url { get; set; } } public class base_resp { public string ret { get; set; } public string err_msg { get; set; } }
這樣就完成了微信的模擬登陸~ 接下來的其餘步驟如獲取登錄用戶信息,羣發信息之類的若是遇到問題再記錄,沒問題的話不更新了。微信開發
參考文章app