Upon integrating the smart button of Paypal I have issues to verify webhook notifications sent by Paypal. The examples I have found are either outdated or do not work.
Is there a way to verify the webhook notifications, ideally in a DIY way (ie. without having to use the bulky and complex Paypal API)?
4
Answers
To the best of my knowledge, this code is only one that actually works. All other examples I have found on stack overflow will not work because instead of passing the ID of the webhook itself when composing the signature string, they use the ID of the webhook event, thus the verify will fail.
The webhook ID will be generated once you add the webhook in the developer backend of Paypal. After creation of the webhook you will see its id in the list of installed webhooks.
The rest is pretty straight forward: We get the headers and the HTTP body and compose the signature using Paypal's recipe:
"These items" are: The transmission id, the transmission date, the webhook id and a CRC over the HTTP body. The first two can be found in the header of the request, the webhook id in the developer backend (of course, that id will never change), the CRC is calculated like shown below.
The certificate's location is in the header, too, so we load it and extract the private key.
Last thing to watch out for: The name of the algorithm provided by Paypal (again in a header field) is not exactly the same as understood by PHP. Paypal calls it "sha256WithRSA" but
openssl_verify
will expect "sha256WithRSAEncryption".Responding to this to save potential headaches but the above example does not work because an authentication token is needed to be sent along with your get request for the cert file "
file_get_contents($header['Paypal-Cert-Url'])
" will not work on its own.Simply include your authentication token in the header and it’ll work.
Answering this for nodejs, as there are subtle security issues and some missing logic in original (but very helpful) answer. This answer addresses the following issues:
but NodeJS < 17.0 can’t do this easily AFAICT. The trust model relies on TLS and the built in nodejs trust chain for the cert fetch URL and not the returned cert from cert URL , which is probably good enough.
You can use the following steps with Paypal API’s
Implementation PayPal API’s
https://www.postman.com/paypal/workspace/paypal-public-api-workspace/collection/19024122-92a85d0e-51e7-47da-9f83-c45dcb1cdf24?action=share&creator=22959279
4.Use the webhook Id, Access Token, and request Headers to verify the Webhook