Created
April 20, 2022 22:29
-
-
Save SpaceboatDVLP/fff3be1af45b3725736bb29233de4c6e to your computer and use it in GitHub Desktop.
Verify a Square Webhook Signature in Vapor 4.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func validSquareSignature(req: Request) -> Bool { | |
guard let headerSignature: String = req.headers["x-square-signature"].first else { return false } | |
guard let urlData = "my webhook url".data(using: .utf8) else { return false } | |
guard let bodyData = req.body.string?.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\n", with: "").data(using: .utf8) else { return false } | |
let payload = urlData + bodyData | |
var hmac = HMAC<Insecure.SHA1>(key: SymmetricKey(data: EnvVars.squareSig.data(using: .utf8) ?? Data())) | |
hmac.update(data: payload) | |
let mac = Data(hmac.finalize()).base64EncodedString() | |
return mac == headerSignature; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment