Skip to content

Commit d0e625c

Browse files
Merge pull request #141 from PaystackOSS/docs/webhook-signing-secret
docs: add Paystack-Signature webhook verification snippet
2 parents e61444c + 6d6ee13 commit d0e625c

9 files changed

Lines changed: 252 additions & 16 deletions

File tree

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
const js = `const crypto = require('crypto');
2+
const express = require('express');
3+
4+
const TOLERANCE_SECONDS = 300;
5+
6+
// Returns the key id (kid) of the signature that matched, or null.
7+
function verifyPaystackSignature(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
8+
if (!Buffer.isBuffer(rawBody) || typeof header !== 'string') return null;
9+
10+
let t = null;
11+
const entries = [];
12+
for (const part of header.split(',')) {
13+
const i = part.indexOf('=');
14+
if (i === -1) continue;
15+
const key = part.slice(0, i).trim();
16+
const value = part.slice(i + 1).trim();
17+
if (key === 't') {
18+
if (t !== null || !/^[0-9]+$/.test(value)) return null;
19+
t = Number(value);
20+
} else if (key === 'v1') {
21+
const j = value.indexOf(':');
22+
if (j !== -1) entries.push({ kid: value.slice(0, j), hex: value.slice(j + 1) });
23+
}
24+
}
25+
if (t === null || entries.length === 0) return null;
26+
if (Math.abs(now - t) > TOLERANCE_SECONDS) return null;
27+
28+
for (const secret of secrets) {
29+
const expected = crypto.createHmac('sha512', secret).update(t + '.').update(rawBody).digest();
30+
for (const { kid, hex } of entries) {
31+
if (!/^[0-9a-f]{128}$/.test(hex)) continue;
32+
if (crypto.timingSafeEqual(expected, Buffer.from(hex, 'hex'))) return kid;
33+
}
34+
}
35+
return null;
36+
}
37+
38+
const app = express();
39+
40+
// express.raw keeps req.body as the exact bytes Paystack sent. Register this route before any
41+
// app.use(express.json()): a JSON parser that runs first consumes the body and every check fails.
42+
app.post('/my/webhook/url', express.raw({ type: 'application/json' }), (req, res) => {
43+
const secret = process.env.PAYSTACK_WEBHOOK_SECRET; // whsec_...
44+
if (!secret) return res.sendStatus(500);
45+
const kid = verifyPaystackSignature(req.body, req.get('paystack-signature'), [secret]);
46+
if (!kid) return res.sendStatus(401);
47+
48+
res.sendStatus(200);
49+
const event = JSON.parse(req.body.toString('utf8'));
50+
// Do something with event
51+
});`
52+
53+
const php = `<?php
54+
const PAYSTACK_TOLERANCE_SECONDS = 300;
55+
56+
// Returns the key id (kid) of the signature that matched, or null.
57+
function verifyPaystackSignature(string $rawBody, ?string $header, array $secrets, ?int $now = null): ?string
58+
{
59+
if ($header === null || $header === '') {
60+
return null;
61+
}
62+
63+
$t = null;
64+
$entries = [];
65+
foreach (explode(',', $header) as $part) {
66+
$pair = explode('=', $part, 2);
67+
if (count($pair) !== 2) {
68+
continue;
69+
}
70+
[$key, $value] = array_map('trim', $pair);
71+
if ($key === 't') {
72+
if ($t !== null || !preg_match('/^[0-9]+$/D', $value)) {
73+
return null;
74+
}
75+
$t = (int) $value;
76+
} elseif ($key === 'v1') {
77+
$kidAndHex = explode(':', $value, 2);
78+
if (count($kidAndHex) === 2) {
79+
$entries[] = $kidAndHex;
80+
}
81+
}
82+
}
83+
if ($t === null || count($entries) === 0) {
84+
return null;
85+
}
86+
$now = $now ?? time();
87+
if (abs($now - $t) > PAYSTACK_TOLERANCE_SECONDS) {
88+
return null;
89+
}
90+
91+
foreach ($secrets as $secret) {
92+
$expected = hash_hmac('sha512', $t . '.' . $rawBody, $secret);
93+
foreach ($entries as [$kid, $hex]) {
94+
if (preg_match('/^[0-9a-f]{128}$/D', $hex) && hash_equals($expected, $hex)) {
95+
return $kid;
96+
}
97+
}
98+
}
99+
return null;
100+
}
101+
102+
$rawBody = file_get_contents('php://input'); // the exact bytes Paystack sent
103+
$secret = getenv('PAYSTACK_WEBHOOK_SECRET'); // whsec_...
104+
$header = $_SERVER['HTTP_PAYSTACK_SIGNATURE'] ?? null;
105+
106+
if (!$secret || verifyPaystackSignature($rawBody, $header, [$secret]) === null) {
107+
http_response_code(401);
108+
exit;
109+
}
110+
111+
http_response_code(200);
112+
$event = json_decode($rawBody, true);
113+
// Do something - that will not take long - with $event`
114+
115+
export {js, php}

