PHP EventSubs Examples

On my github, as you found, there is a example for an EventSub Reciever.

But not one for creating a subscription. As it’s just an API call. if you are already able to “talk to Twitch API” then you are good to go as this is “basic” knowledge so my github tends to cover the “complicated” stuff rather than the simple stuff

So, as per Reference | Twitch Developers

Something like this (untested using twitch_misc/generate_and_maintain_token.php at main · BarryCarlyon/twitch_misc · GitHub as a base for token gen) should do the trick to create a subscription request.

<?php

include(__DIR__ . '/config.php');

$ch = curl_init('https://id.twitch.tv/oauth2/token?client_id=' . CLIENT_ID . '&client_secret=' . CLIENT_SECRET . '&grant_type=client_credentials');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$r = curl_exec($ch);
$i = curl_getinfo($ch);
curl_close($ch);

if ($i['http_code'] == 200) {
    $keys= json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        echo 'Got token';


        $ch = curl_init('https://api.twitch.tv/helix/eventsub/subscriptions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
            // DATA HERE
        )));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Client-ID: ' . CLIENT_ID,
            'Authorization: Bearer ' . $keys->access_token
        ));

        $r = curl_exec($ch);
        $i = curl_getinfo($ch);
        curl_close($ch);

        if ($i['http_code'] == 200) {
            // created sub OK
           echo 'created sub OK';
        } else {
           echo 'failed to create sub: ' . $r;
        }
    } else {
        echo 'Failed to parse JSON';
    }
} else {
    echo 'Failed with ' . $i['http_code'] . ' ' . $r;
}

Substritute // DATA HERE for an suitable payload matching the data keys needed for the topci in EventSub Subscription Types | Twitch Developers

So perhaps

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
            'type' => 'channel.subscribe"',
            'version' => '1',
            'condition' => array( 'broadcaster_user_id' => '1337' ),
            'transport' => array(
                'method' => 'webhook',
                'callback' => 'your handler',
                'secret' => 'whatever you want'
            )
        )));
2 Likes