{"templateId":"markdown","versions":[{"version":"shipengine","label":"ShipStation API (formerly ShipEngine)","link":"/apis/shipengine/docs/guides/webhooks-validation","default":false,"active":false,"folderId":"58c9a61d"},{"version":"shipstation-v2","label":"ShipStation V2 API","link":"/apis/docs/guides/webhooks-validation","default":true,"active":true,"folderId":"58c9a61d"},{"version":"shipstation-v1","label":"ShipStation V1 API","link":"/apis/shipstation-v1/docs/guides/webhooks-validation","default":false,"active":false,"folderId":"58c9a61d"}],"sharedDataIds":{"sidebar":"sidebar-apis/@shipengine/sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["admonition"]},"type":"markdown"},"seo":{"title":"Webhook Validation","keywords":"shipping, labels, shipstation, documentation, api","siteUrl":"https://docs.shipstation.com","lang":"en-US","llmstxt":{"hide":false,"title":"ShipStation API LLM Docs","description":"Find links and references to all markdown documentation for use with LLMs","excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"webhook-validation","__idx":0},"children":["Webhook Validation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["ShipStation includes a digital signature (RSA-SHA256) in all outgoing webhooks."," ","This allows you to ensure requests received at your webhook URL were sent from"," ","our systems."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["We have a ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"#complete-example"},"children":["full code example"]}," below that demonstrates all the steps."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"validation-process","__idx":1},"children":["Validation Process"]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"step-1-extract-the-signature-headers","__idx":2},"children":["Step 1: Extract the Signature Headers"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Extract the three signature headers from the incoming webhook request:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-rsa-sha256-key-id"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-rsa-sha256-signature"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-timestamp"]}]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["If these headers are not present, you should respond with an HTTP status ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["404"]}," ","and stop processing the request. This can help hide the existence of your"," ","webhook endpoint from anyone attempting to impersonate our service."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"step-2-validate-the-timestamp","__idx":3},"children":["Step 2: Validate the Timestamp"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Verify that the timestamp in the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-timestamp"]}," header is recent,"," ","in order to prevent replay attacks. Use your judgement on the age of webhooks"," ","you are willing to accept. Note that because of different server time skews, you may"," ","receive webhooks with timestamps in the future, so your code should account for that."," ","If the timestamp header is more than 5 minutes difference from the current"," ","time, you may want to respond with an HTTP status ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["400"]}," and stop processing the request."," ","If you encounter a lot of these rejections, you may want to double-check your server clocks, or"," ","increase the time range."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"step-3-get-the-raw-request-body","__idx":4},"children":["Step 3: Get the Raw Request Body"]},{"$$mdtype":"Tag","name":"Admonition","attributes":{"type":"warning","name":"Important"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["You must use the raw, unparsed request body exactly as received."," ","Do not parse the JSON first and then re-serialize it, as this may change whitespace,"," ","property ordering, or encoding, which will cause signature verification to fail."," ","Ensure your web server framework provides access to the unparsed body."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"step-4-retrieve-the-public-key","__idx":5},"children":["Step 4: Retrieve the Public Key"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Fetch the JSON Web Key Set (JWKS) from our public endpoint: ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["https://api.shipengine.com/jwks"]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The JWKS endpoint returns a standard ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://tools.ietf.org/html/rfc7517"},"children":["RFC 7517"]}," JSON Web Key Set containing our public keys. Find the key in the JWKS whose ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["kid"]}," (key ID) matches the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-rsa-sha256-key-id"]}," header value."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The set of keys does not change very often, so it is generally safe to cache"," ","the JWKS response for a long period of time. If you receive a webhook request"," ","with a ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["x-shipengine-rsa-sha256-key-id"]}," value that is not in your cached copy,"," ","you should fetch the latest JWKS. The response includes an ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["ETag"]}," header, which"," ","you can pass in subsequent requests via the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/If-None-Match"},"children":["If-None-Match"]}," ","header. If the contents hasn't changed, our JWKS endpoint will respond with status 304."," ","If it responds with a status 200, it means the JWKS has changed, has a new ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["ETag"]},","," ","and you should update your cache."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["ShipStation may periodically rotate our signing keys. As long as you follow"," ","these guidelines related to fetching the JWKS, you should not have any service"," ","interruption. A public key  will always be present in the JWKS before"," ","we start using it for signing outgoing requests."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":3,"id":"step-5-verify-the-signature","__idx":6},"children":["Step 5: Verify the Signature"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To verify the signature, you must first construct the ",{"$$mdtype":"Tag","name":"em","attributes":{},"children":["signed payload"]},". This is"," ","the value that was hashed using our private key to produce the signature."," ","The signed payload is constructed by concatenating the value from the timestamp"," ","header, a literal period (",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["."]},"), followed by the raw request body."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Example:"]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"header":{"controls":{"copy":{}}},"source":"2025-10-02T04:51:00Z.{\"resource_url\":\"https://api.shipstation.com/example\",\"resource_type\":\"EXAMPLE\"}\n"},"children":[]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Use an RSA SHA-256 validation function on this signed payload, along with the"," ","public key from the previous step, to verify the signature."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["If the signature validation fails, you should respond with an HTTP status ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["401"]},","," ","and discard the payload without any further processing."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"complete-example","__idx":7},"children":["Complete Example"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["We've included a full working example of a NodeJS server that receives and"," ","validates webhooks, so that you can use it as a reference in your own implementation."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const crypto = require('crypto');\n\n// Cache for JWKS (in production, use a proper caching mechanism)\nlet jwksCache = null;\nlet jwksCacheETag = null;\n\nclass MissingHeadersError extends Error {}\nclass TimestampError extends Error {}\nclass SignatureError extends Error {}\n\n/**\n * Validates webhook signature\n * @throws {MissingHeadersError} When required headers are missing (should return 404)\n * @throws {TimestampError} When timestamp is out of range (should return 400)\n * @throws {SignatureError} When signature validation fails (should return 401)\n */\nasync function validateWebhookSignature(headers, rawBody) {\n  const keyId = headers['x-shipengine-rsa-sha256-key-id'];\n  const signature = headers['x-shipengine-rsa-sha256-signature'];\n  const timestamp = headers['x-shipengine-timestamp'];\n\n  if (!keyId || !signature || !timestamp) {\n    throw new MissingHeadersError('Missing required signature headers');\n  }\n\n  // Validate timestamp (5 minute window)\n  const webhookTime = new Date(timestamp);\n  const now = new Date();\n  const ageMinutes = (now - webhookTime) / 1000 / 60;\n\n  if (Math.abs(ageMinutes) > 5) {\n    throw new TimestampError(`Webhook timestamp too old or too far in future: ${ageMinutes} minutes`);\n  }\n\n  // Get public key\n  const publicKey = await getPublicKey(keyId);\n  if (!publicKey) {\n    throw new SignatureError(`Public key not found for kid: ${keyId}`);\n  }\n\n  // Construct signed payload\n  const signedPayload = `${timestamp}.${rawBody}`;\n\n  // Verify signature\n  const verify = crypto.createVerify('RSA-SHA256');\n  verify.update(signedPayload, 'utf8');\n  verify.end();\n\n  const isValid = verify.verify(\n    publicKey,\n    signature,\n    'base64'\n  );\n\n  if (!isValid) {\n    throw new SignatureError('Invalid webhook signature');\n  }\n\n  return true;\n}\n\n\n/**\n * Gets public key for a given key ID\n * Handles caching and automatic refresh if key not found\n * @returns Public key object or null if not found\n */\nasync function getPublicKey(keyId) {\n  // Try to find in cached JWKS\n  if (jwksCache) {\n    const jwk = jwksCache.keys.find(k => k.kid === keyId);\n    if (jwk) {\n      return jwkToPem(jwk);\n    }\n  }\n\n  // Key not found in cache, fetch fresh JWKS\n  const jwks = await fetchJWKS();\n  const jwk = jwks.keys.find(k => k.kid === keyId);\n\n  if (!jwk) {\n    return null; // Key not found\n  }\n\n  return jwkToPem(jwk);\n}\n\n/**\n * Fetches the JWKS from ShipEngine\n */\nasync function fetchJWKS() {\n  const headers = {};\n  if (jwksCacheETag) {\n    headers['If-None-Match'] = jwksCacheETag;\n  }\n\n  const response = await fetch('https://api.shipengine.com/jwks', {\n    method: 'GET',\n    headers\n  });\n\n  if (response.status === 304 && jwksCache) {\n    // Not modified, use cache\n    return jwksCache;\n  }\n\n  if (!response.ok) {\n    throw new Error(`Failed to fetch JWKS: ${response.status}`);\n  }\n\n  jwksCache = await response.json();\n  jwksCacheETag = response.headers.get('etag');\n\n  return jwksCache;\n}\n\n/**\n * Converts JWK to PEM format public key\n */\nfunction jwkToPem(jwk) {\n  const modulus = Buffer.from(jwk.n, 'base64');\n  const exponent = Buffer.from(jwk.e, 'base64');\n\n  // Create public key from modulus and exponent\n  const key = crypto.createPublicKey({\n    key: {\n      kty: 'RSA',\n      n: jwk.n,\n      e: jwk.e\n    },\n    format: 'jwk'\n  });\n\n  return key;\n}\n\n// Express.js middleware example\nfunction webhookValidationMiddleware(req, res, next) {\n  // Capture raw body\n  let rawBody = '';\n\n  req.on('data', (chunk) => {\n    rawBody += chunk.toString('utf8');\n  });\n\n  req.on('end', async () => {\n    try {\n      await validateWebhookSignature(req.headers, rawBody);\n      req.body = JSON.parse(rawBody); // Now safe to parse\n      next();\n    } catch (error) {\n      console.error('Webhook validation failed:', error.message);\n\n      if (error instanceof MissingHeadersError) {\n        res.status(404).send();\n      } else if (error instanceof TimestampError) {\n        res.status(400).json({ error: error.message });\n      } else if (error instanceof SignatureError) {\n        res.status(401).json({ error: 'Invalid webhook signature' });\n      } else {\n        res.status(500).json({ error: 'Internal server error' });\n      }\n    }\n  });\n}\n\nconst express = require('express');\nconst app = express();\napp.post('/webhook', webhookValidationMiddleware, (req, res) => {\n  // Process validated webhook\n  console.log('Validated webhook:', req.body);\n  res.status(200).send('OK');\n});\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Webhook server listening on port ${PORT}`);\n});\n\n\n// How to run:\n// 1. Save this entire code block into a file named server.js\n// 2. npm install --save express\n// 3. npm start\n","lang":"javascript"},"children":[]}]},"headings":[{"value":"Webhook Validation","id":"webhook-validation","depth":1},{"value":"Validation Process","id":"validation-process","depth":2},{"value":"Step 1: Extract the Signature Headers","id":"step-1-extract-the-signature-headers","depth":3},{"value":"Step 2: Validate the Timestamp","id":"step-2-validate-the-timestamp","depth":3},{"value":"Step 3: Get the Raw Request Body","id":"step-3-get-the-raw-request-body","depth":3},{"value":"Step 4: Retrieve the Public Key","id":"step-4-retrieve-the-public-key","depth":3},{"value":"Step 5: Verify the Signature","id":"step-5-verify-the-signature","depth":3},{"value":"Complete Example","id":"complete-example","depth":2}],"frontmatter":{"seo":{"title":"Webhook Validation"}},"lastModified":"2026-09-18T22:56:23.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/apis/docs/guides/webhooks-validation","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}