新增微信公众号功能

This commit is contained in:
不做码农 2023-07-19 07:29:49 +08:00
parent 946f4a6de9
commit e496d4095b
6 changed files with 191 additions and 14 deletions

View File

@ -100,6 +100,12 @@ namespace Infrastructure
long unixTime = ((DateTimeOffset)dt).ToUnixTimeMilliseconds();
return unixTime;
}
public static long GetUnixTimeSeconds(DateTime dt)
{
long unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();
return unixTime;
}
#endregion
#region

View File

@ -0,0 +1,43 @@
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Mvc;
using System.Web;
namespace ZR.Admin.WebApi.Controllers
{
/// <summary>
/// 微信公众号
/// </summary>
[Route("[controller]/[action]")]
[AllowAnonymous]
public class WxOpenController : BaseController
{
private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public WxOpenController() { }
/// <summary>
/// 获取签名
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
[Log(Title = "获取微信签名")]
[HttpGet]
public IActionResult GetSignature(string url = "")
{
url = HttpUtility.UrlDecode(url);
var appId = AppSettings.App(new string[] { "WxOpen", "AppID" });
var noncestr = Guid.NewGuid().ToString().Replace("-", "");
var timestamp = DateTimeHelper.GetUnixTimeSeconds(DateTime.Now);
var ticketResult = WxHelper.GetTicket();
if (appId.IsEmpty()) return ToResponse(ResultCode.CUSTOM_ERROR, "appId未配置");
if (ticketResult?.errcode != 0)
{
return ToResponse(ResultCode.CUSTOM_ERROR, "获取配置失败");
}
var signature = WxHelper.GetSignature(ticketResult.ticket, timestamp.ToString(), noncestr, url);
return SUCCESS(new { appId, signature, noncestr, timestamp, url });
}
}
}

View File

@ -56,6 +56,11 @@
"CorpSecret": "",
"SendUser": "@all"
},
//
"WxOpen": {
"AppID": "",
"AppSecret": ""
},
//
"gen": {
"autoPre": true, //

View File

@ -0,0 +1,13 @@
namespace ZR.Common.Model
{
public class WxTokenResult
{
/// <summary>
/// 0、正常
/// </summary>
public int errcode { get; set; }
public string errmsg { get; set; }
public string access_token { get; set; }
public string ticket { get; set; }
}
}

119
ZR.Common/WxHelper.cs Normal file
View File

@ -0,0 +1,119 @@
using Infrastructure;
using Infrastructure.Extensions;
using Newtonsoft.Json;
using System;
using System.Security.Cryptography;
using System.Text;
using ZR.Common.Model;
namespace ZR.Common
{
public class WxHelper
{
private static readonly string GetTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
private static readonly string GetTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
private static readonly string AppID = AppSettings.App(new string[] { "WxOpen", "AppID" });
private static readonly string AppSECRET = AppSettings.App(new string[] { "WxOpen", "AppSecret" });
/// <summary>
/// 获取访问token
/// </summary>
/// <returns>
/// {"errcode":0,"errmsg":"ok","access_token":"iCbcfE1OjfRhV0_io-CzqTNC0lnrudeW3oF5rhJKfmINaxLClLa1FoqAY_wEXtodYh_DTnrtAwZfzeb-NRXvwiOoqUTHx3i6QKLYcfBtF8y-xd5mvaeaf3e9mvTAPhmX0lkm1cLTwRLmoa1IwzgQ-QZEZcuIcntWdEMGseVYok3BwCGpC87bt6nNdgnekZdFVRp1uuaxoctDGlXpoQlQsA","expires_in":7200}
/// </returns>
private static WxTokenResult GetAccessToken()
{
if (AppID.IsEmpty() || AppSECRET.IsEmpty())
{
Console.WriteLine("公众号配置错误");
throw new ArgumentException("公众号配置错误");
};
var Ck = "wx_token";
string getTokenUrl = $"{GetTokenUrl}?grant_type=client_credential&appid={AppID}&secret={AppSECRET}";
if (CacheHelper.Get(Ck) is WxTokenResult tokenResult)
{
return tokenResult;
}
else
{
string result = HttpHelper.HttpGet(getTokenUrl);
tokenResult = JsonConvert.DeserializeObject<WxTokenResult>(result);
if (tokenResult?.errcode == 0)
{
CacheHelper.SetCache(Ck, tokenResult, 110);
}
else
{
Console.WriteLine("GetAccessToken失败,结果=" + result);
throw new Exception("获取AccessToken失败");
}
}
return tokenResult;
}
/// <summary>
/// 获取ticket
/// </summary>
/// <returns></returns>
public static WxTokenResult GetTicket()
{
WxTokenResult token = GetAccessToken();
string ticket = token?.access_token;
var Ck = "wx_ticket";
string getTokenUrl = $"{GetTicketUrl}?access_token={ticket}&type=jsapi";
if (CacheHelper.Get(Ck) is WxTokenResult tokenResult)
{
return tokenResult;
}
else
{
string result = HttpHelper.HttpGet(getTokenUrl);
tokenResult = JsonConvert.DeserializeObject<WxTokenResult>(result);
if (tokenResult?.errcode == 0)
{
CacheHelper.SetCache(Ck, tokenResult, 110);
}
else
{
Console.WriteLine("GetTicket结果=" + result);
throw new Exception("获取ticket失败");
}
}
return tokenResult;
}
/// <summary>
/// 返回正确的签名
/// </summary>
/// <param name="jsapi_ticket"></param>
/// <param name="timestamp"></param>
/// <param name="noncestr"></param>
/// <param name="url"></param>
/// <returns></returns>
public static string GetSignature(string jsapi_ticket, string timestamp, string noncestr, string url = null)
{
if (string.IsNullOrEmpty(jsapi_ticket) || string.IsNullOrEmpty(noncestr) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(url))
return null;
//将字段添加到列表中。
string[] arr = new[]
{
string.Format("jsapi_ticket={0}",jsapi_ticket),
string.Format("noncestr={0}",noncestr),
string.Format("timestamp={0}",timestamp),
string.Format("url={0}",url)
};
//字典排序
Array.Sort(arr);
//使用URL键值对的格式拼接成字符串
var temp = string.Join("&", arr);
var sha1Arr = SHA1.HashData(Encoding.UTF8.GetBytes(temp));
return BitConverter.ToString(sha1Arr).Replace("-", "").ToLower();
}
}
}

View File

@ -1,6 +1,7 @@
using Infrastructure;
using System.Collections.Generic;
using System.Text.Json;
using ZR.Common.Model;
namespace ZR.Common
{
@ -44,7 +45,7 @@ namespace ZR.Common
System.Console.WriteLine("请完成企业微信配置");
return (0, "请完成企业微信通知配置");
}
GetTokenResult tokenResult = GetAccessToken();
WxTokenResult tokenResult = GetAccessToken();
if (tokenResult == null || tokenResult.errcode != 0)
{
@ -74,7 +75,7 @@ namespace ZR.Common
//返回结果
//{"errcode":0,"errmsg":"ok","invaliduser":""}
string msgResult = HttpHelper.HttpPost(msgUrl, postData, "contentType/json");
GetTokenResult getTokenResult = JsonSerializer.Deserialize<GetTokenResult>(msgResult);
WxTokenResult getTokenResult = JsonSerializer.Deserialize<WxTokenResult>(msgResult);
System.Console.WriteLine(msgResult);
return (getTokenResult?.errcode == 0 ? 100 : 0, getTokenResult?.errmsg);
}
@ -89,12 +90,12 @@ namespace ZR.Common
/// <returns>
/// {"errcode":0,"errmsg":"ok","access_token":"iCbcfE1OjfRhV0_io-CzqTNC0lnrudeW3oF5rhJKfmINaxLClLa1FoqAY_wEXtodYh_DTnrtAwZfzeb-NRXvwiOoqUTHx3i6QKLYcfBtF8y-xd5mvaeaf3e9mvTAPhmX0lkm1cLTwRLmoa1IwzgQ-QZEZcuIcntWdEMGseVYok3BwCGpC87bt6nNdgnekZdFVRp1uuaxoctDGlXpoQlQsA","expires_in":7200}
/// </returns>
private static GetTokenResult GetAccessToken()
private static WxTokenResult GetAccessToken()
{
string getTokenUrl = $"{GetTokenUrl}?corpid={CORPID}&corpsecret={CORPSECRET}";
string getTokenResult = HttpHelper.HttpGet(getTokenUrl);
System.Console.WriteLine(getTokenResult);
GetTokenResult tokenResult = JsonSerializer.Deserialize<GetTokenResult>(getTokenResult);
WxTokenResult tokenResult = JsonSerializer.Deserialize<WxTokenResult>(getTokenResult);
return tokenResult;
}
@ -146,15 +147,5 @@ namespace ZR.Common
};
return dic;
}
public class GetTokenResult
{
/// <summary>
/// 0、正常
/// </summary>
public int errcode { get; set; }
public string errmsg { get; set; }
public string access_token { get; set; }
}
}
}