PHP EventSubs Examples

Hey

I’ve managed so far a few basic examples with the API with PHP and CURL. Go

Now I want to interact with my Channel Points and Subscriber Events etc. but I am totaly lost…

I’ve seen so far that BarryCarlyon is the MEN and provided a lot of examples. But I have no clue how to subscribe to eventsubs… for any example with PHP i would thankful.

THX

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'
            )
        )));
1 Like

Thanks for you help…

I’ve tried so far your example. And one where I fetch step by step the tokens with different scopes. This works fine.

BUT… also with different eventsubs I always get the error:

“Got tokenfailed to create sub: {“error”:“Bad Request”,“status”:400,“message”:“unsupported eventsub transport method”}”

<?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(
            
			   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
            'type' => 'channel.subscribe"',
            'version' => '1',
            'condition' => array( 'broadcaster_user_id' => 'myuserID' ),
            'transport' => array(
                'method' => 'webhook',
                'callback' => 'https://mywebsite.com/twitch/recieveEvents.php',
                'secret' => '23k4hadfjd'
				)
			)))
			
        )));
        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;
}

I want to get event when someone redeemed channel points so I tried

{
    "type": "channel.channel_points_custom_reward.update",
    "version": "1",
    "condition": {
        "broadcaster_user_id": "myuserid",
        "reward_id": "9001" // optional to only get notifications for a specific reward
    },
    "transport": {
        "method": "webhook",
        'callback' => 'https://mywebsite.com/twitch/recieveEvents.php',
        "secret": "s3cRe7"
    }
}

(Edit: userid and callback url are just placeholder…I’ve tried it with my own data :slight_smile: )

Thanks for your thoughts on this
Greetings

ps.: u need a Ko-Fi account!!!

I forgot one thing!

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Client-ID: ' . CLIENT_ID,
            'Authorization: Bearer ' . $keys->access_token
        ));

should be

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Client-ID: ' . CLIENT_ID,
            'Authorization: Bearer ' . $keys->access_token,
            'Content-Type: application/json'
        ));

Hinting the “type” of the content being passed helps the reciever understand what kind of data is being passed and how to interpret it, in this case Twitch Defaults to one of the form types and we are not sending a form.

You mean like the one I have that is linked on my github? :stuck_out_tongue:

2 Likes

I have one more Question. I’ve managed a subscription (channel.channel_points_custom_reward_redemption.add)

When I’m now click on one of my channelpoint “actions” I expected something on the eventhandler.
(twitch_misc/index.php at main · BarryCarlyon/twitch_misc · GitHub)

I uncommented the logfunctions…

Array
(
    [Content-Length] => 801
    [Content-Type] => application/json
    [Accept-Encoding] => gzip
    [Connection] => close
    [Host] => www.myhost.com
    [Twitch-Eventsub-Message-Id] => wz8gADSFpMLF_KOtkX66-ASDFsITjbysFg=
    [Twitch-Eventsub-Message-Retry] => 0
    [Twitch-Eventsub-Message-Signature] => sha256=f981c24c93eadasdfaasdfasfsafasfsdfb539161
    [Twitch-Eventsub-Message-Timestamp] => 2022-04-25T16:50:33.979124589Z
    [Twitch-Eventsub-Message-Type] => notification
    [Twitch-Eventsub-Subscription-Is-Batching-Enabled] => false
    [Twitch-Eventsub-Subscription-Type] => channel.channel_points_custom_reward_redemption.add
    [Twitch-Eventsub-Subscription-Version] => 1
    [User-Agent] => Go-http-client/1.1
)

That looks good… and in the body_data I’ve can see a “channel point” redemption… This looks also good.

BUT… the PHP File just jumps to the “endpoint” and delete the logging file after refresh…

For my understanding: After I click on my channel points, the PHP File should show me JSON in this part of the PHP File

if ($headers['Twitch-Eventsub-Message-Type'] == 'notification') {
            // lets parse the data from the notification into an object
            $data = json_decode($raw_data);
            // and check the data parse
            if (json_last_error() == JSON_ERROR_NONE) {
                // we passed all the checks
                // tell Twitch it's OK
                echo 'Ok';
                // and now do something with the $data

                // $data is an object, not an array
		**print_r($data);**  //<--------------- NEW

                // end doing something with the $data
                exit;
            }
        }

Do i missunderstood here something?
Thanks again for your good work and help!

This gets 'echo’ed to Twitch. Not to anywhere useful.

So there is no where you to to “see” it.

So if you want to “see” it then you need to write it to a file. Or process it to do whatever follow up actions.

So at line 95 before $data = json_decode($raw_data); you could do

        if ($headers['twitch-eventsub-message-type'] == 'notification') {
            mylog($raw_data);
            // lets parse the data from the notification into an object
            $data = json_decode($raw_data);
            // and check the data parse
            if (json_last_error() == JSON_ERROR_NONE) {

Which will write the inbound POST JSON body to log for you to “see” it.
Then tail the log file in your console.

1 Like