您好,登錄后才能下訂單哦!
本篇內容主要講解“如何實現Asp.Net Core 企業微信靜默授權”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何實現Asp.Net Core 企業微信靜默授權”吧!
企業微信接口文檔
1. 構造授權網頁鏈接
2.回調獲取到 Code 通過code+access_token去 請求用戶信息
3. 獲取access_token
調試準備工作 -->內網穿透+域名 推薦向日葵有免費的,免費的開發測試夠用了
域名的配置成可信用
上代碼 Demo下載
[ApiController] [Route("api/[controller]")] public class Auth3Controller : ControllerBase { private readonly string _agentId = "1000002"; private readonly string _secret = "Y3f8ESBIBJoC8M_FPHOlpvmghS_Nn2ceFePRVZjw9_E"; private readonly string _corpId = "wwbf72a7a059eac0f8"; /// <summary> /// 授權地址 /// </summary> private readonly string _auth3url = "https://open.weixin.qq.com/connect/oauth3/authorize"; /// <summary> /// 授權回調地址 /// </summary> private readonly string _callbackurl = "http://******.zicp.vip/auth3callback/api/Auth3/Callback"; /// <summary> /// 獲取access_token地址 /// </summary> private readonly string _gettokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; /// <summary> /// 獲取訪問用戶身份地址 /// </summary> private readonly string _getuserurl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo"; private readonly ILogger<Auth3Controller> _logger; private readonly IHttpClientFactory _clientFactory; private readonly IMemoryCache _memoryCache; public Auth3Controller(ILogger<Auth3Controller> logger, IHttpClientFactory clientFactory, IMemoryCache memoryCache) { _logger = logger; _clientFactory = clientFactory; _memoryCache = memoryCache; } [HttpGet] public IActionResult Auth3(string redirecturi) { string strurl = $"{_auth3url}?" + $"&appid={_corpId}" + $"&redirect_uri={System.Web.HttpUtility.UrlEncode(_callbackurl)}" + $"&response_type=code" + $"&scope={_secret}" + $"&agentid={_agentId}" + $"&state={System.Web.HttpUtility.UrlEncode(redirecturi)}#wechat_redirect"; return Redirect(strurl); } [HttpGet("Callback")] public async Task<IActionResult> Callback(string code, string state) { /** 1)code只能消費一次,不能重復消費。比如說,是否存在多個服務器同時消費同一code情況。 2)code需要在有效期間消費(5分鐘),過期會自動失效。 */ string access_token = await GetAccessToken(); string url = $"{_getuserurl}?access_token={access_token}&code=[code]"; HttpResponseMessage response = await _clientFactory.CreateClient().GetAsync(url); if (response.StatusCode == System.Net.HttpStatusCode.OK) { using (var responseStream = await response.Content.ReadAsStreamAsync()) { var userinfo = JsonConvert.DeserializeObject<dynamic>(new StreamReader(responseStream).ReadToEnd()); int errcode = userinfo.errcode; if (errcode == 0) { //企業成員 string UserId = userinfo.UserId; //外部成員 string OpenId = userinfo.OpenId; /** userid是系統生成的可以修改一次; 所以后面的業務邏輯如果遇到錯誤就要重新授權一下; */ if (UserId==null) { _memoryCache.Set<string>("UserId", OpenId); } else { _memoryCache.Set<string>("UserId", UserId); } } else { _logger.LogError($"getuserinfo請求錯誤:{userinfo.errmsg}"); return Ok(); } } } return Redirect($"{System.Web.HttpUtility.UrlDecode(state)}?UserId={_memoryCache.Get<string>("UserId")}"); } public async Task<string> GetAccessToken() { if (_memoryCache.Get<string>("AccessToken") == null) { string url = $"{_gettokenurl}?corpid={_corpId}&corpsecret={_secret}"; HttpResponseMessage response = await _clientFactory.CreateClient().GetAsync(url); if (response.StatusCode == System.Net.HttpStatusCode.OK) { using (var responseStream = await response.Content.ReadAsStreamAsync()) { var access_token_result = JsonConvert.DeserializeObject<dynamic>(new StreamReader(responseStream).ReadToEnd()); int errcode = access_token_result.errcode; if (errcode == 0) { string access_token = access_token_result.access_token; int expires_in = access_token_result.expires_in; _memoryCache.Set<string>("AccessToken", access_token, DateTimeOffset.Now.AddSeconds(expires_in - 10)); } else { _logger.LogError($"access_token請求錯誤:{access_token_result.errmsg }"); } } } } return _memoryCache.Get<string>("AccessToken"); } }
到此,相信大家對“如何實現Asp.Net Core 企業微信靜默授權”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。