C#實(shí)現(xiàn)的微信網(wǎng)頁(yè)授權(quán)操作邏輯封裝示例
本文實(shí)例講述了C#實(shí)現(xiàn)的微信網(wǎng)頁(yè)授權(quán)操作邏輯封裝。分享給大家供大家參考,具體如下:
一、微信網(wǎng)頁(yè)授權(quán)登錄
前提:
1.已經(jīng)獲取的接口權(quán)限,如果是測(cè)試賬號(hào)就已經(jīng)有權(quán)限了
2.配置接口的授權(quán)域名
更多說(shuō)明可以參考方倍工作室:http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html
或者官網(wǎng)API:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
步驟:
1.用戶(hù)同意授權(quán),獲取code
2.根據(jù)code 獲取access_token及當(dāng)前操作用戶(hù)的openid、unionid
3.根據(jù)openid獲取用戶(hù)基本信息(如果需要的話(huà))
注:如果想在網(wǎng)站使用掃一掃,授權(quán)登錄,可以講 _oauth.GetCodeUrl() 授權(quán)地址生成二維碼來(lái)使用
C#封裝微信網(wǎng)頁(yè)授權(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 = "";
//注冊(cè)事件處理
_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();
}
封裝代碼類(lèi)定義:
namespace WXPackage
{
/// <summary>
/// 網(wǎng)頁(yè)授權(quán)邏輯處理,
/// 處理三步操作,處理成功,返回用戶(hù)基本信息
/// </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>
/// 獲取微信用戶(hù)基本信息使用snsapi_userinfo模式
/// 如果使用靜默授權(quán),無(wú)法獲取用戶(hù)基本信息但可以獲取到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 請(qǐng)求過(guò)程信息
/// <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)獲取用戶(hù)信息成功時(shí)觸發(fā)
/// </summary>
public Action<OAuthUser> OnGetUserInfoSuccess = null;
#endregion
#region 第二步,回調(diào)處理
/// <summary>
/// 第二步,通過(guò)code換取網(wǎng)頁(yè)授權(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ù)失敗或用戶(hù)禁止授權(quán)獲取基本信息");
//1.發(fā)送獲取access_token請(qǐng)求
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("第二步,通過(guò)code換取網(wǎng)頁(yè)授權(quán)access_token異常", ex);
}
}
/// <summary>
/// 刷新當(dāng)前access_token
/// </summary>
public OAuthAccess_Token RefreshAccess_Token()
{
try
{
//1.發(fā)送請(qǐng)求
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 第三步,獲取用戶(hù)基本信息
/// <summary>
/// 第三步,獲取基本信息
/// </summary>
public void GetUserInfo()
{
try
{
//1.發(fā)送get請(qǐng)求
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("第三步、獲取用戶(hù)基本信息異常", ex);
}
}
#endregion
#region 靜態(tài)方法
/// <summary>
/// 驗(yàn)證授權(quán)憑證是否有效
/// </summary>
/// <param name="access_token">access_token</param>
/// <param name="openid">用戶(hù)針對(duì)當(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 獲取請(qǐng)求連接
/// <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>
/// 獲取用戶(hù)基本信息地址
/// </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)之后獲取用戶(hù)基本信息
/// </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>
/// 用戶(hù)特權(quán)信息,json 數(shù)組
/// </summary>
public JArray privilege { get; set; }
public string unionid { get; set; }
}
/// <summary>
/// 獲取Access_Token或者刷新返回的數(shù)據(jù)對(duì)象
/// </summary>
public class OAuthAccess_Token
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string refresh_token { get; set; }
/// <summary>
/// 用戶(hù)針對(duì)當(dāng)前公眾號(hào)的唯一標(biāo)識(shí)
/// 關(guān)注后會(huì)產(chǎn)生,返回公眾號(hào)下頁(yè)面也會(huì)產(chǎn)生
/// </summary>
public string openid { get; set; }
public string scope { get; set; }
/// <summary>
/// 當(dāng)前用戶(hù)的unionid,只有在用戶(hù)將公眾號(hào)綁定到微信開(kāi)放平臺(tái)帳號(hào)后
/// </summary>
public string unionid { get; set; }
}
}
更多關(guān)于C#相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《C#常見(jiàn)控件用法教程》、《WinForm控件用法總結(jié)》、《C#數(shù)據(jù)結(jié)構(gòu)與算法教程》、《C#面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》及《C#程序設(shè)計(jì)之線(xiàn)程使用技巧總結(jié)》
希望本文所述對(duì)大家C#程序設(shè)計(jì)有所幫助。
欄 目:C#教程
本文標(biāo)題:C#實(shí)現(xiàn)的微信網(wǎng)頁(yè)授權(quán)操作邏輯封裝示例
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6220.html
您可能感興趣的文章
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并打開(kāi)的方法
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10C#停止線(xiàn)程的方法
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新聞效果的方法
- 01-10C#通過(guò)重寫(xiě)Panel改變邊框顏色與寬度的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已安裝軟件變化的方法


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹(shù)的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過(guò)反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁(yè)無(wú)法打開(kāi)的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動(dòng)新
- 01-10C#停止線(xiàn)程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過(guò)重寫(xiě)Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10C#中split用法實(shí)例總結(jié)
- 01-11Mac OSX 打開(kāi)原生自帶讀寫(xiě)NTFS功能(圖文
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 04-02jquery與jsp,用jquery
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開(kāi)發(fā)環(huán)境設(shè)置
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?


