using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Hosting;using Microsoft.AspNetCore.Http;
using System.Net.Http;
using Newtonsoft.Json;
namespace YiSha.Util
{
public class GlobalContext
{public static IHttpClientFactory HttpClientFactory { get; set; }
public static IConfiguration Configuration { get; set; }public static string Token { get; set; }
public static DateTime TimeOutDate { get; set; }
/// <summary>
/// 获取Token
/// </summary>
/// <returns>Item1 Token;Item2 是否成功</returns>
public static Result GetToken()
{
//判断Token是否存在 以及Token是否在有效期内
if (string.IsNullOrEmpty(Token) || TimeOutDate > DateTime.Now)
{
//构造请求链接
var requestBuild=Configuration[“Wx:getToken”];
requestBuild=string.Format(requestBuild,
Configuration[“Wx:appid”],
Configuration[“Wx:secret”]
);
using (var wxClient=HttpClientFactory.CreateClient(“WxClient”))
{
var httpResponse=wxClient.GetAsync(requestBuild).Result;
var dynamic=JsonConvert.DeserializeObject<dynamic>(
httpResponse.Content.ReadAsStringAsync().Result
);
if (dynamic.errmsg==null)//刷新Token
{
Token=dynamic.access_token;
var expires_in=Convert.ToDouble(dynamic.expires_in);
TimeOutDate=DateTime.Now.AddSeconds(expires_in);
return new Result(Token);
}
else
{
return new Result(errMsg:dynamic.errmsg);
}
}
}
else
{
return new Result(Token);
}
}
public static Result GetUserPhoneNumber(string code)
{
var token=GetToken();
if(!token.isSuccess)
{
return token;
}
//构造请求链接
var requestBuild=Configuration[“Wx:getuserphonenumber”];
requestBuild=string.Format(requestBuild, token.data);
//建立HttpClient
using (var wxClient=HttpClientFactory.CreateClient(“WxClient”))
{
string content=$”{{“code”:”[code]”}}”;
byte[] data=Encoding.UTF8.GetBytes(content);
var bytearray=new ByteArrayContent(data);
var httpResponse=wxClient.PostAsync(requestBuild, bytearray).Result;
var dynamic=JsonConvert.DeserializeObject<dynamic>(
httpResponse.Content.ReadAsStringAsync().Result
);
if (dynamic.errmsg==”ok”)
return new Result(dynamic.phone_info.phoneNumber.ToString());
else
return new Result(errMsg: dynamic.errmsg.ToString());
}
}
/// <summary>
/// 返回消息
/// </summary>
public class Result
{
public Result()
{
}
/// <summary>
/// 正确
/// </summary>
/// <param name=”data”></param>
public Result(string data)
{
this.data=data;
this.isSuccess=true;
}
/// <summary>
/// 错误
/// </summary>
/// <param name=”errMsg”></param>
/// <param name=”isSuccess”></param>
public Result(string errMsg,bool isSuccess=false)
{
this.errMsg=errMsg;
this.isSuccess=isSuccess;
}
public string data { get; set; }
public string errMsg { get; set; }
public bool isSuccess { get; set; }
}
}
}