程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成的微信網頁受權操作邏輯封裝示例

C#完成的微信網頁受權操作邏輯封裝示例

編輯:C#入門知識

C#完成的微信網頁受權操作邏輯封裝示例。本站提示廣大學習愛好者:(C#完成的微信網頁受權操作邏輯封裝示例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成的微信網頁受權操作邏輯封裝示例正文


本文實例講述了C#完成的微信網頁受權操作邏輯封裝。分享給年夜家供年夜家參考,詳細以下:

1、微信網頁受權登錄

條件:

1.曾經獲得的接口權限,假如是測試賬號就曾經有權限了

2.設置裝備擺設接口的受權域名

更多解釋可以參考方倍任務室:http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html

或許官網API:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

步調:

1.用戶贊成受權,獲得code

2.依據code 獲得access_token及以後操感化戶的openid、unionid

3.依據openid獲得用戶根本信息(假如須要的話)

注:假如想在網站應用掃一掃,受權登錄,可以講 _oauth.GetCodeUrl() 受權地址生成二維碼來應用

C#封裝微信網頁受權登錄應用實例:

string appid = "wx145b4a8fd07b24e8";
string appsecrect = "fe6951dcb99772411c42f724b1336065";
string redirect_url = "設置裝備擺設域名下的回調地址";
OAuthManage _oauth = null;
/// <summary>
///掌握器結構函數
/// </summary>
public UserController()
{
  _oauth = new OAuthManage(appid, appsecrect, redirect_url);
}
/// <summary>
/// 受權登錄
/// </summary>
/// <returns></returns>
public ActionResult AuthLogin()
{
  ViewBag.url = _oauth.GetCodeUrl();
  return View();
}
/// <summary>
/// 回調解理
/// </summary>
/// <returns></returns>
public ActionResult OAuthHandle()
{
  string result = "";
  //注冊事宜處置
  _oauth.OnError = (e) =>
  {
    string msg = "";
    Exception inner = e;
    while (inner != null)
    {
      msg += inner.Message;
      inner = inner.InnerException;
    }
    result = msg;
    LogOperate.Write(msg);
  };
  _oauth.OnGetTokenSuccess = (token) =>
  {
    result += "<br/>";
    result += token.ToJsonString();
  };
  _oauth.OnGetUserInfoSuccess = (user) =>
  {
    result += "<br/>";
    result += user.ToJsonString();
  };
  //第二步
  _oauth.GetAccess_Token();
  //第三步
  _oauth.GetUserInfo();
  //顯示成果
  ViewBag.msg = result;
  return View();
}

封裝代碼類界說:

