2021-09-18 12:07:18 +08:00
|
|
|
|
using System.IO;
|
2021-07-30 14:09:25 +08:00
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
|
|
|
|
namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Sample_Net5.Controllers
|
|
|
|
|
{
|
|
|
|
|
[ApiController]
|
|
|
|
|
[Route("notify")]
|
2021-12-04 16:11:49 +08:00
|
|
|
|
public class TenpayNotifyController : ControllerBase
|
2021-07-30 14:09:25 +08:00
|
|
|
|
{
|
|
|
|
|
private readonly ILogger _logger;
|
2021-12-04 16:11:49 +08:00
|
|
|
|
private readonly Services.HttpClients.IWechatTenpayHttpClientFactory _tenpayHttpClientFactory;
|
2021-07-31 21:02:18 +08:00
|
|
|
|
|
2021-12-04 16:11:49 +08:00
|
|
|
|
public TenpayNotifyController(
|
2021-07-31 21:02:18 +08:00
|
|
|
|
ILoggerFactory loggerFactory,
|
2021-12-04 16:11:49 +08:00
|
|
|
|
Services.HttpClients.IWechatTenpayHttpClientFactory tenpayHttpClientFactory)
|
2021-07-30 14:09:25 +08:00
|
|
|
|
{
|
|
|
|
|
_logger = loggerFactory.CreateLogger(GetType());
|
2021-12-04 16:11:49 +08:00
|
|
|
|
_tenpayHttpClientFactory = tenpayHttpClientFactory;
|
2021-07-30 14:09:25 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
[HttpPost]
|
2021-07-31 21:02:18 +08:00
|
|
|
|
[Route("m-{merchant_id}/message-push")]
|
|
|
|
|
public async Task<IActionResult> ReceiveMessage(
|
|
|
|
|
[FromRoute(Name = "merchant_id")] string merchantId,
|
|
|
|
|
[FromHeader(Name = "Wechatpay-Timestamp")] string timestamp,
|
|
|
|
|
[FromHeader(Name = "Wechatpay-Nonce")] string nonce,
|
|
|
|
|
[FromHeader(Name = "Wechatpay-Signature")] string signature,
|
|
|
|
|
[FromHeader(Name = "Wechatpay-Serial")] string serialNumber)
|
2021-07-30 14:09:25 +08:00
|
|
|
|
{
|
|
|
|
|
// 接收服务器推送
|
|
|
|
|
// 文档:https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay4_2.shtml
|
|
|
|
|
|
|
|
|
|
using var reader = new StreamReader(Request.Body, Encoding.UTF8);
|
|
|
|
|
string content = await reader.ReadToEndAsync();
|
|
|
|
|
_logger.LogInformation("接收到微信支付推送的数据:{0}", content);
|
|
|
|
|
|
2021-12-04 16:11:49 +08:00
|
|
|
|
var client = _tenpayHttpClientFactory.Create(merchantId);
|
2021-07-31 21:02:18 +08:00
|
|
|
|
bool valid = client.VerifyEventSignature(
|
|
|
|
|
callbackTimestamp: timestamp,
|
|
|
|
|
callbackNonce: nonce,
|
|
|
|
|
callbackBody: content,
|
|
|
|
|
callbackSignature: signature,
|
|
|
|
|
callbackSerialNumber: serialNumber
|
|
|
|
|
);
|
|
|
|
|
if (!valid)
|
|
|
|
|
{
|
2021-09-18 12:07:18 +08:00
|
|
|
|
// 注意:需提前注入 CertificateManager、并添加平台证书,才可以使用扩展方法执行验签操作
|
|
|
|
|
// 有关 CertificateManager 的用法请参阅《开发文档 / 高级技巧 / 如何验证回调通知事件签名?》
|
2021-07-31 21:02:18 +08:00
|
|
|
|
return new JsonResult(new { code = "FAIL", message = "验签失败" });
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-30 14:09:25 +08:00
|
|
|
|
return new JsonResult(new { code = "SUCCESS", message = "成功" });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|