无为清净楼资源网 Design By www.qnjia.com

企业微信接口文档

1. 构造授权网页链接

Asp.Net Core 企业微信静默授权的实现

2.回调获取到 Code 通过code+access_token去 请求用户信息

Asp.Net Core 企业微信静默授权的实现

3. 获取access_token

Asp.Net Core 企业微信静默授权的实现

调试准备工作 -->内网穿透+域名 推荐向日葵有免费的,免费的开发测试够用了

域名的配置成可信用

Asp.Net Core 企业微信静默授权的实现

上代码 Demo下载

[ApiController]
  [Route("api/[controller]")]
  public class Auth2Controller : ControllerBase
  {

    private readonly string _agentId = "1000002";
    private readonly string _secret = "Y3f8ESBIBJoC8M_FPHOlpvmghS_Nn2ceFePRVZjw9_E";
    private readonly string _corpId = "wwbf72a7a059eac0f8";
    /// <summary>
    /// 授权地址
    /// </summary>
    private readonly string _auth2url = "https://open.weixin.qq.com/connect/oauth2/authorize";
    /// <summary>
    /// 授权回调地址
    /// </summary>
    private readonly string _callbackurl = "http://******.zicp.vip/auth2callback/api/Auth2/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<Auth2Controller> _logger;
    private readonly IHttpClientFactory _clientFactory;
    private readonly IMemoryCache _memoryCache;

    public Auth2Controller(ILogger<Auth2Controller> logger, IHttpClientFactory clientFactory, IMemoryCache memoryCache)
    {
      _logger = logger;
      _clientFactory = clientFactory;
      _memoryCache = memoryCache;
    }   

    [HttpGet]
    public IActionResult Auth2(string redirecturi)
    {
      string strurl = $"{_auth2url}" +
          $"&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}";
      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")}");
    }
    public async Task<string> GetAccessToken()
    {
      if (_memoryCache.Get<string>("AccessToken") == null)
      {
        string url = $"{_gettokenurl}";
        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,静默授权

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。