Webhook twitch start

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));
});

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.

1 Like

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.
<?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
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

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?

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

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

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

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

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:

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

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

1 Like

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.

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.

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

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

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

    $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

    $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?

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

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='.$target_user_id

You can

hub.callback=https://domain.dom/webhooks?type=stream&id='.$target_user_id

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

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

1 Like

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