微信開放平臺之網站授權微信登錄功能
更新時間:2015年09月24日 11:22:29 作者:小 鵬
本文通過.net實現(xiàn)的微信開放平臺之網站授權微信登錄功能,需要的小伙伴一起看看吧
1 微信開放平臺:https://open.weixin.qq.com/

3.pc頁面顯示
4. 通過官方提供的文檔,我們可以看出一共分4個步驟
第一步:請求CODE
第二步:通過code獲取access_token
第三步:通過access_token調用接口
第4步:獲取用戶個人信息(UnionID機制)
api:核心代碼
public class weixin_helper
{
public weixin_helper()
{
}
/// <summary>
/// 根據AppID和AppSecret獲得access token(默認過期時間為2小時)
/// </summary>
/// <returns>Dictionary</returns>
public static Dictionary<string, object> get_access_token()
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2);
string send_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +
config.oauth_app_id + "&secret=" + config.oauth_app_key + "";
//發(fā)送并接受返回值
string result = Utils.HttpGet(send_url);
if (result.Contains("errmsg"))
{
return null;
}
try
{
Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
return dic;
}
catch
{
return null;
}
} /// <summary>
/// 取得臨時的Access Token(默認過期時間為2小時)
/// </summary>
/// <param name="code">臨時Authorization Code</param>
/// <param name="state">防止CSRF攻擊,成功授權后回調時會原樣帶回</param>
/// <returns>Dictionary</returns>
public static Dictionary<string, object> get_access_token(string code, string state)
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2);
string send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
config.oauth_app_id + "&secret=" + config.oauth_app_key + "&code="+code+"&grant_type=authorization_code";
//發(fā)送并接受返回值
string result = Utils.HttpGet(send_url);
if (result.Contains("errmsg"))
{
return null;
}
try
{
Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
return dic;
}
catch
{
return null;
}
}
/// <summary>
/// 根據access_token判斷access_token是否過期
/// </summary>
/// <param name="access_token"></param>
/// <returns>true表示未失效</returns>
public static bool check_access_token(string access_token)
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2);
string send_url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + config.oauth_app_id;
//發(fā)送并接受返回值
string result = Utils.HttpGet(send_url);
try
{
Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
if (dic.ContainsKey("errmsg"))
{
if (dic["errmsg"].ToString()=="ok")
{
return true;
}
else
{
return false;
}
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 若fresh_token已過期則根據refresh_token取得新的refresh_token
/// </summary>
/// <param name="refresh_token">refresh_token</param>
/// <returns>Dictionary</returns>
public static Dictionary<string, object> get_refresh_token(string refresh_token)
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2);
string send_url =
"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" +
config.oauth_app_id + "&grant_type=refresh_token&refresh_token=" + refresh_token;
//發(fā)送并接受返回值
string result = Utils.HttpGet(send_url);
if (result.Contains("errmsg"))
{
return null;
}
try
{
Dictionary<string, object> dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
return dic;
}
catch
{
return null;
}
}
/// <summary>
/// 獲取登錄用戶自己的基本資料
/// </summary>
/// <param name="access_token">臨時的Access Token</param>
/// <param name="open_id">用戶openid</param>
/// <returns>Dictionary</returns>
public static Dictionary<string, object> get_user_info(string access_token, string open_id)
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2);
//發(fā)送并接受返回值
string send_url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+open_id;
//發(fā)送并接受返回值
string result = Utils.HttpGet(send_url);
if (result.Contains("errmsg"))
{
return null;
}
//反序列化JSON
Dictionary<string, object> dic = JsonHelper.DataRowFromJSON(result);
return dic;
}
}
控制器的核心代碼:
#region 微信登錄
/// <summary>
/// 微信登錄
/// </summary>
public ActionResult WeChat()
{
//獲得配置信息
oauth_config config = oauth_helper.get_config(2); //主鍵id
if (config == null)
{
return Content("出錯了,您尚未配置微信相關的API信息!");
}
string state = Guid.NewGuid().ToString().Replace("-", "");
Session["oauth_state"] = state;
string send_url =
"https://open.weixin.qq.com/connect/qrconnect?appid=" + config.oauth_app_id +
"&redirect_uri=" + Utils.UrlEncode(config.return_uri.ToLower()) +
"&response_type=code&scope=snsapi_login&state=" + state +
"#wechat_redirect";
//開始發(fā)送
return Redirect(send_url); //跳轉到微信自己 指定的關聯(lián)登陸頁面
}
/// <summary>
/// 微信登錄返回action
/// </summary>
public ActionResult WeChatReturnUrl(string state, string code)
{
//取得返回參數
string access_token = string.Empty;
string expires_in = string.Empty;
string client_id = string.Empty;
string openid = string.Empty;
string refresh_token = string.Empty;
if (Session["oauth_state"] == null || Session["oauth_state"].ToString() == "" ||
state != Session["oauth_state"].ToString() || string.IsNullOrEmpty(code))//若返回參數中未包含code或者state沒有通過驗證則提示出錯
{
return Content("出錯啦,state未初始化!");
}
//第一步:通過code來獲取Access Token以及openid
Dictionary<string, object> dic1 = weixin_helper.get_access_token(code, state);
if (dic1 == null || !dic1.ContainsKey("access_token"))
{
return Content("錯誤代碼:,無法獲取Access Token,請檢查App Key是否正確!");
}
if (dic1 == null || !dic1.ContainsKey("openid"))
{
if (dic1.ContainsKey("errmsg"))
{
return Content("errcode:" + dic1["errcode"] + ",errmsg:" + dic1["errmsg"]);
}
else
{
return Content("出錯啦,無法獲取用戶授權Openid!");
}
}
access_token = dic1["access_token"].ToString();//獲取access_token
expires_in = dic1["expires_in"].ToString();//獲取過期時間
refresh_token = dic1["refresh_token"].ToString();//獲取用于重新刷新access_token的憑證
openid = dic1["openid"].ToString();//用戶唯一標示openid
//儲存獲取數據用到的信息
Session["oauth_name"] = "webchat";
Session["oauth_access_token"] = access_token;
Session["oauth_openid"] = openid;
Session["oauth_refresh_token"] = refresh_token;
#region todo 將獲取到的用戶信息保存到數據庫中
#endregion
//第二步:通過Access Token以及openid來獲取用戶的基本信息
//Dictionary<string, object> dic2 = weixin_helper.get_user_info(access_token,openid);
//第三步:跳轉到指定頁面
return Content(WeChatResultJson());
}
/// <summary>
/// 微信登錄返回action, 處理用戶信息
/// </summary>
public string WeChatResultJson()
{
string oauth_access_token = string.Empty;
string oauth_openid = string.Empty;
string oauth_name = string.Empty;
string oauth_refresh_token = string.Empty;
if (Session["oauth_name"] == null || Session["oauth_access_token"] == null ||
Session["oauth_openid"] == null)
{
return "{\"ret\":\"1\", \"msg\":\"出錯啦,Access Token已過期或不存在!\"}";
}
oauth_name = Session["oauth_name"].ToString();
oauth_access_token = Session["oauth_access_token"].ToString();
oauth_openid = Session["oauth_openid"].ToString();
oauth_refresh_token = Session["oauth_refresh_token"].ToString();
if (!weixin_helper.check_access_token(oauth_access_token)) //調用access_token前需判斷是否過期
{
Dictionary<string, object> dic1 = weixin_helper.get_refresh_token(oauth_refresh_token);//如果已過期則重新?lián)Q取新的access_token
if (dic1 == null || !dic1.ContainsKey("access_token"))
{
return "{\"openid\":\"0\", \"msg\":\"出錯啦,無法獲取access_token!\"}";
}
oauth_access_token = dic1["access_token"].ToString();
}
Dictionary<string, object> dic = weixin_helper.get_user_info(oauth_access_token, oauth_openid);
if (dic == null)
{
return "{\"openid\":\"0\", \"msg\":\"出錯啦,無法獲取授權用戶信息!\"}";
}
try
{
StringBuilder str = new StringBuilder();
str.Append("{");
str.Append("\"openid\": \"" + dic["openid"].ToString() + "\", ");
str.Append("\"nickname\": \"" + dic["nickname"].ToString() + "\", ");
str.Append("\"sex\": \"" + dic["sex"].ToString() + "\", ");
str.Append("\"province\": \"" + dic["province"].ToString() + "\", ");
str.Append("\"city\": \"" + dic["city"].ToString() + "\", ");
str.Append("\"country\": \"" + dic["country"].ToString() + "\", ");
str.Append("\"headimgurl\": \"" + dic["headimgurl"].ToString() + "\", ");
str.Append("\"privilege\": \"" + dic["privilege"].ToString() + "\", ");
str.Append("\"unionid\": \"" + dic["unionid"].ToString() + "\"");
str.Append("\"oauth_name\": \"" + oauth_name + "\"");
str.Append("\"oauth_access_token\": \"" + oauth_access_token + "\"");
str.Append("\"oauth_openid\": \"" + oauth_openid + "\"");
str.Append("}");
return str.ToString();
}
catch
{
return "{\"ret\":\"0\", \"msg\":\"出錯啦,無法獲取授權用戶信息!\"}";
}
}
#endregion
您可能感興趣的文章:
相關文章
WPF實現(xiàn)繪制統(tǒng)計圖(柱狀圖)的方法詳解
這篇文章主要為大家詳細介紹了如何基于WPF實現(xiàn)實現(xiàn)統(tǒng)計圖(柱狀圖)的繪制,文中的示例代碼簡潔易懂,對我們學習WPF有一定幫助,感興趣的可以了解一下2022-07-07
C#事務處理(Execute Transaction)實例解析
這篇文章主要介紹了C#事務處理(Execute Transaction)實例解析,對于理解和學習事務處理有一定的幫助,需要的朋友可以參考下2014-08-08
C# Newtonsoft.Json 解析多嵌套json 進行反序列化的實例
這篇文章主要介紹了C# Newtonsoft.Json 解析多嵌套json 進行反序列化的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

