Am I even doing this right...? (is_live integration into my own site)

Basically what I am trying to do is get my site to say that I am live with a string of text in the title bar with the game and the title of the stream. I don’t know JS/PHP all that well, just basic:

<?php
require_once ("../somewebpage.php");
?>

So I am basically winging it here. I do get: PHP Parse error: syntax error, unexpected ‘:’, expecting ‘)’ in /public_html/twitch.php on line 48

Which is: $ch = curl_init(‘https://id.twitch.tv/oauth2/token’);

<?php
$client_id = “ID”;
$secret_id = “secret”;
$keys = false;
if (file_exists(DIR . ‘/auth.json’)) {
$keys = json_decode(file_get_contents(DIR . ‘/auth.json’));
}

$generate_token = true;
if ($keys) {
// validate the token

$ch = curl_init('https://id.twitch.tv/oauth2/validate');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: OAuth ' . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($i['http_code'] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo 'Token close to expire. Regenerate';
            $generate_token = true;
        }
    } else {
        echo 'Failed to parse JSON. Assume dead token';
        $generate_token = true;
    }
}

} else { $generate_token = true; }

if ($generate_token) {
$ch = curl_init(‘https://id.twitch.tv/oauth2/token’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
‘client_id’ => $client_id,
‘client_secret’ => $secret_id,
‘grant_type’ => “client_credentials”
));

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

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

        // store the token for next run
        file_put_contents(__DIR__ . '/auth.json', $r, JSON_PRETTY_PRINT);
    } else {
        echo 'Failed to parse JSON';
    }
} else {
    echo 'Failed with ' . $i['http_code'] . ' ' . $r;
}

} else {
echo ‘Token OK’;
print_r($keys);
}

$user = ‘darkmage4’;//Streamers username
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, “https://api.twitch.tv/helix/streams?user_login=$user”);//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
“Client-ID: $client_id”,
"Authorization: Bearer " . $keys->access_token
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data[‘data’][0])) {
$live = 0;//Not live
} else {
$live = 1;//Is live
}

if ($live == 1) {
$title = $profile_data[‘data’][0][‘title’];
$viewer_count = $profile_data[‘data’][0][‘viewer_count’];
$game_id = $profile_data[‘data’][0][‘game_id’];
$went_live_at = DateTime::createFromFormat(“Y-m-d H:i:s”, date(“Y-m-d H:i:s”, strtotime($profile_data[‘data’][0][‘started_at’])))->format(‘Y-m-d H:i:s’);
$started = date_create($went_live_at);
$now = date_create(date(‘Y-m-d H:i:s’));
$diff = date_diff($started, $now);
$hours = $diff->h;
$minutes = $diff->i;
$is_live
echo “
$user is $is_live playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title”;
} else {
echo “
$user is not live”;
}
?>

