提交
This commit is contained in:
468
api_v1/Appointment.Entity/Utility/AizhuhotelHelper.cs
Normal file
468
api_v1/Appointment.Entity/Utility/AizhuhotelHelper.cs
Normal file
@@ -0,0 +1,468 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public class AizhuhotelHelper
|
||||
{
|
||||
private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(AizhuhotelHelper));
|
||||
|
||||
// ---- 获取公众号 Access_token
|
||||
private class LoveInnGetAccessTokenRes
|
||||
{
|
||||
/// <summary>
|
||||
/// 200-成功,400-出错,
|
||||
/// </summary>
|
||||
public int Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回信息:正确、错误都提示
|
||||
/// </summary>
|
||||
public string Message { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 信息
|
||||
/// </summary>
|
||||
public GetAccessTokenRes Data { get; set; }
|
||||
}
|
||||
|
||||
private class GetAccessTokenRes
|
||||
{
|
||||
public string Access_token { get; set; }
|
||||
|
||||
public int? Expires_in { get; set; }
|
||||
|
||||
public string Errcode { get; set; }
|
||||
|
||||
public string Errmsg { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过爱住接口获取Accesstoken
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static ApiResult<string> AizhuhotelGetAccesstoken()
|
||||
{
|
||||
var url = "https://pay.aizhuhotel.com/dlwx/api/WD/LoveInnGetAccessToken";
|
||||
|
||||
string AppId = BaseConfig.App(new string[] { "WeChatService", "AppId" });
|
||||
if (string.IsNullOrWhiteSpace(AppId)) return ApiResult<string>.Failed("配置文件中未获取有效的消息推送AppId");
|
||||
string AppName = BaseConfig.App(new string[] { "WeChatService", "AppName" });
|
||||
if (string.IsNullOrWhiteSpace(AppName)) return ApiResult<string>.Failed("配置文件中未获取有效的消息推送AppName");
|
||||
string AppSecret = BaseConfig.App(new string[] { "WeChatService", "AppSecret" });
|
||||
if (string.IsNullOrWhiteSpace(AppSecret)) return ApiResult<string>.Failed("配置文件中未获取有效的消息推送AppSecret");
|
||||
|
||||
var json = JsonConvert.SerializeObject(new { AppId, AppName, AppSecret });
|
||||
|
||||
try
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Proxy = null;
|
||||
request.Method = "POST";
|
||||
request.ContentType = "application/json";
|
||||
// request.Timeout = 10000;
|
||||
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
|
||||
{
|
||||
dataStream.Write(json);
|
||||
dataStream.Close();
|
||||
}
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
if (response == null)
|
||||
{
|
||||
return ApiResult<string>.Failed("远程服务器没有响应!");
|
||||
}
|
||||
string encoding = response.ContentEncoding;
|
||||
if (encoding == null || encoding.Length < 1)
|
||||
{
|
||||
encoding = "UTF-8"; //默认编码
|
||||
}
|
||||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
|
||||
string retString = reader.ReadToEnd();
|
||||
|
||||
var res = JsonConvert.DeserializeObject<LoveInnGetAccessTokenRes>(retString);
|
||||
if (res.Code != 200) return ApiResult<string>.Failed(res.Message);
|
||||
if (res.Data == null) return ApiResult<string>.Failed("未获取到有效信息");
|
||||
return ApiResult<string>.Success(string.Empty, res.Data.Access_token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Debug(ex.ToString());
|
||||
return ApiResult<string>.Failed("http请求异常,异常信息:" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ---- 通过微信服务器获取access_token
|
||||
|
||||
private static WxAccessTokenData accessCacheToken = null;
|
||||
|
||||
public class WxAccessTokenData
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取到的access_token
|
||||
/// </summary>
|
||||
public string Access_token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 获取时间
|
||||
/// </summary>
|
||||
public DateTime GetDate { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 微信授权返回结果
|
||||
/// </summary>
|
||||
public class WxAuthorizationCodeRep
|
||||
{
|
||||
/// <summary>
|
||||
/// 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
|
||||
/// </summary>
|
||||
public string Access_token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// access_token接口调用凭证超时时间,单位(秒)
|
||||
/// 错误时不返回
|
||||
/// </summary>
|
||||
public int? Expires_in { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户刷新access_token
|
||||
/// </summary>
|
||||
public string Refresh_token { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户唯一标识
|
||||
/// </summary>
|
||||
public string Openid { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 用户授权的作用域,使用逗号(,)分隔
|
||||
/// </summary>
|
||||
public string Scope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 错误码:返回码
|
||||
/// 正确时不返回
|
||||
/// </summary>
|
||||
public int? Errcode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 错误信息
|
||||
/// </summary>
|
||||
public string Errmsg { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取服务号AccessToken
|
||||
/// </summary>
|
||||
/// <param name="forceUpdate">强制刷新</param>
|
||||
/// <returns></returns>
|
||||
public static ApiResult<string> GetAccessToken(bool forceUpdate = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
string AppId = BaseConfig.App(new string[] { "WeChatService", "AppId" });
|
||||
if (string.IsNullOrWhiteSpace(AppId)) return ApiResult<string>.Failed("配置文件中未获取有效的服务号AppId");
|
||||
string AppSecret = BaseConfig.App(new string[] { "WeChatService", "AppSecret" });
|
||||
if (string.IsNullOrWhiteSpace(AppSecret)) return ApiResult<string>.Failed("配置文件中未获取有效的服务号AppSecret");
|
||||
|
||||
DateTime now = DateTime.Now;
|
||||
|
||||
if (forceUpdate == false && accessCacheToken != null && now.AddSeconds(-1 * 55 * 2) < accessCacheToken.GetDate)
|
||||
{
|
||||
return ApiResult<string>.Success(string.Empty, accessCacheToken.Access_token);
|
||||
}
|
||||
|
||||
var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}";
|
||||
using (var http = new HttpClient(new HttpClientHandler()))
|
||||
{
|
||||
var res = http.GetAsync(url).Result;
|
||||
if (res.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
_logger.Error("获取公众号access_token失败,微信服务接口响应" + res.StatusCode.ToString());
|
||||
return ApiResult<string>.Failed("获取公众号access_token失败,微信服务接口响应" + res.StatusCode.ToString());
|
||||
}
|
||||
|
||||
var reContent = res.Content.ReadAsStringAsync().Result;
|
||||
if (!string.IsNullOrWhiteSpace(reContent))
|
||||
{
|
||||
var reToken = JsonConvert.DeserializeObject<WxAuthorizationCodeRep>(reContent);
|
||||
if (!string.IsNullOrEmpty(reToken.Access_token))
|
||||
{
|
||||
accessCacheToken = new WxAccessTokenData()
|
||||
{
|
||||
Access_token = reToken.Access_token,
|
||||
GetDate = now
|
||||
};
|
||||
return ApiResult<string>.Success(string.Empty, reToken.Access_token);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Error(reContent);
|
||||
}
|
||||
}
|
||||
return ApiResult<string>.Failed(string.Empty);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Error(ex.Message);
|
||||
return ApiResult<string>.Failed(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 获取用户Openid
|
||||
|
||||
private class WxServiceRes
|
||||
{
|
||||
public string Access_token { get; set; }
|
||||
|
||||
public int? Expires_in { get; set; }
|
||||
|
||||
public string Refresh_token { get; set; }
|
||||
|
||||
public string Openid { get; set; }
|
||||
|
||||
public string Errcode { get; set; }
|
||||
|
||||
public string Errmsg { get; set; }
|
||||
}
|
||||
|
||||
public static ApiResult<string> GetWxSericeOpenId(string code)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(code)) return ApiResult<string>.Failed("未获取到有效的code");
|
||||
string AppId = BaseConfig.App(new string[] { "WeChatService", "AppId" });
|
||||
if (string.IsNullOrWhiteSpace(AppId)) return ApiResult<string>.Failed("配置文件中未获取有效的消息推送AppId");
|
||||
string AppSecret = BaseConfig.App(new string[] { "WeChatService", "AppSecret" });
|
||||
if (string.IsNullOrWhiteSpace(AppSecret)) return ApiResult<string>.Failed("配置文件中未获取有效的消息推送AppSecret");
|
||||
|
||||
|
||||
string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={AppId}&secret={AppSecret}&code={code}&grant_type=authorization_code";
|
||||
using (var http = new HttpClient(new HttpClientHandler()))
|
||||
{
|
||||
var response = http.GetAsync(url).Result;
|
||||
if (response.StatusCode != HttpStatusCode.OK) return ApiResult<string>.Failed("微信接口无响应");
|
||||
|
||||
string res = response.Content.ReadAsStringAsync().Result;
|
||||
if (!string.IsNullOrWhiteSpace(res))
|
||||
{
|
||||
var wxServiceRes = JsonConvert.DeserializeObject<WxServiceRes>(res);
|
||||
if (!string.IsNullOrWhiteSpace(wxServiceRes.Openid))
|
||||
{
|
||||
return ApiResult<string>.Success(string.Empty, wxServiceRes.Openid);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.Error(res);
|
||||
return ApiResult<string>.Failed(wxServiceRes.Errcode);
|
||||
}
|
||||
}
|
||||
return ApiResult<string>.Failed("返回空");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 发送消息模板
|
||||
|
||||
public static ApiResult SendTemplateMsg(string touser, string template_id, string url, string first, string remark, params object[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
string error = string.Empty;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
error = string.Empty;
|
||||
var msg = WechatHelper.BuildTemlMsg(touser, template_id, url, first, remark, args);
|
||||
|
||||
string accessTokenMode = BaseConfig.App(new string[] { "AccessTokenMode" });
|
||||
if (string.IsNullOrWhiteSpace(accessTokenMode))
|
||||
{
|
||||
_logger.Error("配置文件中未获取有效的AccessTokenMode");
|
||||
return ApiResult.Failed("配置文件中未获取有效的AccessTokenMode");
|
||||
}
|
||||
|
||||
ApiResult<string> tokenResult = null;
|
||||
if (i == 0)
|
||||
{
|
||||
tokenResult = accessTokenMode == "1" ? AizhuhotelGetAccesstoken() : GetAccessToken();
|
||||
}
|
||||
else
|
||||
{
|
||||
tokenResult = accessTokenMode == "1" ? AizhuhotelGetAccesstoken() : GetAccessToken(true);
|
||||
}
|
||||
if (!tokenResult.IsSuccess)
|
||||
{
|
||||
error = "配置文件中未获取有效的AccessTokenMode";
|
||||
_logger.Error(error);
|
||||
continue;
|
||||
}
|
||||
|
||||
var postUrl = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={tokenResult.Info}";
|
||||
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
|
||||
request.Proxy = null;
|
||||
request.Method = "POST";
|
||||
request.ContentType = "application/json";
|
||||
// request.Timeout = 10000;
|
||||
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
|
||||
{
|
||||
dataStream.Write(msg);
|
||||
dataStream.Close();
|
||||
}
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
if (response == null)
|
||||
{
|
||||
error = "远程服务器没有响应!";
|
||||
_logger.Error(error);
|
||||
continue;
|
||||
}
|
||||
string encoding = response.ContentEncoding;
|
||||
if (encoding == null || encoding.Length < 1)
|
||||
{
|
||||
encoding = "UTF-8"; //默认编码
|
||||
}
|
||||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
|
||||
string retString = reader.ReadToEnd();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(retString))
|
||||
{
|
||||
var sendTemplateMsgRes = JsonConvert.DeserializeObject<SendTemplateMsgRes>(retString);
|
||||
if (sendTemplateMsgRes.Errmsg.ToLower() == "ok")
|
||||
{
|
||||
return ApiResult.Success(string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
error = $"接收者openid:{touser},错误代码{sendTemplateMsgRes.Errcode}";
|
||||
_logger.Error(error);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ApiResult.Failed(msg: "", info: error);
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Debug(ex.ToString());
|
||||
return ApiResult.Failed(msg: "", info: ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送模板消息返回结果
|
||||
/// </summary>
|
||||
private class SendTemplateMsgRes
|
||||
{
|
||||
/// <summary>
|
||||
/// 返回代码,0-发送成功
|
||||
/// </summary>
|
||||
public int Errcode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回消息:"ok"-成功
|
||||
/// </summary>
|
||||
public string Errmsg { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 发送成功返回编号:失败不返回
|
||||
/// </summary>
|
||||
public long? Msgid { get; set; }
|
||||
}
|
||||
|
||||
public static void SendTemplateMsg(List<string> tousers, string template_id, string url, string first, string remark, params object[] args)
|
||||
{
|
||||
if (tousers == null || tousers.Count == 0) return;
|
||||
string accessTokenMode = BaseConfig.App(new string[] { "AccessTokenMode" });
|
||||
if (string.IsNullOrWhiteSpace(accessTokenMode))
|
||||
{
|
||||
_logger.Error("配置文件中未获取有效的AccessTokenMode");
|
||||
return;
|
||||
}
|
||||
|
||||
ApiResult<string> tokenResult = accessTokenMode == "1" ? AizhuhotelGetAccesstoken() : GetAccessToken();
|
||||
if (!tokenResult.IsSuccess)
|
||||
{
|
||||
_logger.Error(tokenResult.Msg);
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> msgList = new List<string>();
|
||||
foreach (var touser in tousers)
|
||||
{
|
||||
msgList.Add(WechatHelper.BuildTemlMsg(touser, template_id, url, first, remark, args));
|
||||
}
|
||||
|
||||
int send = 0;
|
||||
_logger.Info($"发送推送消息,模板:{template_id}, 接收者openId:{string.Join(",", msgList)} 。");
|
||||
StringBuilder msg = new StringBuilder();
|
||||
foreach (var itemMsg in msgList)
|
||||
{
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
tokenResult = accessTokenMode == "1" ? AizhuhotelGetAccesstoken() : GetAccessToken(true);
|
||||
if (!tokenResult.IsSuccess)
|
||||
{
|
||||
_logger.Error(tokenResult.Msg);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var postUrl = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={tokenResult.Info}";
|
||||
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);
|
||||
request.Proxy = null;
|
||||
request.Method = "POST";
|
||||
request.ContentType = "application/json";
|
||||
// request.Timeout = 10000;
|
||||
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
|
||||
{
|
||||
dataStream.Write(itemMsg);
|
||||
dataStream.Close();
|
||||
}
|
||||
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
|
||||
if (response == null)
|
||||
{
|
||||
_logger.Error("微信接口远程服务器没有响应");
|
||||
continue;
|
||||
}
|
||||
string encoding = response.ContentEncoding;
|
||||
if (encoding == null || encoding.Length < 1)
|
||||
{
|
||||
encoding = "UTF-8"; //默认编码
|
||||
}
|
||||
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
|
||||
string retString = reader.ReadToEnd();
|
||||
_logger.Info("-->" + itemMsg);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(retString))
|
||||
{
|
||||
var sendTemplateMsgRes = JsonConvert.DeserializeObject<SendTemplateMsgRes>(retString);
|
||||
if (sendTemplateMsgRes.Errmsg.ToLower() == "ok")
|
||||
{
|
||||
send += 1;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (msg.Length == 0) msg.AppendFormat("消息推送失败:消息模板{0}", template_id);
|
||||
msg.AppendFormat("接收者openid:{0},错误代码{1}", itemMsg, sendTemplateMsgRes.Errcode);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
if (msg.Length > 0) _logger.Error(msg.ToString());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
192
api_v1/Appointment.Entity/Utility/ApiResult.cs
Normal file
192
api_v1/Appointment.Entity/Utility/ApiResult.cs
Normal file
@@ -0,0 +1,192 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
/// <summary>
|
||||
/// 接口返回数据标准
|
||||
/// </summary>
|
||||
public class ApiResult
|
||||
{
|
||||
/// <summary>
|
||||
/// 响应状态:true-成功执行,flase-响应异常
|
||||
/// </summary>
|
||||
public bool IsSuccess { get { return this.Code == (int)HttpStatusCode.OK; } }
|
||||
|
||||
/// <summary>
|
||||
/// 是否有效执行以IsSuccess为基准
|
||||
/// 200-有效执行,500-服务错误
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 此属性为定制化返回代码,例如登录成功并需要返回提示修改密码等相关类似的业务
|
||||
/// </remarks>
|
||||
public int Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回消息文本内容
|
||||
/// </summary>
|
||||
public string Msg { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回数据
|
||||
/// </summary>
|
||||
public object Info { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="info"></param>
|
||||
public ApiResult(int code = (int)HttpStatusCode.OK, string msg = "操作成功", object info = null)
|
||||
{
|
||||
this.Code = code;
|
||||
this.Msg = msg;
|
||||
this.Info = info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 成功执行
|
||||
/// </summary>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
public static ApiResult Success(string msg = "操作成功", object info = null)
|
||||
{
|
||||
return new ApiResult
|
||||
{
|
||||
Code = (int)HttpStatusCode.OK,
|
||||
Msg = msg,
|
||||
Info = info,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行错误
|
||||
/// </summary>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
public static ApiResult Failed(string msg = "操作失败", object info = null, int code = (int)HttpStatusCode.InternalServerError)
|
||||
{
|
||||
return new ApiResult
|
||||
{
|
||||
Code = code,
|
||||
Msg = msg,
|
||||
Info = info,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 接口返回数据标准
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class ApiResult<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 响应状态:true-成功执行,flase-响应异常
|
||||
/// </summary>
|
||||
public bool IsSuccess { get { return this.Code == (int)HttpStatusCode.OK; } }
|
||||
|
||||
/// <summary>
|
||||
/// 是否有效执行以IsSuccess为基准
|
||||
/// 200-有效执行,500-服务错误
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 此属性为定制化返回代码,例如登录成功并需要返回提示修改密码等相关类似的业务
|
||||
/// </remarks>
|
||||
public int Code { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回消息文本内容
|
||||
/// </summary>
|
||||
public string Msg { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 返回数据
|
||||
/// </summary>
|
||||
public T Info { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="info"></param>
|
||||
public ApiResult(int code = (int)HttpStatusCode.OK, string msg = "操作成功", T info = default)
|
||||
{
|
||||
this.Code = code;
|
||||
this.Msg = msg;
|
||||
this.Info = info;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行成功
|
||||
/// </summary>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
public static ApiResult<T> Success(string msg = "操作成功", T info = default)
|
||||
{
|
||||
return new ApiResult<T>
|
||||
{
|
||||
Code = (int)HttpStatusCode.OK,
|
||||
Msg = msg,
|
||||
Info = info,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 出现错误
|
||||
/// </summary>
|
||||
/// <param name="msg"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="info"></param>
|
||||
/// <returns></returns>
|
||||
public static ApiResult<T> Failed(string msg = "操作失败", int code = (int)HttpStatusCode.InternalServerError, T info = default)
|
||||
{
|
||||
return new ApiResult<T>
|
||||
{
|
||||
Code = code,
|
||||
Msg = msg,
|
||||
Info = info,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 公共Msg
|
||||
/// </summary>
|
||||
public class ApiResultMsg
|
||||
{
|
||||
/// <summary>
|
||||
/// 参数无效
|
||||
/// </summary>
|
||||
public string InvalidParameter { get { return $"参数[{_InvalidParameter}]无效!"; } set { _InvalidParameter = value; } }
|
||||
private string _InvalidParameter;
|
||||
|
||||
/// <summary>
|
||||
/// 缺少参数
|
||||
/// </summary>
|
||||
public static string NoParameter { get { return "缺少参数!"; } }
|
||||
|
||||
/// <summary>
|
||||
/// 没有权限
|
||||
/// </summary>
|
||||
public static string NoPower { get { return "没有权限,操作失败!"; } }
|
||||
|
||||
/// <summary>
|
||||
/// 没有数据
|
||||
/// </summary>
|
||||
public static string NoData { get { return "没有数据!"; } }
|
||||
|
||||
/// <summary>
|
||||
/// 数据不正确
|
||||
/// </summary>
|
||||
public static string ErrorData { get { return "数据不正确!"; } }
|
||||
}
|
||||
}
|
||||
119
api_v1/Appointment.Entity/Utility/BaseConfig.cs
Normal file
119
api_v1/Appointment.Entity/Utility/BaseConfig.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Configuration.Json;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public class BaseConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// 缓存配置文件
|
||||
/// </summary>
|
||||
static IConfiguration configuration { get; set; }
|
||||
|
||||
static BaseConfig()
|
||||
{
|
||||
/* 当配置文件更新后,IConfiguration会自动更新,使用缓存为了双重保障 */
|
||||
DateTime now = DateTime.Now;
|
||||
if (validTime < now)
|
||||
{
|
||||
string path = "appsettings.json";
|
||||
var _newCreateTime = System.IO.File.GetCreationTime(path);
|
||||
if (_newCreateTime != createTime)
|
||||
{
|
||||
configuration = new ConfigurationBuilder()
|
||||
.Add(new JsonConfigurationSource
|
||||
{
|
||||
Path = path,
|
||||
Optional = false,
|
||||
ReloadOnChange = true
|
||||
}).Build();
|
||||
createTime = _newCreateTime;
|
||||
}
|
||||
validTime = now.AddSeconds(60);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 缓存配置文件创建时间
|
||||
/// </summary>
|
||||
static DateTime createTime;
|
||||
|
||||
/// <summary>
|
||||
/// 缓存配置文件失效时间
|
||||
/// </summary>
|
||||
static DateTime validTime;
|
||||
|
||||
/// <summary>
|
||||
/// 获取配置信息(必项)
|
||||
/// </summary>
|
||||
/// <param name="sections"></param>
|
||||
/// <returns>当不存在或为空是输出异常</returns>
|
||||
public static string App(params string[] sections)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (sections.Any())
|
||||
{
|
||||
string str = configuration[string.Join(":", sections)];
|
||||
if (!string.IsNullOrEmpty(str))
|
||||
{
|
||||
return str;
|
||||
}
|
||||
}
|
||||
throw new Exception($"没有在配置文件中的appSettings中找到{sections.Last()}的配置,请检查配置文件配置!");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取配置文件
|
||||
/// </summary>
|
||||
/// <param name="sections"></param>
|
||||
/// <param name="defaultValue">默认返回值</param>
|
||||
/// <returns>当不存在的配置项会返回null</returns>
|
||||
/// <remarks>
|
||||
/// 获取实例:
|
||||
/// BaseConfig.App(new string[] { "Logging" });
|
||||
/// BaseConfig.App(new string[] { "Logging", "LogLevel" });
|
||||
/// </remarks>
|
||||
public static string App(string[] sections, string defaultValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (sections.Any())
|
||||
{
|
||||
string stre = configuration[string.Join(":", sections)];
|
||||
|
||||
if (!string.IsNullOrEmpty(stre)) return stre;
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归获取配置信息数组
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="sections"></param>
|
||||
/// <returns></returns>
|
||||
public static List<T> App<T>(params string[] sections)
|
||||
{
|
||||
List<T> list = new List<T>();
|
||||
configuration.Bind(string.Join(":", sections), list);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
109
api_v1/Appointment.Entity/Utility/CryptoHelper.cs
Normal file
109
api_v1/Appointment.Entity/Utility/CryptoHelper.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public static class CryptoHelper
|
||||
{
|
||||
private static byte[] DESKeys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
|
||||
|
||||
/// <summary>
|
||||
/// MD5小写加密
|
||||
/// </summary>
|
||||
/// <param name="token">加密前字符串</param>
|
||||
/// <returns></returns>
|
||||
/// <remarks>
|
||||
/// 使用了UTF8格式
|
||||
/// </remarks>
|
||||
public static string Md5(string token)
|
||||
{
|
||||
StringBuilder strHash = new StringBuilder();
|
||||
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
|
||||
byte[] bytHash;
|
||||
|
||||
bytHash = md5.ComputeHash(Encoding.UTF8.GetBytes(token));
|
||||
md5.Clear();
|
||||
for (int i = 0; i < bytHash.Length; i++)
|
||||
{
|
||||
strHash.Append(bytHash[i].ToString("x").PadLeft(2, '0'));
|
||||
}
|
||||
return strHash.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MD5大写加密
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks>
|
||||
/// 字符串转为ASCII再加密
|
||||
/// 与前面方法Md5()的区别是汉字加密后的结构不一致,
|
||||
/// </remarks>
|
||||
public static string Md5Hash(string input)
|
||||
{
|
||||
string strResult;
|
||||
using (var md51 = System.Security.Cryptography.MD5.Create())
|
||||
{
|
||||
var result = md51.ComputeHash(Encoding.ASCII.GetBytes(input));
|
||||
strResult = BitConverter.ToString(result);
|
||||
strResult = strResult.Replace("-", "");
|
||||
}
|
||||
return strResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DES加密字符串
|
||||
/// </summary>
|
||||
/// <param name="encryptString">待加密的字符串</param>
|
||||
/// <param name="encryptKey">加密密钥,要求为8位</param>
|
||||
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
|
||||
public static string DES_Encode(string encryptString, string encryptKey = "dlhisapi")
|
||||
{
|
||||
encryptKey = encryptKey.Substring(0, 8);
|
||||
encryptKey = encryptKey.PadRight(8, ' ');
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
|
||||
byte[] rgbIV = DESKeys;
|
||||
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
|
||||
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
|
||||
MemoryStream mStream = new MemoryStream();
|
||||
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Convert.ToBase64String(mStream.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DES解密字符串
|
||||
/// </summary>
|
||||
/// <param name="decryptString">待解密的字符串</param>
|
||||
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
|
||||
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
|
||||
public static string DES_Decode(string decryptString, string decryptKey = "dlhisapi")
|
||||
{
|
||||
try
|
||||
{
|
||||
decryptKey = decryptKey.Substring(0, 8);
|
||||
decryptKey = decryptKey.PadRight(8, ' ');
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
|
||||
byte[] rgbIV = DESKeys;
|
||||
byte[] inputByteArray = Convert.FromBase64String(decryptString);
|
||||
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
|
||||
|
||||
MemoryStream mStream = new MemoryStream();
|
||||
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Encoding.UTF8.GetString(mStream.ToArray());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
16
api_v1/Appointment.Entity/Utility/DateTimeHelper.cs
Normal file
16
api_v1/Appointment.Entity/Utility/DateTimeHelper.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public static class DateTimeHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取sql server最小时间
|
||||
/// </summary>
|
||||
public static DateTime MSSQLMinValue { get { return _MSSQLMinValue; }}
|
||||
private static DateTime _MSSQLMinValue = new DateTime(1753, 1, 1);
|
||||
|
||||
}
|
||||
}
|
||||
24
api_v1/Appointment.Entity/Utility/PagerData.cs
Normal file
24
api_v1/Appointment.Entity/Utility/PagerData.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
/// <summary>
|
||||
/// 上下文分页类型
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <remarks>
|
||||
/// Add:yuangb 2017-3-1
|
||||
/// </remarks>
|
||||
public class PagerData<T>
|
||||
{
|
||||
public int PageIndex { get; set; }
|
||||
|
||||
public int PageSize { get; set; }
|
||||
|
||||
public int Total { get; set; }
|
||||
|
||||
public List<T> Data { get; set; }
|
||||
}
|
||||
}
|
||||
111
api_v1/Appointment.Entity/Utility/PicHelper.cs
Normal file
111
api_v1/Appointment.Entity/Utility/PicHelper.cs
Normal file
@@ -0,0 +1,111 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public static class PicHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取图片域名
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetPicDomain()
|
||||
{
|
||||
string value = string.Empty;
|
||||
using (System.IO.StreamReader file = System.IO.File.OpenText("appsettings.json"))
|
||||
{
|
||||
using JsonTextReader reader = new JsonTextReader(file);
|
||||
JObject o = (JObject)JToken.ReadFrom(reader);
|
||||
value = Convert.ToString(o["WebApiDomain"]);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(value)) throw new Exception("配置信息中缺少WebApiDomain");
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取图片保存服务器完整路径
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetPicRootPath()
|
||||
{
|
||||
string value = string.Empty;
|
||||
using (System.IO.StreamReader file = System.IO.File.OpenText("appsettings.json"))
|
||||
{
|
||||
using JsonTextReader reader = new JsonTextReader(file);
|
||||
JObject o = (JObject)JToken.ReadFrom(reader);
|
||||
value = Convert.ToString(o["PicRootPath"]);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(value)) throw new Exception("配置信息中缺少PicRootPath");
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 保存图片
|
||||
/// </summary>
|
||||
/// <param name="base64str">图片BASE64</param>
|
||||
/// <returns>NULL-保存图片异常,""-没有图片,其他-保存后的路径</returns>
|
||||
public static ApiResult<string> SavePic(string base64str)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(base64str)) return ApiResult<string>.Success(string.Empty);
|
||||
if (base64str.ToLower().IndexOf("imgfile") > 0) return ApiResult<string>.Success(base64str.Substring(base64str.ToLower().IndexOf("imgfile") - 1));
|
||||
|
||||
DateTime now = DateTime.Now;
|
||||
var rd = new Random().Next(100, 999);
|
||||
string filePath = $"/ImgFile/{now:yyyyMM}";
|
||||
string fileName = $"{now:yyyyMMddHHmmssfff}{rd}";
|
||||
base64str = base64str.Substring(base64str.IndexOf(",") + 1).Trim('\0');
|
||||
byte[] arr = Convert.FromBase64String(base64str);
|
||||
using (MemoryStream ms = new MemoryStream(arr))
|
||||
{
|
||||
if (!Directory.Exists(GetPicRootPath() + filePath)) Directory.CreateDirectory(GetPicRootPath() + filePath);
|
||||
Bitmap bmp = new Bitmap(ms);
|
||||
|
||||
ImageCodecInfo myImageCodecInfo = GetEnoderInfo(bmp.RawFormat.ToString().ToLower());
|
||||
if (bmp.RawFormat.ToString().ToLower().Contains("jpeg"))
|
||||
{
|
||||
fileName = $"{fileName}.jpg";
|
||||
myImageCodecInfo = GetEnoderInfo("png");
|
||||
}
|
||||
else
|
||||
{
|
||||
fileName = $"{fileName}.{bmp.RawFormat}";
|
||||
}
|
||||
|
||||
EncoderParameters destEncParams = new EncoderParameters(1);
|
||||
destEncParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100);
|
||||
|
||||
bmp.Save($"{GetPicRootPath()}{filePath}/{fileName}", myImageCodecInfo, destEncParams);
|
||||
ms.Close();
|
||||
}
|
||||
|
||||
return ApiResult<string>.Success($"{filePath}/{fileName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ApiResult<string>.Failed("保存图片失败,失败信息:" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
#region private
|
||||
private static ImageCodecInfo GetEnoderInfo(string mineType)
|
||||
{
|
||||
ImageCodecInfo[] myEncoders = ImageCodecInfo.GetImageEncoders();
|
||||
|
||||
foreach (System.Drawing.Imaging.ImageCodecInfo myEncoder in myEncoders)
|
||||
if (myEncoder.MimeType.Contains(mineType))
|
||||
return myEncoder;
|
||||
return null;
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
44
api_v1/Appointment.Entity/Utility/RegexHelper.cs
Normal file
44
api_v1/Appointment.Entity/Utility/RegexHelper.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Appointment.Entity.Utility
|
||||
{
|
||||
/// <summary>
|
||||
/// 正则表达式
|
||||
/// </summary>
|
||||
public static class RegexHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 判断是否为手机号码
|
||||
/// </summary>
|
||||
/// <param name="value">字符串</param>
|
||||
/// <returns>True-是,False-否</returns>
|
||||
/// <remarks>
|
||||
/// Add:yuangb 2016-6-12
|
||||
/// </remarks>
|
||||
public static bool IsPhone(this string value)
|
||||
{
|
||||
value = value.Replace("+86", "");
|
||||
return Regex.IsMatch(value, @"^1[3-9]{1}[0-9]{9}$");
|
||||
}
|
||||
|
||||
public static TChild AutoCopy<TParent, TChild>(TParent parent) where TChild : TParent, new()
|
||||
{
|
||||
TChild child = new TChild();
|
||||
var ParentType = typeof(TParent);
|
||||
var Properties = ParentType.GetProperties();
|
||||
foreach (var Propertie in Properties)
|
||||
{
|
||||
//循环遍历属性
|
||||
if (Propertie.CanRead && Propertie.CanWrite)
|
||||
{
|
||||
//进行属性拷贝
|
||||
Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
|
||||
}
|
||||
}
|
||||
return child;
|
||||
}
|
||||
}
|
||||
}
|
||||
150
api_v1/Appointment.Entity/Utility/StringHelper.cs
Normal file
150
api_v1/Appointment.Entity/Utility/StringHelper.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public static class StringHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 去除对象字符串后面的空格
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="t"></param>
|
||||
/// <returns></returns>
|
||||
public static T Replace<T>(this T t)
|
||||
{
|
||||
string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(t);
|
||||
while (true)
|
||||
{
|
||||
if (jsonStr.IndexOf(" \"") > -1)
|
||||
{
|
||||
jsonStr = jsonStr.Replace(" \"","\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonStr);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 得到一个汉字的拼音第一个字母,如果是一个英文字母则直接返回大写字母
|
||||
/// </summary>
|
||||
/// <param name="CnChar">单个汉字</param>
|
||||
/// <returns>单个大写字母</returns>
|
||||
public static string GetCharSpellCode(string CnChar)
|
||||
{
|
||||
long iCnChar;
|
||||
byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar);
|
||||
|
||||
//如果是字母,则直接返回首字母
|
||||
if (ZW.Length == 1)
|
||||
{
|
||||
return CnChar.ToUpper();
|
||||
}
|
||||
else
|
||||
{
|
||||
int i1 = (short)(ZW[0]);
|
||||
int i2 = (short)(ZW[1]);
|
||||
iCnChar = i1 * 256 + i2;
|
||||
}
|
||||
if ((iCnChar >= 45217) && (iCnChar <= 45252))
|
||||
{
|
||||
return "A";
|
||||
}
|
||||
else if ((iCnChar >= 45253) && (iCnChar <= 45760))
|
||||
{
|
||||
return "B";
|
||||
}
|
||||
else if ((iCnChar >= 45761) && (iCnChar <= 46317))
|
||||
{
|
||||
return "C";
|
||||
}
|
||||
else if ((iCnChar >= 46318) && (iCnChar <= 46825))
|
||||
{
|
||||
return "D";
|
||||
}
|
||||
else if ((iCnChar >= 46826) && (iCnChar <= 47009))
|
||||
{
|
||||
return "E";
|
||||
}
|
||||
else if ((iCnChar >= 47010) && (iCnChar <= 47296))
|
||||
{
|
||||
return "F";
|
||||
}
|
||||
else if ((iCnChar >= 47297) && (iCnChar <= 47613))
|
||||
{
|
||||
return "G";
|
||||
}
|
||||
else if ((iCnChar >= 47614) && (iCnChar <= 48118))
|
||||
{
|
||||
return "H";
|
||||
}
|
||||
else if ((iCnChar >= 48119) && (iCnChar <= 49061))
|
||||
{
|
||||
return "J";
|
||||
}
|
||||
else if ((iCnChar >= 49062) && (iCnChar <= 49323))
|
||||
{
|
||||
return "K";
|
||||
}
|
||||
else if ((iCnChar >= 49324) && (iCnChar <= 49895))
|
||||
{
|
||||
return "L";
|
||||
}
|
||||
else if ((iCnChar >= 49896) && (iCnChar <= 50370))
|
||||
{
|
||||
return "M";
|
||||
}
|
||||
else if ((iCnChar >= 50371) && (iCnChar <= 50613))
|
||||
{
|
||||
return "N";
|
||||
}
|
||||
else if ((iCnChar >= 50614) && (iCnChar <= 50621))
|
||||
{
|
||||
return "O";
|
||||
}
|
||||
else if ((iCnChar >= 50622) && (iCnChar <= 50905))
|
||||
{
|
||||
return "P";
|
||||
}
|
||||
else if ((iCnChar >= 50906) && (iCnChar <= 51386))
|
||||
{
|
||||
return "Q";
|
||||
}
|
||||
else if ((iCnChar >= 51387) && (iCnChar <= 51445))
|
||||
{
|
||||
return "R";
|
||||
}
|
||||
else if ((iCnChar >= 51446) && (iCnChar <= 52217))
|
||||
{
|
||||
return "S";
|
||||
}
|
||||
else if ((iCnChar >= 52218) && (iCnChar <= 52697))
|
||||
{
|
||||
return "T";
|
||||
}
|
||||
else if ((iCnChar >= 52698) && (iCnChar <= 52979))
|
||||
{
|
||||
return "W";
|
||||
}
|
||||
else if ((iCnChar >= 52980) && (iCnChar <= 53640))
|
||||
{
|
||||
return "X";
|
||||
}
|
||||
else if ((iCnChar >= 53689) && (iCnChar <= 54480))
|
||||
{
|
||||
return "Y";
|
||||
}
|
||||
else if ((iCnChar >= 54481) && (iCnChar <= 55289))
|
||||
{
|
||||
return "Z";
|
||||
}
|
||||
else
|
||||
return ("?");
|
||||
}
|
||||
}
|
||||
}
|
||||
123
api_v1/Appointment.Entity/Utility/WechatHelper.cs
Normal file
123
api_v1/Appointment.Entity/Utility/WechatHelper.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
|
||||
namespace Appointment.Entity
|
||||
{
|
||||
public class WechatHelper
|
||||
{
|
||||
private static HttpClient _HttpClient = null;
|
||||
|
||||
static WechatHelper()
|
||||
{
|
||||
_HttpClient = new HttpClient(new HttpClientHandler());
|
||||
}
|
||||
|
||||
public object JsonConvert { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 根据小程序登录code获取用户信息
|
||||
/// </summary>
|
||||
/// <param name="code"></param>
|
||||
/// <returns></returns>
|
||||
public ApiResult<WeChatLoginRes> Code2Session(string code)
|
||||
{
|
||||
string appId = BaseConfig.App(new string[] { "WeChat", "AppId" });
|
||||
if(string.IsNullOrWhiteSpace(appId)) ApiResult<WeChatLoginRes>.Failed("缺少配置参数 [AppId]!");
|
||||
string appSecret = BaseConfig.App(new string[] { "WeChat", "AppSecret" });
|
||||
if (string.IsNullOrWhiteSpace(appSecret)) ApiResult<WeChatLoginRes>.Failed("缺少配置参数 [AppSecret]!");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(code) || string.IsNullOrWhiteSpace(appId) || string.IsNullOrWhiteSpace(appSecret))
|
||||
{
|
||||
return ApiResult<WeChatLoginRes>.Failed("获取小程序配置信息出错");
|
||||
}
|
||||
|
||||
string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code";
|
||||
|
||||
var res = _HttpClient.GetAsync(url).Result;
|
||||
if (res.StatusCode == HttpStatusCode.OK)
|
||||
{
|
||||
var result = Encoding.Default.GetString(res.Content.ReadAsByteArrayAsync().Result);
|
||||
if (string.IsNullOrWhiteSpace(result) || result.IndexOf("session_key") == -1)
|
||||
{
|
||||
return ApiResult<WeChatLoginRes>.Failed("调用微信接口失败,可能code已失效");
|
||||
}
|
||||
|
||||
var weChatDto = Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatLoginRes>(result);
|
||||
|
||||
return ApiResult<WeChatLoginRes>.Success("", weChatDto);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ApiResult<WeChatLoginRes>.Failed("调用微信接口失败");
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public class LoveInnGetAccessTokenReq
|
||||
{
|
||||
public string AppId { get; set; }
|
||||
|
||||
public string AppName { get; set; }
|
||||
|
||||
public string AppSecret { get; set; }
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 模版信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string BuildTemlMsg(string toUser, string tmplId, string url, string first, string remark, params object[] args)
|
||||
{
|
||||
string appId = BaseConfig.App(new string[] { "WeChat", "AppId" });
|
||||
if (string.IsNullOrWhiteSpace(appId)) ApiResult<WeChatLoginRes>.Failed("缺少配置参数 [AppId]!");
|
||||
|
||||
StringBuilder sbMsg = new StringBuilder();
|
||||
|
||||
sbMsg.Append("{");
|
||||
sbMsg.AppendFormat("\"touser\":\"{0}\",", toUser);
|
||||
sbMsg.AppendFormat("\"template_id\":\"{0}\",", tmplId);
|
||||
sbMsg.Append("\"miniprogram\":{");
|
||||
sbMsg.AppendFormat("\"appid\":\"{0}\",", appId);
|
||||
sbMsg.AppendFormat("\"pagepath\":\"{0}\"", url);
|
||||
sbMsg.Append("},");
|
||||
sbMsg.Append("\"topcolor\":\"#FF0000\",");
|
||||
sbMsg.Append("\"data\":");
|
||||
sbMsg.Append("{");
|
||||
|
||||
sbMsg.Append("\"first\":");
|
||||
sbMsg.Append("{");
|
||||
sbMsg.AppendFormat("\"value\":\"{0}\",", first);
|
||||
sbMsg.AppendFormat("\"color\":\"{0}\"", "#333333");
|
||||
sbMsg.Append("},");
|
||||
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
sbMsg.AppendFormat("\"keyword{0}\":", i + 1);
|
||||
sbMsg.Append("{");
|
||||
sbMsg.AppendFormat("\"value\":\"{0}\",", args[i]);
|
||||
sbMsg.AppendFormat("\"color\":\"{0}\"", "#333333");
|
||||
sbMsg.Append("},");
|
||||
}
|
||||
|
||||
sbMsg.Append("\"remark\":");
|
||||
sbMsg.Append("{");
|
||||
sbMsg.AppendFormat("\"value\":\"{0}\",", remark);
|
||||
sbMsg.AppendFormat("\"color\":\"{0}\"", "#333333");
|
||||
sbMsg.Append("}");
|
||||
|
||||
sbMsg.Append("}");
|
||||
sbMsg.Append("}");
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return sbMsg.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user