namespace WXPackage
{
  /// <summary>
  /// 網頁受權邏輯處置,
  /// 處置三步操作,處置勝利,前往用戶根本信息
  /// </summary>
  public class OAuthManage
  {
    #region 根本信息界說
    /// <summary>
    /// "號的獨一標識
    /// </summary>
    private string appid;
    /// <summary>
    /// "號的appsecret
    /// </summary>
    private string secret;
    /// <summary>
    /// 回調url地址
    /// </summary>
    private string redirect_uri;
    /// <summary>
    /// 獲得微信譽戶根本信息應用snsapi_userinfo形式
    /// 假如應用靜默受權,沒法獲得用戶根本信息但可以獲得到openid
    /// </summary>
    private string scope;
    public OAuthManage(string appid, string appsecret, string redirect_uri, bool IsUserInfo = true)
    {
      this.appid = appid;
      this.secret = appsecret;
      this.redirect_uri = redirect_uri;
      this.scope = IsUserInfo ? "snsapi_userinfo" : "snsapi_base";
    }
    #endregion
    #region 要求進程信息
    /// <summary>
    /// 第一步獲得到的Code 值
    /// </summary>
    public string Code { get; set; }
    /// <summary>
    /// 第二步獲得到的access_token及相干數據
    /// </summary>
    public OAuthAccess_Token TokenData = null;
    #endregion
    #region 事宜界說
    /// <summary>
    /// 當處置湧現異常時,觸發
    /// </summary>
    public Action<Exception> OnError = null;
    /// <summary>
    /// 當獲得AccessToken勝利是觸發
    /// </summary>
    public Action<OAuthAccess_Token> OnGetTokenSuccess = null;
    /// <summary>
    /// 當獲得用戶信息勝利時觸發
    /// </summary>
    public Action<OAuthUser> OnGetUserInfoSuccess = null;
    #endregion
    #region 第二步,回調解理
    /// <summary>
    /// 第二步,經由過程code換取網頁受權access_token
    /// </summary>
    public void GetAccess_Token()
    {
      try
      {
        //1.處置跳轉
        this.Code = ReqHelper.GetString("code");
        if (string.IsNullOrEmpty(this.Code))
          throw new Exception("獲得code參數掉敗或用戶制止受權獲得根本信息");
        //1.發送獲得access_token要求
        string url = GetAccess_TokenUrl();
        string result = NetHelper.Get(url);
        //2.解析響應成果
        TokenData = JsonConvert.DeserializeObject<OAuthAccess_Token>(result);
        if (TokenData == null)
          throw new Exception("反序列化成果掉敗,前往內容為:" + result);
        //3.獲得勝利
        if (OnGetTokenSuccess != null)
          OnGetTokenSuccess(TokenData);
      }
      catch (Exception ex)
      {
        Error("第二步,經由過程code換取網頁受權access_token異常", ex);
      }
    }
    /// <summary>
    /// 刷新以後access_token
    /// </summary>
    public OAuthAccess_Token RefreshAccess_Token()
    {
      try
      {
        //1.發送要求
        string url = GetReferesh_TokenUrl();
        string result = NetHelper.Get(url);
        //2.解析成果
        OAuthAccess_Token token = JsonConvert.DeserializeObject<OAuthAccess_Token>(result);
        if (token == null)
          throw new Exception("反序列化成果掉敗,前往內容:" + result);
        return token;
      }
      catch (Exception ex)
      {
        Error("刷新以後access_token掉敗", ex);
        return null;
      }
    }
    #endregion
    #region 第三步,獲得用戶根本信息
    /// <summary>
    /// 第三步,獲得根本信息
    /// </summary>
    public void GetUserInfo()
    {
      try
      {
        //1.發送get要求
        string url = GetUserInfoUrl();
        string result = NetHelper.Get(url);
        //2.解析成果
        OAuthUser user = JsonConvert.DeserializeObject<OAuthUser>(result);
        if (user == null)
          throw new Exception("反序列化成果掉敗,前往內容:" + result);
        //3.獲得勝利
        if (OnGetUserInfoSuccess != null)
          OnGetUserInfoSuccess(user);
      }
      catch (Exception ex)
      {
        Error("第三步、獲得用戶根本信息異常", ex);
      }
    }
    #endregion
    #region 靜態辦法
    /// <summary>
    /// 驗證受權憑證能否有用
    /// </summary>
    /// <param name="access_token">access_token</param>
    /// <param name="openid">用戶針對以後"號的openid</param>
    /// <returns></returns>
    public static bool CheckWebAccess_Token(string access_token, string openid)
    {
      try
      {
        string url = string.Format("https://api.weixin.qq.com/sns/auth?access_token={0}&openid={1}",
       access_token,
       openid);
        string result = NetHelper.Get(url);
        JObject obj = JObject.Parse(result);
        int errcode = (int)obj["errcode"];
        return errcode == 0;
      }
      catch (Exception ex)
      {
        throw new Exception("," + ex.Message);
      }
    }
    #endregion
    #region 獲得要求銜接
    /// <summary>
    /// 獲得Code的url 地址
    /// </summary>
    /// <returns></returns>
    public string GetCodeUrl()
    {
      string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect",
        this.appid,
        SecurityHelper.UrlEncode(this.redirect_uri),
        this.scope);
      return url;
    }
    /// <summary>
    /// 獲得access_token的url地址
    /// </summary>
    /// <returns></returns>
    private string GetAccess_TokenUrl()
    {
      string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
        this.appid,
        this.secret,
        this.Code);
      return url;
    }
    /// <summary>
    /// 獲得刷新AccessToke的地址
    /// </summary>
    /// <returns></returns>
    private string GetReferesh_TokenUrl()
    {
      string url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}",
        this.appid,
        this.TokenData.refresh_token
        );
      return url;
    }
    /// <summary>
    /// 獲得用戶根本信息地址
    /// </summary>
    /// <returns></returns>
    private string GetUserInfoUrl()
    {
      string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN",
        this.TokenData.access_token,
        this.TokenData.openid);
      return url;
    }
    #endregion
    private void Error(string msg, Exception inner)
    {
      if (this.OnError != null)
      {
        this.OnError(new Exception(msg, inner));
      }
    }
  }
  /// <summary>
  /// 受權以後獲得用戶根本信息
  /// </summary>
  public class OAuthUser
  {
    public string openid { get; set; }
    public string nickname { get; set; }
    public int sex { get; set; }
    public string province { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public string headimgurl { get; set; }
    /// <summary>
    /// 用戶特權信息,json 數組
    /// </summary>
    public JArray privilege { get; set; }
    public string unionid { get; set; }
  }
  /// <summary>
  /// 獲得Access_Token或許刷新前往的數據對象
  /// </summary>
  public class OAuthAccess_Token
  {
    public string access_token { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
    /// <summary>
    /// 用戶針對以後"號的獨一標識
    /// 存眷後會發生,前往"號下頁面也會發生
    /// </summary>
    public string openid { get; set; }
    public string scope { get; set; }
    /// <summary>
    /// 以後用戶的unionid,只要在用戶將"號綁定到微信開放平台帳號後
    /// </summary>
    public string unionid { get; set; }
  }
}

願望本文所述對年夜家C#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved