> Agent-readable docs index: /llms.txt. Download /docs.zip to grep all markdown files locally.

---
title: "Webhook Handlers"
description: "Example webhook callback handlers for handling market purchase events."
icon: server
---

# Webhook Handlers

The following handlers validate the request signature and process a purchase
event.

## Handler Flow

<Steps>
  <Step title="Read request body" icon="braces">
    Parse the JSON payload sent by Neverlose.
  </Step>

  <Step title="Remove signature" icon="scissors">
    Keep the received signature aside before recomputing your own hash.
  </Step>

  <Step title="Compare hashes" icon="shield-check">
    Generate the expected signature from sorted fields and your secret key.
  </Step>

  <Step title="Process purchase" icon="shopping-bag">
    Use `username`, `item_id`, and `unique_id` after signature validation succeeds.
  </Step>
</Steps>

## Purchase Handler Examples

<Tabs items={["Python (bottle)", "Node.js (express)"]}>
  <Tab title="Python (bottle)">
    ```python
    #!/usr/bin/python3

    from bottle import run, request, post
    import bottle
    from decimal import Decimal
    from hashlib import sha256

    SECRET_KEY = "key"


    def market_api_sig_value(key, value):
        if key == "amount" and isinstance(value, float) and value.is_integer():
            return str(int(value))
        return str(value)


    def market_api_generate_signature(j, secret):
        str_to_hash = ("".join([i + market_api_sig_value(i, j[i]) for i in sorted(j)]) + secret).encode()
        hashed = sha256(str_to_hash).hexdigest()
        return hashed


    def market_api_validate_signature(j, secret):
        nl_sig = j["signature"]
        del j["signature"]
        our_sig = market_api_generate_signature(j, secret)
        return nl_sig == our_sig


    @post("/on_purchase")
    def on_purchase():
        data = request.json
        if not market_api_validate_signature(data, SECRET_KEY):
            return "invalid signature"
        res = data["username"] + " bought item https://neverlose.cc/market/item?id=" + data["item_id"]
        print(res, flush=True)
        return res


    app = application = bottle.Bottle()
    run(host='0.0.0.0', port=8080)
    ```
  </Tab>

  <Tab title="Node.js (express)">
    ```javascript
    const express = require('express')
    const app = express()
    const crypto = require("crypto")

    app.use(express.json())

    const secret_key = "key"

    const sort_obj = function(obj) {
      return Object.keys(obj).sort().reduce(function (result, key) {
        result[key] = obj[key]
        return result
      }, {})
    }

    const obj_to_string = function (obj) {
     obj = sort_obj(obj)
        let str = ''
        for (let p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += p + obj[p]
            }
        }
        return str
    }

    const market_api_generate_signature = function(j, secret){
        const str_to_hash = obj_to_string(j) + secret
        const hashed = crypto.createHash('sha256').update(str_to_hash).digest('hex')
        return hashed
    }

    const market_api_validate_signature = function(j, secret){
      const nl_sig = j["signature"]
      delete j["signature"]
      const our_sig = market_api_generate_signature(j, secret)
      return nl_sig === our_sig
    }

    app.post('/on_purchase', (req, res) => {
      if (!market_api_validate_signature(req.body, secret_key))
        return res.send("invalid signature")

      let response = req.body.username + " bought item https://neverlose.cc/market/item?id=" + req.body.item_id
      console.log(response)
      res.send(response)
    })

    app.listen(8080)
    ```
  </Tab>
</Tabs>

## Handler Checklist

<AccordionGroup>
  <Accordion title="Use raw event fields for signature validation" icon="fingerprint" defaultOpen>
    Validate the payload before normalizing names, parsing amounts, or storing the event.
  </Accordion>

  <Accordion title="Store processed unique ids" icon="database">
    Keep `unique_id` values you have already processed to avoid duplicate side effects.
  </Accordion>

  <Accordion title="Return quickly" icon="timer">
    Do expensive work asynchronously after signature validation when your service needs retries or queueing.
  </Accordion>
</AccordionGroup>
