国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實(shí)現(xiàn)的微信網(wǎng)頁授權(quán)操作邏輯封裝示例

2019-10-29 21:20:24
字體:
供稿:網(wǎng)友

本文實(shí)例講述了C#實(shí)現(xiàn)的微信網(wǎng)頁授權(quán)操作邏輯封裝。分享給大家供大家參考,具體如下:

一、微信網(wǎng)頁授權(quán)登錄

前提:

1.已經(jīng)獲取的接口權(quán)限,如果是測試賬號(hào)就已經(jīng)有權(quán)限了

2.配置接口的授權(quán)域名

更多說明可以參考方倍工作室:http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html

或者官網(wǎng)API:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

步驟:

1.用戶同意授權(quán),獲取code

2.根據(jù)code 獲取access_token及當(dāng)前操作用戶的openid、unionid

3.根據(jù)openid獲取用戶基本信息(如果需要的話)

注:如果想在網(wǎng)站使用掃一掃,授權(quán)登錄,可以講 _oauth.GetCodeUrl() 授權(quán)地址生成二維碼來使用

C#封裝微信網(wǎng)頁授權(quán)登錄使用實(shí)例:

string appid = "wx145b4a8fd07b24e8";string appsecrect = "fe6951dcb99772411c42f724b1336065";string redirect_url = "配置域名下的回調(diào)地址";OAuthManage _oauth = null;/// <summary>///控制器構(gòu)造函數(shù)/// </summary>public UserController(){  _oauth = new OAuthManage(appid, appsecrect, redirect_url);}/// <summary>/// 授權(quán)登錄/// </summary>/// <returns></returns>public ActionResult AuthLogin(){  ViewBag.url = _oauth.GetCodeUrl();  return View();}/// <summary>/// 回調(diào)處理/// </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();  //顯示結(jié)果  ViewBag.msg = result;  return View();}

封裝代碼類定義:

