微信是个坑货4-网页授权
生活随笔
收集整理的這篇文章主要介紹了
微信是个坑货4-网页授权
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
功能:認證服務號通過網頁授權獲取用戶信息
?
--公眾號后臺配置
》此次設置的是網頁授權域名,設置成你調試的域名或者正式備案的域名(不帶http或https)。
?
--自定義菜單設置
設置參數:
appid:微信公眾號的appid
uri:微信網頁授權后跳轉的網頁(該uri需經過UrlEncode編碼)
scope:此處使用 snsapi_userinfo方式
關于網頁授權的兩種scope的區別說明
1、以snsapi_base為scope發起的網頁授權,是用來獲取進入頁面的用戶的openid的,并且是靜默授權并自動跳轉到回調頁的。用戶感知的就是直接進入了回調頁(往往是業務頁面)
2、以snsapi_userinfo為scope發起的網頁授權,是用來獲取用戶的基本信息的。但這種授權需要用戶手動同意,并且由于用戶同意過,所以無須關注,就可在授權后獲取該用戶的基本信息。
?
--授權步驟
1 第一步:用戶同意授權,獲取code
2 第二步:通過code換取網頁授權access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用戶信息(需scope為 snsapi_userinfo)
--后臺代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Xml;namespace wxweb.Areas.wechatPage.Controllers {public class service_PersonalController : Controller{// GET: wechatPage/service_Personalpublic ActionResult Index(){//--------------微信oauth授權---------------wxPlatForm.OAuth.wechatOAuth oauth = new wxPlatForm.OAuth.wechatOAuth();oauth.appid = appid;//微信公眾號的appidoauth.secret = secret;//微信公眾號的AppSecretoauth.get_code();//獲取token及userinfo信息if (oauth.o_user != null){//獲取用戶信息成功,繼續邏輯業務操作 }else{return RedirectToAction("Error", "service_Personal");}//--------------end微信oauth授權---------------return View();}} }網頁授權接入頁面
?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Script.Serialization;namespace wxPlatForm.OAuth {public class wechatOAuth{/// <summary> /// 公眾號的唯一標識 /// </summary> public string appid;/// <summary> /// 公眾號的appsecret /// </summary> public string secret;public OAuthAccess_Token o_token;public OAuthUser o_user;private string code;/// <summary>/// 獲取code/// </summary>public void get_code() {try{code = HttpContext.Current.Request.QueryString["Code"];if (code != ""&&code!=null) {get_access_token();}}catch (Exception ex){common.CommonMethod.WriteTxt(ex.Message);}}/// <summary>/// 通過code換取網頁授權access_token/// </summary>public void get_access_token() {Dictionary<string, string> obj = new Dictionary<string, string>();var client = new System.Net.WebClient();var serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);//獲取字典obj = serializer.Deserialize<Dictionary<string, string>>(dataaccess);string accessToken = "";if (obj.TryGetValue("access_token", out accessToken)) //判斷access_Token是否存在 {o_token =new OAuthAccess_Token {access_token=obj["access_token"],expires_in =Convert.ToInt32( obj["expires_in"]),refresh_token = obj["refresh_token"],openid = obj["openid"],scope = obj["scope"]};if (o_token.scope == "snsapi_userinfo") {get_userinfo(o_token.access_token, o_token.openid);}}else //access_Token 失效時重新發送。 {//存log方法common.CommonMethod.WriteTxt("access_token 獲取失敗,time:"+DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法 common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 拉取用戶信息(需scope為 snsapi_userinfo)/// </summary>/// <param name="access_token">網頁授權接口調用憑證,注意:此access_token與基礎支持的access_token不同</param>/// <param name="access_token"> 用戶的唯一標識</param>public void get_userinfo(string access_token,string openid) {Dictionary<string, object> obj = new Dictionary<string, object>();var client = new System.Net.WebClient();JavaScriptSerializer serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);obj = serializer.Deserialize<Dictionary<string, object>>(dataaccess);object user_openid = "";if (obj.TryGetValue("openid", out user_openid)) //判斷access_Token是否存在 {o_user = new OAuthUser{openid = obj["openid"].ToString(),nickname = obj["nickname"].ToString(),sex =Convert.ToInt32( obj["sex"]),province = obj["province"].ToString(),city = obj["city"].ToString(),country = obj["country"].ToString(),headimgurl = obj["headimgurl"].ToString(),privilege =obj["privilege"].ToString(),unionid =""};}else //access_Token 失效時重新發送。 {//存log方法common.CommonMethod.WriteTxt("用戶信息 獲取失敗,time:" + DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法 common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 檢驗授權憑證(access_token)是否有效/// </summary>/// <param name="appid">公眾號的唯一標識</param> /// <param name="refresh_token">填寫通過access_token獲取到的refresh_token參數</param>public void refresh_access_token(string refresh_token) {Dictionary<string, string> obj = new Dictionary<string, string>();var client = new System.Net.WebClient();var serializer = new JavaScriptSerializer();string url = string.Format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}", this.appid, refresh_token);client.Encoding = System.Text.Encoding.UTF8;string dataaccess = "";try{dataaccess = client.DownloadString(url);//獲取字典obj = serializer.Deserialize<Dictionary<string, string>>(dataaccess);string accessToken = "";if (obj.TryGetValue("access_token", out accessToken)) //判斷access_Token是否存在 {OAuthAccess_Token o_token = new OAuthAccess_Token{access_token = obj["access_token"],expires_in = Convert.ToInt32(obj["expires_in"]),refresh_token = obj["refresh_token"],openid = obj["openid"],scope = obj["scope"]};if (o_token.scope == "snsapi_userinfo"){get_userinfo(o_token.access_token, o_token.openid);}}else //access_Token 失效時重新發送。 {//存log方法common.CommonMethod.WriteTxt("access_token 獲取失敗,time:" + DateTime.Now.ToLongTimeString());}}catch (Exception e){//存log方法 common.CommonMethod.WriteTxt(e.Message);}}/// <summary>/// 刷新access_token(如果需要)/// </summary>public void check_access_token(){}} }網頁授權接入-調用wechatOAuth
?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace wxPlatForm.OAuth {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; }} }網頁授權接入-調用OAuthAccess_Token
?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace wxPlatForm.OAuth {/// <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 privilege { get; set; }public string unionid { get; set; }} }網頁授權接入-調用OAuthUser
?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Web; using System.Web.Script.Serialization;namespace common {/// <summary>/// 通用方法類/// </summary>public class CommonMethod{#region 記錄bug,以便調試/// <summary>/// 記錄bug,以便調試/// </summary>public static bool WriteTxt(string str){try{string LogPath = HttpContext.Current.Server.MapPath("/err_log/");if (!Directory.Exists(LogPath)){Directory.CreateDirectory(LogPath);}FileStream FileStream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("/err_log//xiejun_" + DateTime.Now.ToLongDateString() + "_.txt"), FileMode.Append);StreamWriter StreamWriter = new StreamWriter(FileStream);//開始寫入 StreamWriter.WriteLine(str);//清空緩沖區 StreamWriter.Flush();//關閉流 StreamWriter.Close();FileStream.Close();}catch (Exception){return false;}return true;}#endregion} }寫日志
?
轉載于:https://www.cnblogs.com/eye-like/p/9276529.html
總結
以上是生活随笔為你收集整理的微信是个坑货4-网页授权的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 普通焊帽多少钱
- 下一篇: Kubernetes入门