# Examples

## Example 1: Webhooks

Below is a **Node.js + Express** example of what the code for your webhook endpoint could look like:

```javascript
//Your webhooks payload endpoint
app.post("/your/webhook/payload-url", function(req, res) {
  const body = req.body;
  
  try {
    if (body.event === 'PARTICIPANT_REACHED_A_GOAL') {
      // Write code here to do something when a participant wins a reward
      console.log(`${body.data.participant.email} just won this reward: ${body.data.reward.description}`);

      // If the reward is approved
      if (body.data && body.data.reward && body.data.reward.approved) {
        // Do something
      }
      
      // If this is a double-sided reward, use body.data.reward.isReferrer to determine if this is for the referrer or referred person
      if (body.data && body.data.reward && body.data.reward.isReferrer) {
        // Do something
        
        // Optional: If you set metadata on the CampaignReward object, you can reference it:
        if (body.data.reward.metadata && body.data.reward.metadata["proRewardValue"]) {
            console.log(`${body.data.participant.email} earned an amount of ${body.data.reward.metadata["proRewardValue"]}.`);
        }
      }
      
      // Optional: If this is the referrer that unlocked the reward, you can get the details of the person that they referred
      if (body.data.reward.isReferrer && body.data.participant.referee) {
          console.log(`${body.data.participant.referee.email} was the person referred by ${body.data.participant.email}.`);
      }      

    } else if (body.event === 'NEW_PARTICIPANT_ADDED') {
      // Write code here to do something when a new participant is added    
      console.log(`${body.data.email} just joined via source: ${body.data.referralSource}.`);
            
    } else if (body.event === 'CAMPAIGN_ENDED') {
      // Write code here to do something when a program ends
      console.log(`${body.data.name} just ended with ${body.data.referralCount} total referrals!`);
            
    }
  
  } catch (err) {
    res.status(400).end();
  }
  res.json({received: true});
});
```

{% hint style="info" %}
**Helpful tips:**

* To see the different sample data from webhook request payloads, see [Events](/developer-tools/webhooks/events-reference.md)
* If you reference [reward metadata](https://docs.growsurf.com/developer-tools/webhooks/events-reference#campaign_ended) in your *New Participant Reward* events, your marketing team can update these values anytime in the future from the Program Editor without getting developers involved.
  {% endhint %}

## Example 2: Webhooks (with secret)

Below is a **Node.js + Express** example (using the [crypto-js](https://github.com/brix/crypto-js) library) of what the code for your webhook endpoint could look like:

```javascript
//Your webhooks payload endpoint
app.post("/your/webhook/payload-url", function(req, res) {
  const body = req.body;
  const signature = req.get("GrowSurf-Signature");
  
  try {
    // Validate the signature
    validateSignature(body, signature);
  
    // Do work!.....
    // Write your code in here...  
  
  } catch (err) {
    res.status(400).end();
  }
  res.json({received: true});
});

/**
 * Compares the GrowSurf header provided signature against the expected
 * signature.
 *
 * @param {Object} body the request body provided by GrowSurf
 * @param {String} signature the signature hash value provided within the header of the request
 * @returns {Boolean} valid true if the expected matches the given
 * @throws {Exception} thrown if the expected signature value does not match the given
 */
const validateSignature = function(body, signature) {
  // Extract
  let parts = signature.split(",");
  // t value
  let timestamp = parts[0].split("=")[1];
  // v value
  let hash = parts[1].split("=")[1];
  // Generate hash
  let message = (timestamp + "." + JSON.stringify(body));
  let expected = CryptoJS.HmacSHA256(message, "YOUR-SECRET-TOKEN").toString();

  // Validate/Compare
  if(expected === hash) {
    return true;
  } else {
    throw new Error("Invalid Signature");
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.growsurf.com/developer-tools/webhooks/examples.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
