资讯详情

C#获取企业微信 access_token

一、新建配置文件(名称:appsettings.json)

{   "PLMConnectionString": "Server=数据库IP;database=;uid=数据库名称;pwd=数据库密码", ///数据库配置   "CORPID": "", //企业Id   "SECRET": "" //使用的凭证密钥 } 

二、放置配置文件 …/bin/Debug目录下。 将配置文件引入项目。 四、代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Net.Http; using System.Data.SqlClient; using System.Data; using Microsoft.Extensions.Configuration; using System.IO; using System.Collections;  namespace Send_Message { 
          class Program  { 
          ///存储权限管理组的凭证密钥   string _AccessToken;    static void Main(string[] args)   { 
           //引入配置文件    var build = new ConfigurationBuilder();    build.AddJsonFile(AppDomain.CurrentDomain.BaseDirectory   "/appsettings.json", true, true);    build.SetBasePath(Dirctory.GetCurrentDirectory());
			var Config = build.Build();
			string PLMConnectionString = Config.GetSection("PLMConnectionString").Value;
			string CORPID = Config.GetSection("CORPID").Value;
			string SECRET = Config.GetSection("SECRET").Value;

			Program p = new Program();
			p.GetToken(CORPID, SECRET);
		}

		//获取企业微信 access_token 企业微信官方文档 https://developer.work.weixin.qq.com/document/path/91039
		public string GetToken(string CORPID, string SECRET)
		{ 
       
			try
			{ 
       
				//API:"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=企业Id&corpsecret=权限管理组的凭证密钥"
				HttpClient httpClient = new HttpClient();
				//httpClient.MaxResponseContentBufferSize = 256000;
				string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", CORPID, SECRET);
				HttpResponseMessage response = httpClient.GetAsync(new Uri(url)).Result;
				string result = response.Content.ReadAsStringAsync().Result;
				var rsEntity = new { 
        access_token = "", expires_in = 0, errcode = 0, errmsg = "" };
				dynamic en = JsonConvert.DeserializeAnonymousType<object>(result, rsEntity); // Newtonsoft.Json提供的匿名类反序列化
				_AccessToken = en.access_token;
				return _AccessToken;
			}
			catch (Exception ex)
			{ 
       
				throw ex;
			}
		}
	}

}

标签: 37zkh矩形电连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台