# Webhook twitch start

**URL:** <https://discuss.dev.twitch.com/t/webhook-twitch-start/21010>\
**Category:** API\
**Created:** [April 27, 2019, 1:02am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010 "2019-04-27T01:02:53Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![Wed](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/wed/32/6246_2.png) [@Wed](https://discuss.dev.twitch.com/u/Wed)\
**Post date:** [April 27, 2019, 1:02am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/1 "2019-04-27T01:02:53Z")

</div>

Hello, trying to make my first application using twitch webhook. Made sure that my application gives 202, then I got confused. I understand that this is not the final answer with the data, you need to send something else, here the question arises, what exactly and how to organize it? Please tell me how to implement it. Thanks.

```
const request = require('request');
const express = require("express");
const server = express();
const options = {
    url: 'https://api.twitch.tv/helix/webhooks/hub',
    method: 'POST',
    headers: {
      'Client-ID': ' ***************',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        'hub.mode':'subscribe',
         'hub.topic':'https://api.twitch.tv/helix/users/follows?first=1&to_id=117191228',
        'hub.callback':'http://localhost',
        'hub.lease_seconds':'864000',
        'hub.secret':' *************'
      })
  };

request.post(options, function (error, response, body) {

  console.error('error:', error); 
  console.log('statusCode:', response && response.statusCode); 
  console.log('body:', JSON.stringify(body));
});
```

---

<div class="post-metadata">

**Author:** ![Dist](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/dist/32/7192_2.png) [@Dist](https://discuss.dev.twitch.com/u/Dist)\
**Post date:** [April 27, 2019, 9:58am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/2 "2019-04-27T09:58:46Z")

</div>

You can’t use `http://localhost` as a callback, you need to use an address that is internet accessible and has a web server running that will listen for the GET and POST messages sent by Twitch.

Once you send the subscription request to Twitch, they will then send a GET request to your callback (and since you’re using localhost, you’ll never receive it as that’s not reachable by Twitch) at which point you need a web server running to listen for that request and respond with the `hub.challenge` contained in the request.

After you respond to that challenge the webhook subscription should be created, and you will be sent POST requests to your callback which contain the notifications about the topic you requested.

---

<div class="post-metadata">

**Author:** ![Wed](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/wed/32/6246_2.png) [@Wed](https://discuss.dev.twitch.com/u/Wed)\
**Post date:** [April 27, 2019, 4:03pm UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/3 "2019-04-27T16:03:04Z")

</div>

Thank you, I think I’m beginning to understand. I do not know js so I decided to try to do it in php. Took a few steps.

1. There’s a twitch file.webhook.php that sends the request. In response to the received code 202.

```auto
<?php
    $client_id = ' ***************************';
    $mode = 'subscribe';
    $callback_url = 'http://mysite.com/twitch/twitch.notifications.php';
    $target_user_id = '117191228';

    $lease_days = '10';

    $lease_seconds = $lease_days * 24 * 60 * 60;

    $subscribe_to_event_url = 'https://api.twitch.tv/helix/webhooks/hub';

    $data = array(

    'hub.mode' => $mode,

    'hub.topic' => 'https://api.twitch.tv/helix/users/follows?first=1&from_id='.$target_user_id,

    'hub.callback' => $callback_url,

    'hub.lease_seconds' => $lease_seconds

    );

    $data_string = json_encode($data);

    $ch = curl_init($subscribe_to_event_url);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(

    'Content-Type: application/json',

    'Content-Length:'.strlen($data_string),

    'Client-ID: '.$client_id

    ));

    $result = curl_exec($ch);

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    echo $httpcode."

    ".$result; 

```

1. What I did is the twitch file.notifications.php containing script

```auto
header("Access-Control-Allow-Headers:*");
ini_set("allow_url_fopen", true);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
   
   $printString = "";
   
   foreach ($_GET as $key => $value) {
       
       $printString = $printString . "Key: " . $key . " Val: " . $value . "\n";
   }
   
   file_put_contents("getRequest.txt", $printString);
   
   if (isset($_GET['hub_challenge'])) {
       $challenge = $_GET['hub_challenge'];
       echo $challenge;
       file_put_contents("resget.txt", $challenge);
   }
}

$post = $_POST;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   $payload = "POST received\n";
   file_put_contents("payload.txt", $payload);
}
file_put_contents("respost.txt", $post);`

```

who accepts answers.

I managed to get

- Key: hub\_challenge Val: xv98f4agjuJXIPi5tj3XmZUm3BrMNhx8
- Key: hub\_lease\_seconds Val: 864000
- Key: hub\_mode Val: subscribe
- Key: hub\_topic Val: [https://api.twitch.tv/helix/users/follows?first=1&to\_id=117191228](https://api.twitch.tv/helix/users/follows?first=1&to_id=117191228)

and I don’t know how to respond to that message. Made an echo, but it doesn’t work. All actions, subscriptions, the beginning of the stream, do not work. What am I doing wrong?

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [April 28, 2019, 10:19am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/4 "2019-04-28T10:19:27Z")

</div>

> [@Wed](#):
>
> and I don’t know how to respond to that message. Made an echo, but it doesn’t work.

> [@Got no requests of twitch webhook after subscription](https://discuss.dev.twitch.com/t/got-no-requests-of-twitch-webhook-after-subscription/14993/2):
>
> Did you see the incoming post request from Twitch in your web server access logs? Did you see an error in your incoming server error logs? Did you reply to the incoming hub\_challenge with the hub\_challenge? \<?php if ($\_GET['hub\_challenge']) { echo $\_GET['hub\_challenge']; exit; }

```
if ($_GET['hub_challenge']) {
    echo $_GET['hub_challenge'];
    exit;
}

```

Is correct. (Or the isset you have is _more_ correct)

> [@Wed](#):
>
> file\_put\_contents(“getRequest.txt”, $printString);

You can improve this/save a loop with

> file\_put\_contents(‘getRequest.txt’, print\_r($\_GET,true) . “\n”);

If you need to log $\_GET/$\_POST

> [@Wed](#):
>
> All actions, subscriptions, the beginning of the stream, do not work. What am I doing wrong?

You have subscribed to the follows topic for a user following someone, this will only send you events when `$target_user_id` follows someone else on Twitch (which is back to front for overlay/chat announcments for new followers to a channel).

It won’t send you subscriptions (there is currently no topic for that) and it won’t send you stream changes.

**For Stream Change** Subscribe to `https://api.twitch.tv/helix/streams?user_id=<USERID>`  
**For new follows to a streamer** Subscribe to `https://api.twitch.tv/helix/users/follows?first=1&to_id=<USERID>`  
**For new follows a user makes** Subscribe to `https://api.twitch.tv/helix/users/follows?first=1&from_id=<USERID>`

You probably don’y need the last topic, but that is what you have subscribed to

> [@Wed](#):
>
> ini\_set(“allow\_url\_fopen”, true);

You don’t need and should never enable this on production.

You also don’t need the access control header in this context.

**Additionally** you can use the following:

> **[Reference](https://dev.twitch.tv/docs/api/reference/#get-webhook-subscriptions)**
>
> Twitch Developer tools and services to integrate Twitch into your development or create interactive experience on twitch.tv.

To check the status and existence of any active Webhooks.

**GOTCHA** As this is a webhook following the spec, data is not delivered via `$_POST` but via `php://input` as per

> **[Handling Incoming Webhooks in PHP](https://lornajane.net/posts/2017/handling-incoming-webhooks-in-php)**
>
> An increasing number of applications now offer webhooks as an integration, often in addition to an API. The classic example, familiar to most developers, is the GitHub webhooks which can notify your other systems such as CI tooling that a new commit...

**Code Tidy/corrections**

```
<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    file_put_contents( __DIR__. "/payload.txt", print_r(file_get_contents('php://input'), true) . "\n", FILE_APPEND);

    $incoming_payload = json_decode(file_get_contents('php://input'));
    if (json_last_error() == JSON_ERROR_NONE) {
        // all good do stuff

        header('HTTP/1.1 200 OK');
        echo 'OK';
        exit;
    }

    // someone posted but no data to read?
    header('HTTP/1.1 404 Not Found');
    exit;
}

// must be a GET (should not be PUT/etc

file_put_contents( __DIR__. "/getRequest.txt", print_r($_GET, true) . "\n", FILE_APPEND);
   
if (isset($_GET['hub_challenge'])) {
    $challenge = $_GET['hub_challenge'];
    header('HTTP/1.1 200 OK');
    echo $challenge;
    exit;
}
header('HTTP/1.1 404 Not Found');
exit;

```

Finally `if ($_SERVER['REQUEST_METHOD'] === 'POST') {` is fine. I usually prefer `if ($_POST)` but that’s a preference thing really

---

<div class="post-metadata">

**Author:** ![Wed](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/wed/32/6246_2.png) [@Wed](https://discuss.dev.twitch.com/u/Wed)\
**Post date:** [April 28, 2019, 11:05pm UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/5 "2019-04-28T23:05:12Z")

</div>

Thank you very much, everything works. I had a few more questions:

1. So for every event, I have to send new requests? For follower  
`'hub.topic' = 'https://api.twitch.tv/helix/users/follows?first=1&amp;to_id= ******** http://mysite.com/twitch.webhookfollow.php`  
To notify the streamer?  
`https://api.twitch.tv/helix/streams?user_id= ******** http://mysite.com/twitch.webhookstream.php`  
Or perhaps somehow specify the query to receive all events?

2. The connection will operate 10 days, after which it will stop working right? So you have to put the update on cron, or is the connection not lost?

3. `https://api.twitch.tv/helix/users/follows?first=1&amp;to_id= ******** ` we receive information about all new followers, and is it possible to also receive notifications about all unfollowers? Thanks for your help.

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [April 29, 2019, 8:55am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/6 "2019-04-29T08:55:41Z")

</div>

> [@Wed](#):
>
> Or perhaps somehow specify the query to receive all events?

What do you mean all events?

The Topic you specified will send you all new followers as they occur for that `to_id` as long as the webhook is active/within lease time. And you continue to maintain the listener.

> [@Wed](#):
>
> The connection will operate 10 days, after which it will stop working right? So you have to put the update on cron, or is the connection not lost?

Correct, you set the lease time to whatever you want, the maximum is 10 days and you need to manually recreate the link. You will need to space out your reconnections to stay within the posted rate limits

> [@Wed](#):
>
> `https://api.twitch.tv/helix/users/follows?first=1&amp;to_id= ******** ` we receive information about all new followers, and is it possible to also receive notifications about all unfollowers? Thanks for your help.

No you cannot receive notifications about unfollows. This leads to harassment of the person unfollowing and as such is excluded as a notification.

---

<div class="post-metadata">

**Author:** ![Wed](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/wed/32/6246_2.png) [@Wed](https://discuss.dev.twitch.com/u/Wed)\
**Post date:** [May 3, 2019, 4:28am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/7 "2019-05-03T04:28:31Z")

</div>

> [@BarryCarlyon](#):
>
> What do you mean all events?
> 
> The Topic you specified will send you all new followers as they occur for that `to_id` as long as the webhook is active/within lease time. And you continue to maintain the listener.

Thank You for your answer, I meant that now I specify for each event a new confirmation request

```auto
    $data = array(
     'hub.mode' => $mode,
     'hub.topic' => 'https://api.twitch.tv/helix/users/follows?first=1&to_id='.$target_user_id,
     'hub.callback' => $callback_url,
     'hub.lease_seconds' => $lease_seconds
     );

```

to receive notification of new followers and

```auto
    $data = array(
     'hub.mode' => $mode,
     'hub.topic' => 'https://api.twitch.tv/helix/streams?user_id='.$target_user_id,
     'hub.callback' => $callback_url,
     'hub.lease_seconds' => $lease_seconds
     ); 

```

to receive notification of the beginning of the stream.  
And therefore the files take answers. twitch.webhook.follow.php and twitch.webhook.stream.php with the code you specified above. Is it possible to somehow make a request for receiving and notifications about new followers and the beginning of the stream in one request?  
That is, specify something like ‘hub.topic’ = all and receive all available notifications and how to track them in twitch.webhook.php is Allowed not to create a large number of requests and files that will accept responses.

And there was another question. Configured notifications about the stream, it comes more than once. For 3 hours stream can come more than 4 notifications, this is a bug of the system? Or did I do something wrong Or I made a mistake in the code, although I did not see such an error in the notification of followers?

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [May 3, 2019, 10:37am UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/8 "2019-05-03T10:37:11Z")

</div>

> [@Wed](#):
>
> Is it possible to somehow make a request for receiving and notifications about new followers and the beginning of the stream in one request?

No, it’s Two topics. So you need two requests

> [@Wed](#):
>
> That is, specify something like ‘hub.topic’ = all and receive all available notifications and how to track them in twitch.webhook.php is Allowed not to create a large number of requests and files that will accept responses.

No there is no “all”.

You can use query strings in your callback so for example

For topic

> [https://api.twitch.tv/helix/streams?user\_id=](https://api.twitch.tv/helix/streams?user_id=)'.$target\_user\_id

You can

> hub.callback=[https://domain.dom/webhooks?type=stream&id=](https://domain.dom/webhooks?type=stream&id=)'.$target\_user\_id

> [@Wed](#):
>
> And there was another question. Configured notifications about the stream, it comes more than once. For 3 hours stream can come more than 4 notifications, this is a bug of the system?

You will get a stream change when the following occurs

- The Stream Went Live
- The Stream went offline
- Anything changes (except viewer count), so, for example, if any of the following changes you will get another payload
  - game
  - title

---

<div class="post-metadata">

**Author:** ![Wed](https://d3ovvz0v2ajtpu.cloudfront.net/user_avatar/discuss.dev.twitch.com/wed/32/6246_2.png) [@Wed](https://discuss.dev.twitch.com/u/Wed)\
**Post date:** [May 4, 2019, 4:25pm UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/9 "2019-05-04T16:25:27Z")

</div>

Oh, I never thought of that.  
Thanks for Your help, everything works.

---

<div class="post-metadata">

**Author:** ![system](https://d2opxh93rbxzdn.cloudfront.net/original/2X/0/05909729875cce3b53e59d5561c4d23bb14948fc.png) [@system](https://discuss.dev.twitch.com/u/system)\
**Post date:** [June 3, 2019, 4:25pm UTC](https://discuss.dev.twitch.com/t/webhook-twitch-start/21010/10 "2019-06-03T16:25:28Z")

</div>

Closed on June 3, 2019, 4:25pm UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