namespace WXPackage{  /// <summary>  /// 網(wǎng)頁授權(quán)邏輯處理,  /// 處理三步操作,處理成功,返回用戶基本信息  /// </summary>  public class OAuthManage  {    #region 基本信息定義    /// <summary>    /// 公眾號(hào)的唯一標(biāo)識(shí)    /// </summary>    private string appid;    /// <summary>    /// 公眾號(hào)的appsecret    /// </summary>    private string secret;    /// <summary>    /// 回調(diào)url地址    /// </summary>    private string redirect_uri;    /// <summary>    /// 獲取微信用戶基本信息使用snsapi_userinfo模式    /// 如果使用靜默授權(quán),無法獲取用戶基本信息但可以獲取到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及相關(guān)數(shù)據(jù)    /// </summary>    public OAuthAccess_Token TokenData = null;    #endregion    #region 事件定義    /// <summary>    /// 當(dāng)處理出現(xiàn)異常時(shí),觸發(fā)    /// </summary>    public Action<Exception> OnError = null;    /// <summary>    /// 當(dāng)獲取AccessToken成功是觸發(fā)    /// </summary>    public Action<OAuthAccess_Token> OnGetTokenSuccess = null;    /// <summary>    /// 當(dāng)獲取用戶信息成功時(shí)觸發(fā)    /// </summary>    public Action<OAuthUser> OnGetUserInfoSuccess = null;    #endregion    #region 第二步,回調(diào)處理    /// <summary>    /// 第二步,通過code換取網(wǎng)頁授權(quán)access_token    /// </summary>    public void GetAccess_Token()    {      try      {        //1.處理跳轉(zhuǎn)        this.Code = ReqHelper.GetString("code");        if (string.IsNullOrEmpty(this.Code))          throw new Exception("獲取code參數(shù)失敗或用戶禁止授權(quán)獲取基本信息");        //1.發(fā)送獲取access_token請求        string url = GetAccess_TokenUrl();        string result = NetHelper.Get(url);        //2.解析相應(yīng)結(jié)果        TokenData = JsonConvert.DeserializeObject<OAuthAccess_Token>(result);        if (TokenData == null)          throw new Exception("反序列化結(jié)果失敗,返回內(nèi)容為:" + result);        //3.獲取成功        if (OnGetTokenSuccess != null)          OnGetTokenSuccess(TokenData);      }      catch (Exception ex)      {        Error("第二步,通過code換取網(wǎng)頁授權(quán)access_token異常", ex);      }    }    /// <summary>    /// 刷新當(dāng)前access_token    /// </summary>    public OAuthAccess_Token RefreshAccess_Token()    {      try      {        //1.發(fā)送請求        string url = GetReferesh_TokenUrl();        string result = NetHelper.Get(url);        //2.解析結(jié)果        OAuthAccess_Token token = JsonConvert.DeserializeObject<OAuthAccess_Token>(result);        if (token == null)          throw new Exception("反序列化結(jié)果失敗,返回內(nèi)容:" + result);        return token;      }      catch (Exception ex)      {        Error("刷新當(dāng)前access_token失敗", ex);        return null;      }    }    #endregion    #region 第三步,獲取用戶基本信息    /// <summary>    /// 第三步,獲取基本信息    /// </summary>    public void GetUserInfo()    {      try      {        //1.發(fā)送get請求        string url = GetUserInfoUrl();        string result = NetHelper.Get(url);        //2.解析結(jié)果        OAuthUser user = JsonConvert.DeserializeObject<OAuthUser>(result);        if (user == null)          throw new Exception("反序列化結(jié)果失敗,返回內(nèi)容:" + result);        //3.獲取成功        if (OnGetUserInfoSuccess != null)          OnGetUserInfoSuccess(user);      }      catch (Exception ex)      {        Error("第三步、獲取用戶基本信息異常", ex);      }    }    #endregion    #region 靜態(tài)方法    /// <summary>    /// 驗(yàn)證授權(quán)憑證是否有效    /// </summary>    /// <param name="access_token">access_token</param>    /// <param name="openid">用戶針對當(dāng)前公眾號(hào)的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>  /// 授權(quán)之后獲取用戶基本信息  /// </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>    /// 用戶特權(quán)信息,json 數(shù)組    /// </summary>    public JArray privilege { get; set; }    public string unionid { get; set; }  }  /// <summary>  /// 獲取Access_Token或者刷新返回的數(shù)據(jù)對象  /// </summary>  public class OAuthAccess_Token  {    public string access_token { get; set; }    public int expires_in { get; set; }    public string refresh_token { get; set; }    /// <summary>    /// 用戶針對當(dāng)前公眾號(hào)的唯一標(biāo)識(shí)    /// 關(guān)注后會(huì)產(chǎn)生,返回公眾號(hào)下頁面也會(huì)產(chǎn)生    /// </summary>    public string openid { get; set; }    public string scope { get; set; }    /// <summary>    /// 當(dāng)前用戶的unionid,只有在用戶將公眾號(hào)綁定到微信開放平臺(tái)帳號(hào)后    /// </summary>    public string unionid { get; set; }  }}

 

希望本文所述對大家C#程序設(shè)計(jì)有所幫助。


注:相關(guān)教程知識(shí)閱讀請移步到c#教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 克拉玛依市| 诸暨市| 南漳县| 珠海市| 陆川县| 枞阳县| 永宁县| 东辽县| 定西市| 师宗县| 台山市| 无为县| 霍林郭勒市| 都匀市| 砚山县| 黎城县| 沅陵县| 施甸县| 钟祥市| 松潘县| 施秉县| 漳州市| 湘西| 汶上县| 平利县| 海林市| 海丰县| 岑巩县| 株洲市| 大渡口区| 栾城县| 清原| 辽阳县| 布尔津县| 防城港市| 长子县| 台东市| 嘉兴市| 珠海市| 黑水县| 石狮市|