Admin note: tried to fix your post submission [code] tags use ``` at start and end instead or indent with four spaces.

After fixing the copy paste from the forum to my file the only error I get is on line 108.
Since your input to the forum was littered with bad and

Since you tried to use [code] instaed of this forums preformatting methods

As the line 107 $is_live doesn’t have anything after it.

Aftr removing that line the file passed parse test (other than DIR not existing but I’m assuming copy/paste fail from the forums and you meant __DIR__

Ahh it said BBCode. I haven’t done forums in 12 years now, last I remembered it was the [code] tag to put it into a block. Apologies. So it works/behaves like Discord then with the BB Code. Alright!

On my server I am still getting:
PHP Parse error: syntax error, unexpected ‘:’, expecting ‘)’ in /public_html/twitch.php on line 48 - x10

Is this even the correct way of doing it for the API?

I also noticed in Notepad++ my secret ID is also orange for the digits.
Example:

The client ID is in normal text color, black.

The code that I had originally posted is this below:
NOTE: I also took out the is_live.

<?php
$client_id = “ID”;
$secret_id = “Secret
$keys = false;
if (file_exists(DIR . ‘/auth.json’)) {
$keys = json_decode(file_get_contents(DIR . ‘/auth.json’));
}

$generate_token = true;
if ($keys) {
// validate the token

$ch = curl_init('https://id.twitch.tv/oauth2/validate');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: OAuth ' . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($i['http_code'] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo 'Token close to expire. Regenerate';
            $generate_token = true;
        }
    } else {
        echo 'Failed to parse JSON. Assume dead token';
        $generate_token = true;
    }
}

} else { $generate_token = true; }

if ($generate_token) {
$ch = curl_init(‘https://id.twitch.tv/oauth2/token’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
‘client_id’ => $client_id,
‘client_secret’ => $secret_id,
‘grant_type’ => “client_credentials”
));

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

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

        // store the token for next run
        file_put_contents(__DIR__ . '/auth.json', $r, JSON_PRETTY_PRINT);
    } else {
        echo 'Failed to parse JSON';
    }
} else {
    echo 'Failed with ' . $i['http_code'] . ' ' . $r;
}

} else {
echo ‘Token OK’;
print_r($keys);
}

$user = ‘darkmage4’;//Streamers username
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, “https://api.twitch.tv/helix/streams?user_login=$user”);//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
“Client-ID: $client_id”,
"Authorization: Bearer " . $keys->access_token
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data[‘data’][0])) {
$live = 0;//Not live
} else {
$live = 1;//Is live
}

if ($live == 1) {
$title = $profile_data[‘data’][0][‘title’];
$viewer_count = $profile_data[‘data’][0][‘viewer_count’];
$game_id = $profile_data[‘data’][0][‘game_id’];
$went_live_at = DateTime::createFromFormat(“Y-m-d H:i:s”, date(“Y-m-d H:i:s”, strtotime($profile_data[‘data’][0][‘started_at’])))->format(‘Y-m-d H:i:s’);
$started = date_create($went_live_at);
$now = date_create(date(‘Y-m-d H:i:s’));
$diff = date_diff($started, $now);
$hours = $diff->h;
$minutes = $diff->i;
echo “
$user is $is_live playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title”;
} else {
echo “
$user is not live”;
}
?>

image

Should be

$secret_id = "abc";

You omitting the closing double quotes

Oh whoops! Ok, fixed that, but its still showing orange for the secret ID It stops when there is a letter.
Example:

With it showing orange in the secret ID portion, will that render the code useless?

Looks like you have a stylised " instead of a "

Note how it’s slanted.

Delete the slanted " and retype with shift + 2’s

Oh my, how did that even happen. lol. Fixed that.

Very interesting on why it did that. Fixed every occurrence on that, even ’ was slanted.

Otherwise, the orange is gone. But it’s still not outputting anything…

Then you need to add debug code.

Everything in lower end of your code, assumes you got a 200 OK and assumes that the response is a streams response and not an error response.

And if it’s outputting nothing then it’s failing in the token checks too since if the token is ok then it should output Token OK and a dump of the token.

So it should output something and if it isn’t I don’t know.

My OAuth Redirect URLs is “http://localhost” would that be the cause of issue? If so, then do I put my site in?
I just went ahead and did it after typing the first line, and still isn’t working.

EDIT: NOW I am getting something:

Failed with 403 {“status”:403,“message”:“invalid client secret”} Array ( [error] => Unauthorized [status] => 401 [message] => OAuth token is missing ) darkmage4 is not live

That suggests the token fetch step is failing.

And your client secret is invalid.

And your script didn’t stop there like it probably should and get going

I did fix the client secret.

Now i get this:
Got tokenstdClass Object ( [access_token] => REMOVED [expires_in] => 4770991 [token_type] => bearer ) Array ( [error] => Unauthorized [status] => 401 [message] => OAuth token is missing ) darkmage4 is not live

Removed your token, never leak those they are basically passwords

Whats yoru code look like now?

Oh! Thank you! Didn’t realize.
Edit: My error_log is showing
[23-May-2021 21:11:14 UTC] PHP Warning: Use of undefined constant DIR - assumed ‘DIR’ (this will throw an Error in a future version of PHP) in /public_html/twitch.php on line 8

<?php
$client_id = "ID";
$secret_id = "secret";
$keys = false;
if (file_exists(DIR . "/auth.json")) {
$keys = json_decode(file_get_contents(DIR . "/auth.json"));
}

$generate_token = true;
if ($keys) {
// validate the token

$ch = curl_init("https://id.twitch.tv/oauth2/validate");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: OAuth " . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($i["http_code"] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo "Token close to expire. Regenerate";
            $generate_token = true;
        }
    } else {
        echo "Failed to parse JSON. Assume dead token";
        $generate_token = true;
    }
}

} else { $generate_token = true; }

if ($generate_token) {
$ch = curl_init("https://id.twitch.tv/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"client_id" => $client_id,
"client_secret" => $secret_id,
"grant_type" => "client_credentials"
));

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

if ($i["http_code"] == 200) {
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        echo "Got token";
        print_r($data);

        // store the token for next run
        file_put_contents(__DIR__ . "/auth.json", $r, JSON_PRETTY_PRINT);
    } else {
        echo "Failed to parse JSON";
    }
} else {
    echo "Failed with " . $i["http_code"] . " " . $r;
}

} else {
echo "Token OK";
print_r($keys);
}

$user = "darkmage4";//Streamers username
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/helix/streams?user_login=$user");//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Client-ID: $client_id",
"Authorization: Bearer " . $keys->access_token
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data["data"][0])) {
$live = 0;//Not live
} else {
$live = 1;//Is live
}

if ($live == 1) {
$title = $profile_data["data"][0]["title"];
$viewer_count = $profile_data["data"][0]["viewer_count"];
$game_id = $profile_data["data"][0]["game_id"];
$went_live_at = DateTime::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:s", strtotime($profile_data["data"][0]["started_at"])))->format("Y-m-d H:i:s");
$started = date_create($went_live_at);
$now = date_create(date("Y-m-d H:i:s"));
$diff = date_diff($started, $now);
$hours = $diff->h;
$minutes = $diff->i;
echo "
$user is $is_live playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title";
} else {
echo "
$user is not live";
}
?>
$keys = false;
if (file_exists(DIR . "/auth.json")) {
$keys = json_decode(file_get_contents(DIR . "/auth.json"));
}

Should be

$keys = false;
if (file_exists(__DIR__ . "/auth.json")) {
$keys = json_decode(file_get_contents(__DIR__ . "/auth.json"));
}

But this doesn’t cause the problem of the missing token,

I downloaded your script. Plugged in my clientID and secret.
And it ran fine:

php forum_31761.php
Token OKstdClass Object
(
    [access_token] => SomeToken
    [expires_in] => 4733801
    [token_type] => bearer
)
Array
(
    [data] => Array
        (
        )

    [pagination] => Array
        (
        )

)

All I did was fix the DIR to __DIR__ at the top of the file

And fix this

You were generating a new token but not assigning it to $keys

<?php

$client_id = "";
$secret_id = "";
$keys = false;
if (file_exists(__DIR__ . "/auth.json")) {
$keys = json_decode(file_get_contents(__DIR__ . "/auth.json"));
}

$generate_token = true;
if ($keys) {
// validate the token

$ch = curl_init("https://id.twitch.tv/oauth2/validate");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: OAuth " . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($i["http_code"] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo "Token close to expire. Regenerate";
            $generate_token = true;
        }
    } else {
        echo "Failed to parse JSON. Assume dead token";
        $generate_token = true;
    }
}

} else { $generate_token = true; }

if ($generate_token) {
$ch = curl_init("https://id.twitch.tv/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"client_id" => $client_id,
"client_secret" => $secret_id,
"grant_type" => "client_credentials"
));

$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";
        print_r($keys);

        // store the token for next run
        file_put_contents(__DIR__ . "/auth.json", $r);
    } else {
        echo "Failed to parse JSON";
        exit;
    }
} else {
    echo "Failed with " . $i["http_code"] . " " . $r;
    exit;
}

} else {
echo "Token OK";
print_r($keys);
}

$user = "darkmage4";//Streamers username
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/helix/streams?user_login=$user");//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Client-ID: $client_id",
"Authorization: Bearer " . $keys->access_token
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data["data"][0])) {
$live = 0;//Not live
} else {
$live = 1;//Is live
}

if ($live == 1) {
$title = $profile_data["data"][0]["title"];
$viewer_count = $profile_data["data"][0]["viewer_count"];
$game_id = $profile_data["data"][0]["game_id"];
$went_live_at = DateTime::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:s", strtotime($profile_data["data"][0]["started_at"])))->format("Y-m-d H:i:s");
$started = date_create($went_live_at);
$now = date_create(date("Y-m-d H:i:s"));
$diff = date_diff($started, $now);
$hours = $diff->h;
$minutes = $diff->i;
echo "
$user is $is_live playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title";
} else {
echo "
$user is not live";
}

Token OKstdClass Object ( [access_token] => TOKEN [expires_in] => 5122285 [token_type] => bearer ) Array ( [data] => Array ( ) [pagination] => Array ( ) ) darkmage4 is not live

This is what its outputting on the test site.

and nothing in the error log.

See this adjustment:

On “new token” generation $keys wasn’t being set

<?php

$client_id = "";
$secret_id = "";
$keys = false;
if (file_exists(__DIR__ . "/auth.json")) {
$keys = json_decode(file_get_contents(__DIR__ . "/auth.json"));
}

$generate_token = true;
if ($keys) {
// validate the token

$ch = curl_init("https://id.twitch.tv/oauth2/validate");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: OAuth " . $keys->access_token
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

if ($i["http_code"] == 200) {
    // the token appears good
    $generate_token = false;

    // optional to check the expires
    $data = json_decode($r);
    if (json_last_error() == JSON_ERROR_NONE) {
        if ($data->expires_in < 3600) {
            // less than an hour left
            // make a new token
            echo "Token close to expire. Regenerate";
            $generate_token = true;
        }
    } else {
        echo "Failed to parse JSON. Assume dead token";
        $generate_token = true;
    }
}

} else { $generate_token = true; }

if ($generate_token) {
$ch = curl_init("https://id.twitch.tv/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
"client_id" => $client_id,
"client_secret" => $secret_id,
"grant_type" => "client_credentials"
));

$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";
        print_r($keys);

        // store the token for next run
        file_put_contents(__DIR__ . "/auth.json", $r);
    } else {
        echo "Failed to parse JSON";
        exit;
    }
} else {
    echo "Failed with " . $i["http_code"] . " " . $r;
    exit;
}

} else {
echo "Token OK";
print_r($keys);
}

$user = "darkmage4";//Streamers username
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.twitch.tv/helix/streams?user_login=$user");//Endpoint
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Client-ID: $client_id",
"Authorization: Bearer " . $keys->access_token
));
$profile_data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($profile_data);

if (!isset($profile_data["data"][0])) {
$live = 0;//Not live
} else {
$live = 1;//Is live
}

if ($live == 1) {
$title = $profile_data["data"][0]["title"];
$viewer_count = $profile_data["data"][0]["viewer_count"];
$game_id = $profile_data["data"][0]["game_id"];
$went_live_at = DateTime::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:s", strtotime($profile_data["data"][0]["started_at"])))->format("Y-m-d H:i:s");
$started = date_create($went_live_at);
$now = date_create(date("Y-m-d H:i:s"));
$diff = date_diff($started, $now);
$hours = $diff->h;
$minutes = $diff->i;
echo "
$user is $is_live playing $game_name, started streaming $hours hours $minutes minutes ago and has $viewer_count viewers TITLE: $title";
} else {
echo "
$user is not live";
}

It looks like you took my example https://github.com/BarryCarlyon/twitch_misc/blob/main/authentication/app_access_tokens/php/generate_and_maintain_token.php and didn’t modify it correctly.

This line https://github.com/BarryCarlyon/twitch_misc/blob/main/authentication/app_access_tokens/php/generate_and_maintain_token.php#L62 just has the keys in $data which is useless to the test of the file.

Since this script is only for generating and maintaint a token not for then making other calls, so you missed a modification

What do you mean your example?

Also, still getting the error:

Token OKstdClass Object ( [access_token] => TOKEN [expires_in] => 5122285 [token_type] => bearer ) Array ( [data] => Array ( ) [pagination] => Array ( ) ) darkmage4 is not live

The log isn’t outputting any errors anymore though.

This isn’t an error.

This is all the print_r’s outputting

This: https://github.com/BarryCarlyon/twitch_misc/blob/main/authentication/app_access_tokens/php/generate_and_maintain_token.php

I recognised a mistake in the code you originally posted (passing json_pretty_print to file_put_contents) which I’ve since fixed in the linked file in the last 10 minutes

Yeah, I wasn’t on github, I’ve found snippets of some code around the web and compiled it together a bit, stack overflow mainly. But the lot of them were older codes. So I gathered old information with new information on the dev twitch. Your snipped must have been floating around in other codes and that’s how I picked it up I do believe.

Anyways, how do I get it to just print out that I am live with the game name, hours, and viewers?

Remove all the print_rs