We just finished a big upgrade. We upgraded our appservices to .NET 5 and we updated our
square version, and the square API’S which pushed us to use the WebHook V2. We have everything working except the HMAC-SHA1 signature part. I’ve used an HMAC SHA1 generator and tested a simple example and I was able to match that result with my result successfully. I’m thinking the problem is I’m using a different square signature key than you guys or my request body is being parsed differently than yours. Is there any c# examples? Any help would be greatly appreciated.
We don’t have an public example however we’ve used the following.
This readBody function:
public async Task<string> readBody(HttpRequest request)
{
var stream = Request.Body;
string combined = "";
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string value = await reader.ReadToEndAsync();
combined = "webhook_url_here" + value;
}
return combined;
}
Then code that uses it and the signature:
public async Task<IActionResult> Index()
{
var signature = Request.Headers["x-square-signature"];
var body = await readBody(Request);
string signatureKey = "signature_key_here";
byte[] secret = Encoding.UTF8.GetBytes(signatureKey);
HMACSHA1 hmac = new HMACSHA1(secret);
var payloadBytes = Encoding.UTF8.GetBytes(body);
byte[] hash = hmac.ComputeHash(payloadBytes);
String hashString = Convert.ToBase64String(hash);
if (hashString.Equals(signature)) {
Console.WriteLine(true);
} else {
Console.WriteLine(false);
}
return View();
}
You will received a webhook and it prints out true
.
1 Like
great. I’ll try using this and re-test. thx
got it working. thx for the sample code.
That’s fantastic! Please feel free to reach out if you have any additional questions.