You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC应用中Webhook调用的处理:实现与测试

本地ASP.NET MVC应用接收PSP Webhook的解决方案

1. 用本地隧道工具把localhost暴露成公开地址

这类工具能把你本地运行的应用端口映射到公网可访问的域名,让PSP能把POST请求发过来。常用的两个工具:

  • ngrok:打开命令行,执行ngrok http 5000(把5000换成你应用实际的运行端口),工具会生成一个类似https://xxxx-xx-xx-xx-xx.ngrok.io的公开地址,把这个地址填到PSP的Webhook配置里就行。
  • localtunnel:如果装了npm,直接执行npx localtunnel --port 5000,同样会生成一个公开域名。

注意:每次重启工具,生成的域名会变化,得同步更新PSP那边的Webhook URL。

2. 在MVC里编写Webhook接收Action

PSP的响应是隐藏字段形式的POST请求,直接用FormCollection或者自定义模型接收字段即可,记得加上签名验证(防止恶意伪造请求):

示例代码:

[HttpPost]
public ActionResult PaymentWebhook(FormCollection form)
{
    // 读取PSP返回的核心字段
    var paymentId = form["PaymentId"];
    var paymentStatus = form["Status"];
    var amount = form["Amount"];

    // 先执行签名验证(必须严格按照PSP文档规则实现,以下是示例)
    var receivedSignature = form["Signature"];
    if (!ValidatePaymentSignature(form, receivedSignature))
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    // 处理业务逻辑:更新订单状态、记录日志、发送通知等
    UpdateOrderPaymentStatus(paymentId, paymentStatus, amount);

    // 返回200 OK给PSP,大部分服务商收到成功响应后就不会重复发送请求
    return new HttpStatusCodeResult(HttpStatusCode.OK);
}

// 签名验证的示例实现(需根据PSP提供的规则调整)
private bool ValidatePaymentSignature(FormCollection form, string receivedSignature)
{
    // 按PSP要求的字段顺序拼接内容,加上商户密钥生成签名
    var rawContent = $"{form["PaymentId"]}{form["Amount"]}{form["Status"]}{"YourMerchantSecretKey"}";
    var computedSignature = CreateHmacSha256Signature(rawContent);
    return computedSignature.Equals(receivedSignature, StringComparison.OrdinalIgnoreCase);
}

private string CreateHmacSha256Signature(string input)
{
    using (var hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes("YourMerchantSecretKey")))
    {
        var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(input));
        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }
}

3. 本地自测Webhook逻辑

不用依赖PSP的真实请求,你可以用Postman或者curl手动发送POST请求到本地地址,模拟PSP的请求格式,先验证代码能否正确解析字段和处理逻辑:

curl命令示例:

curl -X POST http://localhost:5000/Payment/PaymentWebhook \
  -d "PaymentId=TEST_PAY_001" \
  -d "Status=Completed" \
  -d "Amount=99.99" \
  -d "Signature=abc123def456"

先把本地逻辑跑通,再用隧道工具对接PSP的测试环境,能大幅减少调试成本。

内容的提问来源于stack exchange,提问作者Eddie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 05:15:39