# PHP EventSubs Examples

**URL:** <https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072>\
**Category:** API\
**Created:** [April 23, 2022, 2:32pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072 "2022-04-23T14:32:49Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![oerjanjong](https://avatars.discourse-cdn.com/v4/letter/o/90db22/32.png) [@oerjanjong](https://staging-discuss.dev.twitch.com/u/oerjanjong)\
**Post date:** [April 23, 2022, 2:32pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/1 "2022-04-23T14:32:49Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [April 23, 2022, 4:38pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/2 "2022-04-23T16:38:46Z")

</div>

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](https://dev.twitch.tv/docs/api/reference#create-eventsub-subscription)

Something like this (untested using [twitch\_misc/generate\_and\_maintain\_token.php at main · BarryCarlyon/twitch\_misc · GitHub](https://github.com/BarryCarlyon/twitch_misc/blob/main/authentication/app_access_tokens/php/generate_and_maintain_token.php) as a base for token gen) should do the trick to create a subscription request.

```auto
<?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](https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types#channelsubscribe)

So perhaps

```auto
        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'
            )
        )));

```

---

<div class="post-metadata">

**Author:** ![oerjanjong](https://avatars.discourse-cdn.com/v4/letter/o/90db22/32.png) [@oerjanjong](https://staging-discuss.dev.twitch.com/u/oerjanjong)\
**Post date:** [April 24, 2022, 8:57am UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/3 "2022-04-24T08:57:12Z")

</div>

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”}”

```auto
<?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

```auto
{
    "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 🙂 )

Thanks for your thoughts on this  
Greetings

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

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [April 24, 2022, 11:51am UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/4 "2022-04-24T11:51:10Z")

</div>

> [@oerjanjong](#):
>
> “Got tokenfailed to create sub: {“error”:“Bad Request”,“status”:400,“message”:“unsupported eventsub transport method”}”

I forgot one thing!

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

```

should be

```php
        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.

> [@oerjanjong](#):
>
> ps.: u need a Ko-Fi account!!!

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

---

<div class="post-metadata">

**Author:** ![oerjanjong](https://avatars.discourse-cdn.com/v4/letter/o/90db22/32.png) [@oerjanjong](https://staging-discuss.dev.twitch.com/u/oerjanjong)\
**Post date:** [April 25, 2022, 5:14pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/5 "2022-04-25T17:14:00Z")

</div>

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](https://github.com/BarryCarlyon/twitch_misc/blob/main/eventsub/handlers/php/index.php))

I uncommented the logfunctions…

```auto
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

```auto
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!

---

<div class="post-metadata">

**Author:** ![BarryCarlyon](https://d1d6mrmdu7ztse.cloudfront.net/user_avatar/staging-discuss.dev.twitch.com/barrycarlyon/32/253_2.png) [@BarryCarlyon](https://staging-discuss.dev.twitch.com/u/BarryCarlyon)\
**Post date:** [April 25, 2022, 5:49pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/6 "2022-04-25T17:49:44Z")

</div>

> [@oerjanjong](#):
>
> ```auto
> // $data is an object, not an array
> **print_r($data);** //<--------------- NEW
> 
> // end doing something with the $data
> exit;
> 
> ```

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

```php
        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.

---

<div class="post-metadata">

**Author:** ![system](https://d2spem0quai2ol.cloudfront.net/original/2X/0/05909729875cce3b53e59d5561c4d23bb14948fc.png) [@system](https://staging-discuss.dev.twitch.com/u/system)\
**Post date:** [May 25, 2022, 5:49pm UTC](https://staging-discuss.dev.twitch.com/t/php-eventsubs-examples/38072/7 "2022-05-25T17:49:44Z")

</div>

Closed on May 25, 2022, 5:49pm UTC

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