# Rewards Webhook

![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0ahLW2WavtwcwNbSR9%2F-MTFzJJO9IrVkcbEctqO%2F-MTFzR4MRo0OVDrN8Ru1%2FProduct%20Flow%20Diagram%20-%20v2.0%20-%206.%20Reward%20webhook.jpg?alt=media\&token=71be85e9-bfa6-48c5-81fe-4dd2ee9bf2e5)

A webhook url can be provided to CustomerGlu to receive the rewards won by users in real-time

A POST request will be made to the specified Webhook URL . Example request body is as follows

```
{
        "campaignId": "xyz41c29-bb0d-4fe6-8260-1403d1c0e964",
        "type": "scratchcard",
//"direct","spinthewheel","slotmachine","memorygame","quiz",giftbox,...//
        "userId": "testuser1",
        "rewardId": "xyzbb3ca-093f-43f2-84ba-8d5ed0d6c1b4",
//rewardId will be unique and can be used as a de-duplication filter
        "rewardName": "200 Coins",
        "rewardAmount": 400 //optional
        "code": "CODE123"//optional
        "details": {//optional
            "userBName": "testuser2", //in case of a reward for a referral
            "userBId": "testuser2"//in case of a reward for a referral
            "userAName": "testuser0", //in case of a reward for a referral
            "userAId": "testuser0"//in case of a reward for a referral
            "rewardCategory": "RM",//custom attribute
            "currency":"USD"//custom attribute
        }
//details object can also contain any logic/business specific custom attributes which can be given as a campaign input//
}
```

***Optionally***,  to verify the authenticity of request,  a secret token  can be provided to CustomerGlu.&#x20;

When you set a token, you'll receive the `X-CG-SIGNATURE` header in the webhook `POST` request. value of this header will be a hmac hexdigest of the request body with the provided token. See on how to validate the requests

#### Validating Reward Webhook

{% tabs %}
{% tab title="JavaScript" %}

```
const verifySignature = (reqBodyDigest, cgHeader) => {
  return crypto.timingSafeEqual(Buffer.from(cgHeader), Buffer.from(`${reqBodyDigest}`));
}


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/hook', (req, res) => {
  const jsonString = JSON.stringify(req.body);
  const reqBodyDigest = crypto.createHmac('sha1', token)
    .update(jsonString)
    .digest('hex');
  const cgHeader = req.headers['x-cg-signature'];
  const verify = verifySignature(reqBodyDigest, cgHeader)
}
```

{% endtab %}

{% tab title="Python" %}

```
import hmac,hashlib,json

sampleObj = {"campaignId":"6bab1116-ae8e-4644-9cee-7a3d8ee9aff3","type":"direct","userId":"test-8-june-9","rewardId":"acdc71c6-08ad-4cd9-8c1e-3c812487b854","rewardName":"$15","rewardAmount":15,"details":{"currency":"USD","value":15,"reward_reason":"got_referred","userAName":"Test Solve 7","userAId":"test-8-june-7"}}
gluHeader="f2719895b483fbf3f98e1936bc88271cbe74f138"


def generateSignature(incomingBody):
  key="PbTJp694bmgrfJpJPQmrjGfjgq".encode('utf-8')
  incomingBodyString = json.dumps(incomingBody, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
  return hmac.new(key, incomingBodyString, hashlib.sha1).hexdigest()

def verifySignature(cgHeader,incomingBody):
    return hmac.compare_digest(cgHeader,generateSignature(incomingBody))
    
    
```

{% endtab %}

{% tab title="Java" %}
{% hint style="info" %}
**Note**:&#x20;

CustomerGlu requires the raw body of the request to perform signature verification. If you are using a framework/library, make sure it doesn't manipulate the raw body. Any manipulation to the raw body of the request will cause the verification to fail.
{% endhint %}

{% code overflow="wrap" %}

```java
private static String toHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }
    public static String calculateSHA1HMAC(String payload, String key)
            throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
        //
        String HMAC_SHA1_ALGORITHM = "HmacSHA1";
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return toHexString(mac.doFinal(payload.getBytes()));
    }
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}

```php
function verifySignature($apiSecret)
{
    $body = json_encode(file_get_contents('php://input')); // get json encoded body
    $hmac = hash_hmac('sha1', $body, $apiSecret); // Generate HMAC from body and shared secret
    $signature = $_SERVER['x-cg-signature'];  // Get signature from request header
    return $hmac == $signature; // compare request signature with generated signature. 
}
```

{% endtab %}
{% endtabs %}

### Webhook Payload Customization

You can define your own schema for the webhook payload. Below are the default keys that we will send as part of the payload. You can extend this with additional custom attributes as needed.

#### Default Keys

* `campaignId`, `type`, `rewardType`, `userId`, `rewardId`, `status`, `transactionId`, `rewardName`, `rewardAmount`, `body`, `rewardExpiry`, `tnc`, `code`,`details`.

#### How To Use

* Use the `$` symbol with Default Keys to access dynamic values, and static values can be accessed without the `$` symbol.

{% hint style="info" %}
Note: If you want to access nested payload values in the root, you can access them using the `dot` operator.
{% endhint %}

* Example Screenshots from CustomerGlu Dashboard > Dev Console > Reward Webhook.

<figure><img src="https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FhK7GFIDqhlXBQNVx62vP%2FScreenshot%202024-09-09%20at%201.39.21%E2%80%AFPM.png?alt=media&#x26;token=d83064ea-6702-4c0c-8c28-dc679999169b" alt="" width="563"><figcaption></figcaption></figure>

* Example Payload You Will Receive After Setting Up the Reward Webhook.

<figure><img src="https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2F7L2QjyEfmm0ra1tYbBXE%2FScreenshot%202024-09-09%20at%201.42.43%E2%80%AFPM.png?alt=media&#x26;token=2262e43c-f08a-43f7-af6b-98ebe0462872" alt="" width="563"><figcaption></figcaption></figure>

### Setting Up Reward Webhook from the Dashboard

{% embed url="<https://drive.google.com/file/d/1APw2_5FIyBfBVcdgvI_QzV6KmU-WYadE/view?usp=drive_link>" %}

#### Whitelisting CustomerGlu Webhook IPs

The following IP address(es) should be whitelisted by your Server, to receive Webhook requests from CustomerGlu:

`20.207.108.216`