‎dist/doc/payments/webhooks/verifying-transaction.js‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ app.use(express.json({
99
1010
app.post("/my/webhook/url", function(req, res) {
1111
//validate event
12-
const hash = crypto.createHmac('sha512', secret).update(req.rawBody).digest('hex');
13-
if (hash == req.headers['x-paystack-signature']) {
12+
const hash = crypto.createHmac('sha512', secret).update(req.rawBody).digest();
13+
const signature = req.headers['x-paystack-signature'] || '';
14+
if (!/^[0-9a-f]{128}$/.test(signature) || !crypto.timingSafeEqual(hash, Buffer.from(signature, 'hex'))) {
15+
return res.sendStatus(401);
16+
}
1417
// Retrieve the request's body
1518
const event = req.body;
16-
// Do something with event
17-
}
18-
res.send(200);
19+
// Do something with event
20+
res.sendStatus(200);
1921
});`
2022

2123
const php = `<?php
@@ -28,7 +30,7 @@ const php = `<?php
2830
define('PAYSTACK_SECRET_KEY','SECRET_KEY');
2931
3032
// validate event do all at once to avoid timing attack
31-
if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
33+
if(!hash_equals(hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY), $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']))
3234
exit();
3335
3436
http_response_code(200);
@@ -44,6 +46,7 @@ const java = `package hmacexample;
4446
4547
import java.io.UnsupportedEncodingException;
4648
import java.security.InvalidKeyException;
49+
import java.security.MessageDigest;
4750
import java.security.NoSuchAlgorithmException;
4851
import javax.crypto.Mac;
4952
import javax.crypto.spec.SecretKeySpec;
@@ -71,7 +74,7 @@ public class HMacExample {
7174
byte [] mac_data = sha512_HMAC.
7275
doFinal(body.getBytes("UTF-8"));
7376
result = DatatypeConverter.printHexBinary(mac_data);
74-
if(result.toLowerCase().equals(xpaystackSignature)) {
77+
if(MessageDigest.isEqual(result.toLowerCase().getBytes("UTF-8"), xpaystackSignature.getBytes("UTF-8"))) {
7578
// you can trust the event, it came from paystack
7679
// respond with the http 200 response immediately before attempting to process the response
7780
//retrieve the request body, and deliver value to the customer
@@ -106,7 +109,7 @@ namespace HMacExample
106109
107110
String xpaystackSignature = ""; //put in the request's header value for x-paystack-signature
108111
109-
if(result.ToLower().Equals(xpaystackSignature)) {
112+
if(CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(result.ToLower()), Encoding.UTF8.GetBytes(xpaystackSignature))) {
110113
// you can trust the event, it came from paystack
111114
// respond with the http 200 response immediately before attempting to process the response
112115
//retrieve the request body, and deliver value to the customer
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
languages:
2+
- js
3+
- php
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const crypto = require('crypto');
2+
const express = require('express');
3+
4+
const TOLERANCE_SECONDS = 300;
5+
6+
// Returns the key id (kid) of the signature that matched, or null.
7+
function verifyPaystackSignature(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
8+
if (!Buffer.isBuffer(rawBody) || typeof header !== 'string') return null;
9+
10+
let t = null;
11+
const entries = [];
12+
for (const part of header.split(',')) {
13+
const i = part.indexOf('=');
14+
if (i === -1) continue;
15+
const key = part.slice(0, i).trim();
16+
const value = part.slice(i + 1).trim();
17+
if (key === 't') {
18+
if (t !== null || !/^[0-9]+$/.test(value)) return null;
19+
t = Number(value);
20+
} else if (key === 'v1') {
21+
const j = value.indexOf(':');
22+
if (j !== -1) entries.push({ kid: value.slice(0, j), hex: value.slice(j + 1) });
23+
}
24+
}
25+
if (t === null || entries.length === 0) return null;
26+
if (Math.abs(now - t) > TOLERANCE_SECONDS) return null;
27+
28+
for (const secret of secrets) {
29+
const expected = crypto.createHmac('sha512', secret).update(t + '.').update(rawBody).digest();
30+
for (const { kid, hex } of entries) {
31+
if (!/^[0-9a-f]{128}$/.test(hex)) continue;
32+
if (crypto.timingSafeEqual(expected, Buffer.from(hex, 'hex'))) return kid;
33+
}
34+
}
35+
return null;
36+
}
37+
38+
const app = express();
39+
40+
// express.raw keeps req.body as the exact bytes Paystack sent. Register this route before any
41+
// app.use(express.json()): a JSON parser that runs first consumes the body and every check fails.
42+
app.post('/my/webhook/url', express.raw({ type: 'application/json' }), (req, res) => {
43+
const secret = process.env.PAYSTACK_WEBHOOK_SECRET; // whsec_...
44+
if (!secret) return res.sendStatus(500);
45+
const kid = verifyPaystackSignature(req.body, req.get('paystack-signature'), [secret]);
46+
if (!kid) return res.sendStatus(401);
47+
48+
res.sendStatus(200);
49+
const event = JSON.parse(req.body.toString('utf8'));
50+
// Do something with event
51+
});
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
const PAYSTACK_TOLERANCE_SECONDS = 300;
3+
4+
// Returns the key id (kid) of the signature that matched, or null.
5+
function verifyPaystackSignature(string $rawBody, ?string $header, array $secrets, ?int $now = null): ?string
6+
{
7+
if ($header === null || $header === '') {
8+
return null;
9+
}
10+
11+
$t = null;
12+
$entries = [];
13+
foreach (explode(',', $header) as $part) {
14+
$pair = explode('=', $part, 2);
15+
if (count($pair) !== 2) {
16+
continue;
17+
}
18+
[$key, $value] = array_map('trim', $pair);
19+
if ($key === 't') {
20+
if ($t !== null || !preg_match('/^[0-9]+$/D', $value)) {
21+
return null;
22+
}
23+
$t = (int) $value;
24+
} elseif ($key === 'v1') {
25+
$kidAndHex = explode(':', $value, 2);
26+
if (count($kidAndHex) === 2) {
27+
$entries[] = $kidAndHex;
28+
}
29+
}
30+
}
31+
if ($t === null || count($entries) === 0) {
32+
return null;
33+
}
34+
$now = $now ?? time();
35+
if (abs($now - $t) > PAYSTACK_TOLERANCE_SECONDS) {
36+
return null;
37+
}
38+
39+
foreach ($secrets as $secret) {
40+
$expected = hash_hmac('sha512', $t . '.' . $rawBody, $secret);
41+
foreach ($entries as [$kid, $hex]) {
42+
if (preg_match('/^[0-9a-f]{128}$/D', $hex) && hash_equals($expected, $hex)) {
43+
return $kid;
44+
}
45+
}
46+
}
47+
return null;
48+
}
49+
50+
$rawBody = file_get_contents('php://input'); // the exact bytes Paystack sent
51+
$secret = getenv('PAYSTACK_WEBHOOK_SECRET'); // whsec_...
52+
$header = $_SERVER['HTTP_PAYSTACK_SIGNATURE'] ?? null;
53+
54+
if (!$secret || verifyPaystackSignature($rawBody, $header, [$secret]) === null) {
55+
http_response_code(401);
56+
exit;
57+
}
58+
59+
http_response_code(200);
60+
$event = json_decode($rawBody, true);
61+
// Do something - that will not take long - with $event

‎src/doc/payments/webhooks/verifying-transaction/index.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ static void Main(string[] args) {
2323

2424
String xpaystackSignature = ""; //put in the request's header value for x-paystack-signature
2525

26-
if(result.ToLower().Equals(xpaystackSignature)) {
26+
if(CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(result.ToLower()), Encoding.UTF8.GetBytes(xpaystackSignature))) {
2727
// you can trust the event, it came from paystack
2828
// respond with the http 200 response immediately before attempting to process the response
2929
//retrieve the request body, and deliver value to the customer

‎src/doc/payments/webhooks/verifying-transaction/index.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.io.UnsupportedEncodingException;
44
import java.security.InvalidKeyException;
5+
import java.security.MessageDigest;
56
import java.security.NoSuchAlgorithmException;
67
import javax.crypto.Mac;
78
import javax.crypto.spec.SecretKeySpec;
@@ -29,7 +30,7 @@ public static void main(String[] args) throws UnsupportedEncodingException, Inva
2930
byte [] mac_data = sha512_HMAC.
3031
doFinal(body.getBytes("UTF-8"));
3132
result = DatatypeConverter.printHexBinary(mac_data);
32-
if(result.toLowerCase().equals(xpaystackSignature)) {
33+
if(MessageDigest.isEqual(result.toLowerCase().getBytes("UTF-8"), xpaystackSignature.getBytes("UTF-8"))) {
3334
// you can trust the event, it came from paystack
3435
// respond with the http 200 response immediately before attempting to process the response
3536
//retrieve the request body, and deliver value to the customer

‎src/doc/payments/webhooks/verifying-transaction/index.js‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ app.use(express.json({
99

1010
app.post("/my/webhook/url", function(req, res) {
1111
//validate event
12-
const hash = crypto.createHmac('sha512', secret).update(req.rawBody).digest('hex');
13-
if (hash == req.headers['x-paystack-signature']) {
12+
const hash = crypto.createHmac('sha512', secret).update(req.rawBody).digest();
13+
const signature = req.headers['x-paystack-signature'] || '';
14+
if (!/^[0-9a-f]{128}$/.test(signature) || !crypto.timingSafeEqual(hash, Buffer.from(signature, 'hex'))) {
15+
return res.sendStatus(401);
16+
}
1417
// Retrieve the request's body
1518
const event = req.body;
16-
// Do something with event
17-
}
18-
res.send(200);
19+
// Do something with event
20+
res.sendStatus(200);
1921
});

‎src/doc/payments/webhooks/verifying-transaction/index.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
define('PAYSTACK_SECRET_KEY','SECRET_KEY');
99

1010
// validate event do all at once to avoid timing attack
11-
if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
11+
if(!hash_equals(hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY), $_SERVER['HTTP_X_PAYSTACK_SIGNATURE']))
1212
exit();
1313

1414
http_response_code(200);

0 commit comments

Comments
 (0)