C#開發——網站應用微信登入開發

歸來時依然是少年發表於2018-12-10

1. 在微信開放平臺註冊開發者賬號,並有一個稽核已通過的網站應用,並獲得相對應的AppID和AppSecret,申請通過登陸後,方可開始接入流程。

2.微信OAuth2.0授權登入目前支援authorization_code模式,適用於擁有server端的應用授權。該模式整體流程為:

1. 第三方發起微信授權登入請求,微信使用者允許授權第三方應用後,微信會拉起應用或重定向到第三方網站,並且帶上授權臨時票據code引數;
2. 通過code引數加上AppID和AppSecret等,通過API換取access_token;
3. 通過access_token進行介面呼叫,獲取使用者基本資料資源或幫助使用者實現基本操作。

3.實現程式碼如下:

 

兩個類物件

public class user
{
public string access_token { get; set; } //介面呼叫憑證
public int expires_in { get; set; } //access_token介面呼叫憑證超時時間,單位(秒)
public string refresh_token { get; set; }  //使用者重新整理access_token
public string openid { get; set; } //授權使用者唯一標識
public string scope { get; set; } //使用者授權的作用域,使用逗號(,)分隔
public string unionid { get; set; } //當且僅當該網站應用已獲得該使用者的userinfo授權時,才會出現該欄位
}
public class Errmsg
{
public string errcode { get; set; }
public string errmsg { get; set; }
}

1. 若access_token已超時,那麼進行refresh_token會獲取一個新的access_token,新的超時時間;

2. 若access_token未超時,那麼進行refresh_token不會改變access_token,但超時時間會重新整理,相當於續期access_token。

refresh_token擁有較長的有效期(30天),當refresh_token失效的後,需要使用者重新授權。

 

public ActionResult WxLogin(string code,string state)
{
try
{
if (!string.IsNullOrWhiteSpace(code))
{
string Url = “https://api.weixin.qq.com/sns/oauth2/access_token?appid=******&secret=*******&code=” + code + “&grant_type=authorization_code”;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Proxy = null;
request.KeepAlive = false;
request.Method = “GET”;
request.ContentType = “application/json; charset=UTF-8”;
request.AutomaticDecompression = DecompressionMethods.GZip;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();

//轉為json物件
user u = Common.JsonHelper.JsonDeserialize<user>(retString);
if (u != null)
{
  Url = “https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=******&grant_type=refresh_token&refresh_token=” + u.refresh_token;
  request = (HttpWebRequest)WebRequest.Create(Url);
  request.Proxy = null;
  request.KeepAlive = false;
  request.Method = “GET”;
  request.ContentType = “application/json; charset=UTF-8”;
  request.AutomaticDecompression = DecompressionMethods.GZip;

  response = (HttpWebResponse)request.GetResponse();
  myResponseStream = response.GetResponseStream();
  myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  retString = myStreamReader.ReadToEnd();
  user us = Common.JsonHelper.JsonDeserialize<user>(retString);
  TUsers user = new TUsersLogic().GetTUsers(new TUsers() { OpenIDTwo = us.openid });
  if (user != null && user.ID > 0)
  {
    System.Web.HttpCookie cookie = new System.Web.HttpCookie(“CurrentUser-” + “ID”);
    cookie.Value = user.ID.ToString();
    cookie.Expires = DateTime.Now.AddDays(7);
    System.Web.HttpContext.Current.Response.AppendCookie(cookie);
    return Redirect(“/home/index”);
  }
  
  return View();
}
else
{
  Errmsg emsg= Common.JsonHelper.JsonDeserialize<Errmsg>(retString);
  return Json(new { errcode = emsg.errcode, errmsg = emsg.errmsg }, JsonRequestBehavior.AllowGet);
}
}
string url = Common.UrlHelper.CurrentUrl;
return Redirect(“https://open.weixin.qq.com/connect/qrconnect?appid=*******&redirect_uri=” + url + “&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect”);

}
catch (Exception e)
{
return Json(new { errormessage = e.Message });
}
}

請求引數及連結就不一一寫了,參考連結:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN




 

相關文章