How to authenticate calls to the Webhooks API and how to verify that a webhook delivery came from Paylocity.
Early Access (EA)This API is currently in Early Access and available only to approved EA participants. Do not rely on this version for production workloads unless explicitly authorized. If you have any feedback, please share with your designated Early Adoption program representative.
Overview
Paylocity Webhooks use two separate authentication methods depending on the direction of the request:
| Direction | Method | Used for |
|---|---|---|
| Your application → Paylocity | OAuth 2.0 bearer token | Calling the Webhooks API to create, view, update, or delete subscriptions and to read events |
| Paylocity → Your application | HMAC-SHA256 signature | Verifying that a webhook delivery came from Paylocity and was not modified |
Calling the Webhooks API (OAuth 2.0)
All Webhooks API endpoints require an OAuth 2.0 bearer token (JWT). Webhooks use the same OAuth 2.0 Client Credentials flow as other Paylocity APIs. See Authentication in API Basics for instructions on obtaining a token.
Include the token in the Authorization header of every request:
Authorization: Bearer YOUR_ACCESS_TOKENA missing or invalid token returns 401 Unauthorized.
The credentials you use also determine the environment. Sandbox credentials create and manage sandbox subscriptions. Production credentials create and manage production subscriptions.
Securing webhook deliveries (HMAC-SHA256)
When Paylocity sends a webhook to your endpoint, it signs the request with HMAC-SHA256. Your application recalculates the signature with the shared secret and compares it with the value sent by Paylocity.
Step 1: Create an HMAC-secured subscription
When you create the subscription, set auth.type to HMAC and provide a future expiration date in auth.hmac.key1.expirationAt.
{
"name": "Employee Updates - HMAC",
"eventTypes": ["employee.person.v1", "employee.assignment.v1"],
"url": "https://my-app.example.com/webhooks/paylocity",
"auth": {
"type": "HMAC",
"hmac": {
"key1": {
"expirationAt": "2027-01-01T00:00:00Z"
}
}
}
}Step 2: Save the HMAC secret
The 201 Created response includes the key details in auth.hmac.key1:
| Property | Type | Description |
|---|---|---|
keyId | string (UUID) | Unique identifier of the HMAC key. Appears in the x-pcty-signature header. |
secret | string | The base64-encoded HMAC secret. Returned only in the response that creates the key. |
issuedAt | string (date-time) | When the key was issued |
expirationAt | string (date-time) | When the key expires |
ImportantThe secret is returned only once. Store it securely, such as in a secrets manager. Later
GETrequests returnkeyId,issuedAt, andexpirationAt, but never the secret. If you lose the secret, add a new key (see Rotating HMAC keys) and store the new secret.
Step 3: Verify each delivery
Each delivery includes the following headers:
| Header | Description |
|---|---|
x-pcty-signature | The key ID and hex-encoded HMAC signature, in the format keyId={uuid}:signature={hex}. During key rotation, when more than one key is active, the header contains a comma-separated pair for each active key. |
x-pcty-timestamp | Unix timestamp, in seconds, when the delivery was signed |
Example header during key rotation:
x-pcty-signature: keyId=1b2c...:signature=9f86d0...,keyId=7e4a...:signature=4c1b2e...
The signature is calculated as:
hex( HMAC-SHA256( base64Decode(secret), "{timestamp}.{rawBody}" ) )
Verification process
- Read the
x-pcty-timestampheader. - Reject the request if the timestamp is more than 5 minutes (300 seconds) from your current time. This helps protect against replay attacks.
- Build the signed string:
{timestamp}.{rawBody}. Use the raw request body exactly as received (UTF-8). Do not parse and re-serialize the JSON. - Base64-decode your stored secret.
- Calculate the HMAC-SHA256 of the signed string with the decoded secret, and hex-encode the result (lowercase).
- Split
x-pcty-signatureon commas. For eachkeyId=...:signature=...pair, compare thesignaturevalue with your result using a constant-time comparison. - If any signature matches, accept the request. Otherwise, respond with
401.
Examples (Node.js / Python)
const crypto = require('crypto');
const express = require('express');
const app = express();
function verifyWebhookSignature(rawBody, base64Secret, sigHeader, tsHeader) {
if (!sigHeader || !tsHeader) return false;
const timestamp = parseInt(tsHeader, 10);
const now = Math.floor(Date.now() / 1000);
// Reject timestamps more than 5 minutes from now (replay protection)
if (Number.isNaN(timestamp) || Math.abs(now - timestamp) > 300) return false;
const computedHex = crypto
.createHmac('sha256', Buffer.from(base64Secret, 'base64'))
.update(`${timestamp}.${rawBody}`, 'utf8')
.digest('hex');
// One "keyId={uuid}:signature={hex}" pair per active key, comma-separated
return sigHeader.split(',').some((part) => {
const m = part.trim().match(/keyId=[^:]+:signature=([0-9a-f]+)/i);
if (!m) return false;
const a = Buffer.from(m[1].toLowerCase(), 'utf8');
const b = Buffer.from(computedHex, 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
});
}
// Use express.raw() so the body bytes are preserved exactly
app.post('/webhooks/paylocity', express.raw({ type: 'application/json' }), (req, res) => {
const rawBody = req.body.toString('utf8');
const valid = verifyWebhookSignature(
rawBody,
process.env.PAYLOCITY_WEBHOOK_SECRET,
req.headers['x-pcty-signature'],
req.headers['x-pcty-timestamp']
);
if (!valid) return res.status(401).json({ error: 'Invalid signature' });
const event = JSON.parse(rawBody);
console.log(`Received ${event.type} | id: ${event.id}`);
res.sendStatus(200);
});import base64, hashlib, hmac, json, os, time
from flask import Flask, request, abort
app = Flask(__name__)
def verify_webhook_signature(raw_body: bytes, base64_secret: str,
sig_header: str, ts_header: str) -> bool:
try:
timestamp = int(ts_header)
except (TypeError, ValueError):
return False
# Reject timestamps more than 5 minutes from now (replay protection)
if abs(time.time() - timestamp) > 300:
return False
string_to_sign = f"{timestamp}.{raw_body.decode('utf-8')}"
key = base64.b64decode(base64_secret)
computed = hmac.new(key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
# One "keyId={uuid}:signature={hex}" pair per active key, comma-separated
for entry in (sig_header or "").split(","):
parts = dict(item.split("=", 1) for item in entry.strip().split(":") if "=" in item)
if hmac.compare_digest(parts.get("signature", "").lower(), computed):
return True
return False
@app.route("/webhooks/paylocity", methods=["POST"])
def handle_webhook():
raw_body = request.get_data() # raw bytes, before any JSON parsing
if not verify_webhook_signature(
raw_body,
os.environ["PAYLOCITY_WEBHOOK_SECRET"],
request.headers.get("x-pcty-signature", ""),
request.headers.get("x-pcty-timestamp", ""),
):
abort(401)
event = json.loads(raw_body)
print(f"Received {event['type']} | id: {event['id']}")
return "", 200A C# example is available in the Create Subscription API reference.
Rotating HMAC keys
A subscription can have up to two keys: key1 (primary) and key2 (secondary, used for rotation). While both keys are active, each delivery is signed with both keys, so you can deploy the new secret before the old key expires without interrupting delivery.
Step 1: Add a second key. Use PATCH with op: add on /auth/hmac/key2:
curl -X PATCH "https://dc1demogwext.paylocity.com/apiHub/webhooks/v1/subscriptions/YOUR_SUBSCRIPTION_ID" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json-patch+json" \
-d '[
{ "op": "add", "path": "/auth/hmac/key2", "value": { "expirationAt": "2027-06-01T00:00:00Z" } }
]'Because this update changes authentication settings, Paylocity returns 200 OK with the resulting HMAC key details, including the secret for the newly created key. Store it immediately.
Step 2: Accept both secrets. Update your endpoint to accept a signature from either the old or the new secret.
Step 3: Retire the old key. Let the old key expire, or shorten its expiration with replace on /auth/hmac/key1/expirationAt.
Step 4: Clean up. Remove the old secret from your endpoint after the old key expires.
You can also replace the full authentication configuration in one operation with replace on /auth, keeping the existing key by its keyId:
[
{
"op": "replace",
"path": "/auth",
"value": {
"type": "HMAC",
"hmac": {
"key1": { "keyId": "EXISTING_KEY1_ID", "expirationAt": "2027-01-01T00:00:00Z" },
"key2": { "expirationAt": "2027-06-01T00:00:00Z" }
}
}
}
]If both HMAC keys on a subscription expire, we will stop delivering to that subscriber. We will only sign with keys that haven’t yet expired.
Security best practices
- Always use HTTPS for your callback URL.
- Always configure HMAC authentication on your subscriptions.
- Verify the signature before processing any payload.
- Use constant-time comparison to prevent timing attacks.
- Never log or commit the HMAC secret.
- Rotate keys before they expire.
- Track processed event
idvalues to ignore duplicates and replays. - Return
401for requests that fail verification.