You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何通过C# MVC页面接收WooCommerce WebHook的订单追踪数据

How to Receive WooCommerce Order Tracking WebHook Data in C# MVC

Got it, let's walk through how to set up your C# MVC app to receive WooCommerce webhook data for order tracking. I've broken this down into clear, actionable steps so you can get this working quickly:

Step 1: Create a Controller Action to Accept WebHook Requests

First, you'll need a POST action in an MVC controller to handle incoming webhook requests. WooCommerce sends data as JSON, so we'll read the request body and deserialize it into a usable object. Also, we need to disable CSRF validation here because external webhook requests don't include a CSRF token.

Here's the code for your controller:

using System.IO;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text;

public class WooCommerceWebHookController : Controller
{
    // Disable CSRF validation since external webhooks don't provide a token
    [HttpPost]
    [ValidateAntiForgeryToken(false)]
    [Route("test")] // Matches your webhook delivery URL: https://antiochiadoner.com/test
    public ActionResult ReceiveOrderTracking()
    {
        // Read the raw JSON from the request body
        string jsonPayload;
        using (var reader = new StreamReader(Request.InputStream))
        {
            jsonPayload = reader.ReadToEnd();
        }

        // Verify the webhook signature first (critical for security!)
        var signatureHeader = Request.Headers["X-WC-Webhook-Signature"];
        var webHookSecret = "YOUR_WOOCOMMERCE_WEBHOOK_SECRET"; // Replace with your actual secret
        if (!IsValidSignature(jsonPayload, signatureHeader, webHookSecret))
        {
            // Reject requests with invalid signatures
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
        }

        // Deserialize JSON into a strongly-typed object (adjust fields to match WooCommerce's response)
        var orderTrackingData = JsonConvert.DeserializeObject<WooCommerceOrderTracking>(jsonPayload);

        // Add your business logic here: save to database, update order status, send notifications, etc.
        // Example: SaveTrackingInfoToDatabase(orderTrackingData);

        // Return 200 OK to confirm successful receipt (WooCommerce will stop retrying)
        return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
    }

    // Helper method to verify WooCommerce's webhook signature
    private bool IsValidSignature(string payload, string signatureHeader, string secret)
    {
        using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
        {
            var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
            var computedSignature = $"sha256={BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant()}";
            return computedSignature.Equals(signatureHeader, StringComparison.OrdinalIgnoreCase);
        }
    }

    // Strongly-typed class to map WooCommerce's order tracking data
    // Adjust fields based on the actual JSON structure from your WooCommerce webhook
    public class WooCommerceOrderTracking
    {
        public int id { get; set; }
        public string status { get; set; }
        public string tracking_number { get; set; }
        public string tracking_provider { get; set; }
        public int order_id { get; set; }
        // Add other fields you need (e.g., customer details, shipping info) based on WooCommerce's response
    }
}

Step 2: Configure Routing (If Needed)

The [Route("test")] attribute on the action already maps directly to your delivery URL, but if you prefer using traditional routing, you can add this to your RouteConfig.cs:

routes.MapRoute(
    name: "WooCommerceWebHook",
    url: "test",
    defaults: new { controller = "WooCommerceWebHook", action = "ReceiveOrderTracking" }
);

Step 3: Key Security Note - Signature Verification

WooCommerce includes an X-WC-Webhook-Signature header with every request, generated using your webhook secret. Never skip this verification—it ensures the request actually comes from your WooCommerce store, not a malicious actor. Make sure to replace YOUR_WOOCOMMERCE_WEBHOOK_SECRET with the secret you set when creating the webhook in WooCommerce.

Step 4: Test the Setup

  • Use Postman: Send a POST request to https://antiochiadoner.com/test with a JSON payload matching WooCommerce's order tracking structure, and include the X-WC-Webhook-Signature header (compute it using your secret to test validation).
  • WooCommerce Logs: Check WooCommerce's webhook logs (WooCommerce > Settings > Advanced > Webhooks > View Logs) to see if requests are being sent successfully. If there are errors, the logs will tell you why (e.g., invalid signature, timeout).

Additional Tips

  • Handle Large Payloads: If your orders have lots of data, ensure your MVC app is configured to accept larger request bodies (adjust maxRequestLength in web.config if needed).
  • Async Processing: If your business logic takes time (e.g., sending emails, updating external systems), offload it to a background task (like using Hangfire) so you can return a 200 OK quickly—WooCommerce will retry requests if it doesn't get a timely response.
  • HTTPS: Ensure your MVC site uses HTTPS (WooCommerce recommends this for webhook security, and many hosts enforce it now).

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

火山引擎 最新活动