-
Notifications
You must be signed in to change notification settings - Fork 0
/
page-stream-team.php
83 lines (73 loc) · 2.44 KB
/
page-stream-team.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/*
Template Name: Campaign - Stream Team
*/
$context = Timber::context();
$timber_post = new Timber\Post();
$context['post'] = $timber_post;
$users_array = array_map(
'trim',
explode(PHP_EOL, get_field('stream_team_members'))
);
$context['stream_calendar_url'] = get_field('stream_calendar_url');
sort($users_array, SORT_NATURAL);
$client_id = get_field('api_twitch_client_id', 'option');
$client_secret = get_field('api_twitch_client_secret', 'option');
$access_token = get_field('api_twitch_access_token', 'option');
function getAccessToken($client_id, $client_secret)
{
// Get Oauth access token
$access = curl_init();
curl_setopt(
$access,
CURLOPT_URL,
"https://id.twitch.tv/oauth2/token?client_id=$client_id&client_secret=$client_secret&grant_type=client_credentials"
);
curl_setopt($access, CURLOPT_POST, true);
curl_setopt($access, CURLOPT_RETURNTRANSFER, true);
$access_response = json_decode(curl_exec($access), true);
$access_token = $access_response['access_token'];
update_field("api_twitch_access_token", $access_token, "option");
curl_close($access);
return $access_token;
}
function getChannels($client_id, $access_token, $users_array)
{
$channels = curl_init();
curl_setopt(
$channels,
CURLOPT_URL,
"https://api.twitch.tv/helix/streams?user_login=" .
implode("&user_login=", $users_array)
);
curl_setopt($channels, CURLOPT_RETURNTRANSFER, true);
curl_setopt($channels, CURLOPT_HTTPHEADER, [
"Client-ID: $client_id",
"Authorization: Bearer $access_token",
]);
$return = json_decode(curl_exec($channels));
curl_close($channels);
return $return;
}
$context['twitch_data'] = [];
if ($client_id && $client_secret) {
if ($access_token) {
// We got a token, let's try it...
$stream_data = getChannels($client_id, $access_token, $users_array);
if ($stream_data !== null) {
// We got something?
$context['twitch_data'] = $stream_data;
} else {
// We didn't get nuffin, try refreshing the token and going again...
$access_token = getAccessToken($client_id, $client_secret);
$stream_data = getChannels($client_id, $access_token, $users_array);
$context['twitch_data'] = $stream_data;
}
} else {
$access_token = getAccessToken($client_id, $client_secret);
$stream_data = getChannels($client_id, $access_token, $users_array);
$context['twitch_data'] = $stream_data;
}
}
$context['twitch_usernames'] = $users_array;
Timber::render('page-stream-team.twig', $context, 0, Timber\Loader::CACHE_NONE);