using CommonUtil;
|
using CommonUtil.Web;
|
using System;
|
using System.Collections.Generic;
|
using System.Text;
|
|
namespace Operater.Common
|
{
|
|
public class SmsGzhHelperHandle
|
{
|
public static GzhToken _gzhToken;
|
|
/// <summary>
|
/// 获取公众号acess_token
|
/// </summary>
|
/// <returns></returns>
|
public static GetAccessTokenResponse GetGzhAccessToken()
|
{
|
string gzhAppid = ConfigUtil.GetValue<string>("gzhappid");
|
string gzhSecret= ConfigUtil.GetValue<string>("gzhsecret");
|
string getUrl = $" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={gzhAppid}&secret={gzhSecret}";
|
string resStr = new WebUtil().DoGet(getUrl, null);
|
LogUtil.Info($"[获取access_token]返回:{resStr}", "接口请求日志");
|
if (resStr.IsNullOrEmpty())
|
{
|
return null;
|
}
|
GetAccessTokenResponse response = JSONUtil.JsonToObject<GetAccessTokenResponse>(resStr);
|
return response;
|
}
|
|
/// <summary>
|
/// 获取公众号token
|
/// </summary>
|
/// <returns></returns>
|
public static string GetGzhToken()
|
{
|
if (_gzhToken.IsNull() || _gzhToken.ExpressTime < DateTime.Now)
|
{
|
if (_gzhToken.IsNull())
|
{
|
_gzhToken = new GzhToken();
|
}
|
var token = GetGzhAccessToken();
|
_gzhToken.AccessToken = token.access_token;
|
_gzhToken.ExpressTime = DateTime.Now.AddSeconds(token.expires_in);
|
}
|
return _gzhToken.AccessToken;
|
}
|
|
/// <summary>
|
/// 发送公众号模板消息
|
/// </summary>
|
/// <param name="request"></param>
|
public static SendTemplateMsgResponse SendTemplateMsg(SendTemplateMsgRequest request, string access_token)
|
{
|
string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
|
Dictionary<string, object> dic = new Dictionary<string, object>();
|
dic.Add("touser", request.touser);
|
dic.Add("template_id", request.template_id);
|
dic.Add("data", request.data);
|
string resStr = new WebUtil().DoPostWithJson(url, dic, null);
|
LogUtil.Info($"[发模板消息]请求:{JSONUtil.ObjectToJson(dic)},返回:{resStr}", "发送模板消息日志");
|
SendTemplateMsgResponse res = JSONUtil.JsonToObject<SendTemplateMsgResponse>(resStr);
|
return res;
|
}
|
}
|
public class SendTemplateMsgRequest
|
{
|
public string touser { get; set; }
|
|
public string template_id { get; set; }
|
|
public object data { get; set; }
|
|
}
|
|
public class SendTemplateMsgResponse : WxKfBaseResponse
|
{
|
public string msgid { get; set; }
|
}
|
|
public class GzhToken
|
{
|
public string AccessToken { get; set; }
|
|
public DateTime ExpressTime { get; set; }
|
}
|
public class WxKfBaseResponse
|
{
|
public int errcode { get; set; }
|
|
public string errmsg { get; set; }
|
}
|
public class GetAccessTokenResponse : WxKfBaseResponse
|
{
|
public string access_token { get; set; }
|
|
public long expires_in { get; set; }
|
}
|
}
|