12年的時候寫了些關於微信開發的內容,當時看好這個東西,可惜當時騰訊開放的權限太少,之后的一年多時間沒有太關注了。
現在又要重新開始微信開發的陣容了,微信只是個入口,微網站才是趨勢。
我是個水貨,所以寫的都是比較入門的,給初學者點啟發用的。
這里有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("登陸失敗");
}
}
方法類
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; }
}
這樣就完成了微信的模擬登錄~ 接下來的其他步驟如獲取登陸用戶信息,群發信息之類的如果遇到問題再記錄,沒問題的話不更新了。
參考文章
