Skip to content

Commit f7ad279

Browse files
committed
README Updates #82
1 parent 730b695 commit f7ad279

File tree

1 file changed

+130
-111
lines changed

1 file changed

+130
-111
lines changed

README.md

Lines changed: 130 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,180 @@
1-
# twitch-api-php
1+
# Twitch API PHP Library
22

3-
# New Twitch API (Helix)
3+
![Packagist Version](https://img.shields.io/packagist/v/nicklaw5/twitch-api-php)
4+
![Packagist PHP Version Support](https://img.shields.io/packagist/php-v/nicklaw5/twitch-api-php)
5+
![Packagist Downloads](https://img.shields.io/packagist/dt/nicklaw5/twitch-api-php)
6+
![Packagist License](https://img.shields.io/packagist/l/nicklaw5/twitch-api-php)
47

5-
A New Twitch API (Helix) client for PHP. The code for the new API is all contained within `src/NewApi/`. This is because the New API code is meant to be separate from the old Kraken API code, such that in the future, when Kraken is no longer available, the old Kraken code can be removed without affecting the new API code. Additionally, keeping them separate allows for existing code using the Kraken part of this library to continue to function, untouched by the new code.
8+
The Twitch API PHP Library allows you to interact through HTTP to a number of [Twitch API](https://dev.twitch.tv/docs/api/) endpoints. The library does not format the repsonses of your request so you have full flexability in how to handle the data that is returned from the API.
69

7-
The New Twitch API client is still being developed and is currently incomplete. The endpoints that are implemented are usable, but not all endpoints have been implemented yet. If an endpoint you need is missing, incomplete, or not working correctly, please report it or fix it if you can and create a PR for it.
10+
## Documentation & Links
811

9-
## Usage
12+
- [Twitch API Documentation](https://dev.twitch.tv/docs/api/)
13+
- [TwitchDev Discord](https://link.twitch.tv/devchat)
14+
- [Twitch Libraries Discord](https://discord.gg/8NXaEyV)
1015

11-
Everything stems from the `NewTwitchApi` class. However, if you want to individually instantiate `UsersApi`, `OauthApi`, etc. you are free to do so.
16+
## Getting Started
1217

13-
The API calls generally return an object implementing `ResponseInterface`. Since you are getting the full `Response` object, you'll need to handle its contents, e.g. by decoding then into an object with `json_decode()`. This library does not assume this is what you want to do, so it does not do this for you automatically. This library simply acts as a middleman between your code and Twitch, providing you with the raw responses the Twitch API returns.
18+
### Requirements
1419

15-
The individual API classes that can be called from `NewTwitchApi` correspond to the [New Twitch API documentation](https://dev.twitch.tv/docs/api/). `OauthApi` is for Oauth calls. `WebhooksSubscriptionApi` is for subscribing/unsubscribing to webhooks. The rest of the API classes are based on the resources listed [here](https://dev.twitch.tv/docs/api/reference/). The methods in the classes generally correspond to the endpoints for each resource. The naming convention was chosen to try and match the Twitch documentation. Each primary endpoint method (not convenience or helper methods) should have an `@link` annotation with a URL to that endpoint's specific documentation.
20+
- PHP 7.4 - The library has been shown to work on earlier versions but we encoruage you to use the latest versions of PHP that are tested with our library. - The requirement will be increased to PHP 8.0 in the future, so you should develop for the latest version of PHP.
21+
- Composer
22+
- `ext-json: *`
23+
- [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) `~6.0|~7.0`
1624

17-
## Examples
25+
### Installation
1826

19-
Getting a user's information via their access token:
27+
The recommended way to install the Twitch API PHP Library is through [Composer](https://getcomposer.org/).
2028

21-
```php
22-
// Assuming you already have the access token.
23-
$accessToken = 'the token';
24-
25-
// The Guzzle client used can be the included `HelixGuzzleClient` class, for convenience.
26-
// You can also use a mock, fake, or other double for testing, of course.
27-
$helixGuzzleClient = new HelixGuzzleClient($clientId);
28-
29-
// Instantiate NewTwitchApi. Can be done in a service layer and injected as well.
30-
$newTwitchApi = new NewTwitchApi($helixGuzzleClient, $clientId, $clientSecret);
29+
```bash
30+
composer require nicklaw5/twitch-api-php
3131

32-
try {
33-
// Make the API call. A ResponseInterface object is returned.
34-
$response = $newTwitchApi->getUsersApi()->getUserByAccessToken($accessToken);
35-
36-
// Get and decode the actual content sent by Twitch.
37-
$responseContent = json_decode($response->getBody()->getContents());
38-
39-
// Return the first (or only) user.
40-
return $responseContent->data[0];
41-
} catch (GuzzleException $e) {
42-
// Handle error appropriately for your application
43-
}
4432
```
4533

46-
## Developer Tools
47-
48-
### PHP Coding Standards Fixer
34+
### Example Usage
4935

50-
[PHP Coding Standards Fixer](https://cs.sensiolabs.org/) (`php-cs-fixer`) has been added, specifically for the New Twitch API code. A configuration file for it can be found in `.php_cs.dist`. The ruleset is left at default (PSR-2 at this time). The configuration file mostly just limits it's scope to only the New Twitch API code.
51-
52-
You can run the fixer with `vendor/bin/php-cs-fixer fix`. However, the easiest way to run the fixer is with the provided git hook.
36+
All calls to the Twitch API require bearer tokens that can be retrieved through the `OauthApi` class. You can review the [types of tokens](https://dev.twitch.tv/docs/authentication/#types-of-tokens) in the Twitch API docs. The below examples store the Client ID, Secret and Scopes directly in the example, but you should not do this. Store your IDs, Secret, and Scopes in a secure place such as your database or environment variables or alternate settings storage. Security of this information is important. Here is an example of how you can retrieve a token for your application:
5337

54-
### Git pre-commit Hook
55-
56-
In `bin/git/hooks`, you'll find a `pre-commit` hook that you can add to git that will automatically run the `php-cs-fixer` everytime you commit. The result is that, after the commit is made, any changes that fixer has made are left as unstaged changes. You can review them, then add and commit them.
38+
```php
39+
$twitch_client_id = 'TWITCH_CLIENT_ID';
40+
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
41+
$twitch_scopes = '';
5742

58-
To install the hook, go to `.git/hooks` and `ln -s ../../bin/git/hooks/pre-commit`.
43+
$helixGuzzleClient = new \NewTwitchApi\HelixGuzzleClient($twitch_client_id);
44+
$newTwitchApi = new \NewTwitchApi\NewTwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
45+
$oauth = $newTwitchApi->getOauthApi();
5946

60-
## API Documentation
47+
try {
48+
$token = $oauth->getAppAccessToken($twitch_scopes ?? '');
49+
$data = json_decode($token->getBody()->getContents());
6150

62-
The New Twitch API docs can be found [here](https://dev.twitch.tv/docs/api/).
51+
// Your bearer token
52+
$twitch_access_token = $data->access_token ?? null;
6353

64-
## License
54+
// The scopes from the API
55+
$twitch_scopes = $data->scope;
56+
} catch (Exception $e) {
57+
//TODO: Handle Error
58+
}
59+
```
6560

66-
Distributed under the [MIT](LICENSE) license.
61+
Here is an example of how you retrieve a users token:
6762

68-
---
69-
---
70-
---
63+
```php
64+
$twitch_client_id = 'TWITCH_CLIENT_ID';
65+
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
66+
$twitch_scopes = '';
67+
68+
$helixGuzzleClient = new \NewTwitchApi\HelixGuzzleClient($twitch_client_id);
69+
$newTwitchApi = new \NewTwitchApi\NewTwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
70+
$oauth = $newTwitchApi->getOauthApi();
71+
72+
// Get the current URL, we'll use this to redirect them back to exactly where they came from
73+
$currentUri = explode('?', 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'])[0];
74+
75+
if ($code == '') {
76+
// Generate the Oauth Uri
77+
$oauthUri = $oauth->getAuthUrl($currentUri, 'code', $twitch_scopes);
78+
// Redirect them as there was no auth code
79+
header("Location: {$oauthUri}");
80+
} else {
81+
try {
82+
$token = $oauth->getUserAccessToken($code, $currentUri);
83+
// It is a good practice to check the status code when they've responded, this really is optional though
84+
if ($token->getStatusCode() == 200) {
85+
// Below is the returned token data
86+
$data = json_decode($token->getBody()->getContents());
87+
88+
// Your bearer token
89+
$twitch_access_token = $data->access_token ?? null;
90+
91+
// The scopes from the API
92+
$twitch_scopes = $data->scope;
93+
} else {
94+
//TODO: Handle Error
95+
}
96+
} catch (Exception $e) {
97+
//TODO: Handle Error
98+
}
99+
}
100+
```
71101

72-
# Kraken
102+
When you have a user token that is expired, you're able to refresh it instead of requiring them to authenticate again. Here is an example of how you refresh a users token:
73103

74-
A Twitch Kraken API client for PHP. This is the old API, which is deprecated and will be deleted soon. Please use Helix instead. If something is missing from the Helix API, please add it or request it.
104+
```php
105+
$twitch_client_id = 'TWITCH_CLIENT_ID';
106+
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
107+
$twitch_scopes = '';
108+
$user_refresh_token = 'REFRESH_TOKEN';
75109

76-
The documentation below is left for legacy purposes, until Kraken support is removed.
110+
$helixGuzzleClient = new \NewTwitchApi\HelixGuzzleClient($twitch_client_id);
111+
$newTwitchApi = new \NewTwitchApi\NewTwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
112+
$oauth = $newTwitchApi->getOauthApi();
77113

78-
[![Build Status](https://travis-ci.com/nicklaw5/twitch-api-php.svg?branch=master)](https://travis-ci.com/nicklaw5/twitch-api-php)
114+
try {
115+
$token = $oauth->getAppAccessToken($twitch_scopes ?? '');
116+
$data = json_decode($token->getBody()->getContents());
79117

80-
## Supported APIs
118+
// Your bearer token
119+
$twitch_access_token = $data->access_token ?? null;
81120

82-
This library aims to support `v3` and `v5` of the Twitch API until each one becomes [deprecated](https://dev.twitch.tv/docs/v5). If an API version is not specified, `v5` will be used as the default.
121+
// The scopes from the API
122+
$twitch_scopes = $data->scope;
123+
} catch (Exception $e) {
124+
//TODO: Handle Error
125+
}
126+
```
83127

84-
## Features Completed
128+
### Usage of the API Classes
85129

86-
**Main API Endpoints:**
130+
Everything stems from the `NewTwitchApi` class. However, if you want to individually instantiate `UsersApi`, `OauthApi`, etc. you are free to do so.
87131

88-
- [x] Authentication
89-
- [x] Bits
90-
- [x] Channel Feed
91-
- [x] Channels
92-
- [x] Chat
93-
- [x] Clips
94-
- [x] Collections
95-
- [x] Communities
96-
- [x] Games
97-
- [x] Ingests
98-
- [x] Search
99-
- [x] Streams
100-
- [x] Teams
101-
- [x] Users
102-
- [x] Videos
132+
The API calls generally return an object implementing `ResponseInterface`. Since you are getting the full `Response` object, you'll need to handle its contents, e.g. by decoding then into an object with `json_decode()`. This library does not assume this is what you want to do, so it does not do this for you automatically. This library simply acts as a middleman between your code and Twitch, providing you with the raw responses the Twitch API returns.
103133

104-
Any endpoints missing? Open an [issue here](https://github.com/nicklaw5/twitch-api-php/issues).
134+
The individual API classes that can be called from `NewTwitchApi` correspond to the [Twitch API documentation](https://dev.twitch.tv/docs/api/). The rest of the API classes are based on the resources listed [here](https://dev.twitch.tv/docs/api/reference/). The methods in the classes generally correspond to the endpoints for each resource. The naming convention was chosen to try and match the Twitch documentation. Each primary endpoint method (not convenience or helper methods) should have an `@link` annotation with a URL to that endpoint's specific documentation.
105135

106-
## Basic Example
136+
Here is a sample of retrieving a users table from their access token:
107137

108138
```php
109-
$options = [
110-
'client_id' => 'YOUR-CLIENT-ID',
111-
];
112-
113-
$twitchApi = new \TwitchApi\TwitchApi($options);
114-
$user = $twitchApi->getUser(26490481);
115-
116-
// By default API responses are returned as an array, but if you want the raw JSON instead:
117-
$twitchApi->setReturnJson(true);
118-
$user = $twitchApi->getUser(26490481);
119-
120-
// If you want to switch between API versions on the fly:
121-
$twitchApi->setApiVersion(3);
122-
$user = $twitchApi->getUser('summit1g');
123-
```
124-
125-
See the [examples](examples) directory for more common use cases.
126-
127-
## Requirements
139+
$twitch_client_id = 'TWITCH_CLIENT_ID';
140+
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
141+
// Assuming you already have the access token - see above
142+
$twitch_access_token = 'the token';
128143

129-
PHP 7.1 or higher is required.
144+
// The Guzzle client used can be the included `HelixGuzzleClient` class, for convenience.
145+
// You can also use a mock, fake, or other double for testing, of course.
146+
$helixGuzzleClient = new HelixGuzzleClient($twitch_client_id);
130147

131-
## Installation
148+
// Instantiate NewTwitchApi. Can be done in a service layer and injected as well.
149+
$newTwitchApi = new NewTwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
132150

133-
Either pull in the library via composer:
151+
try {
152+
// Make the API call. A ResponseInterface object is returned.
153+
$response = $newTwitchApi->getUsersApi()->getUserByAccessToken($twitch_access_token);
134154

135-
```bash
136-
composer require nicklaw5/twitch-api-php
155+
// Get and decode the actual content sent by Twitch.
156+
$responseContent = json_decode($response->getBody()->getContents());
137157

158+
// Return the first (or only) user.
159+
return $responseContent->data[0];
160+
} catch (GuzzleException $e) {
161+
//TODO: Handle Error
162+
}
138163
```
139164

140-
or add the following dependency to your `composer.json` file and run `composer install`:
141-
142-
```json
143-
"nicklaw5/twitch-api-php": "~1.0"
144-
```
165+
## Developer Tools
145166

146-
## Tests
167+
### PHP Coding Standards Fixer
147168

148-
All unit tests can be run with the following command:
169+
[PHP Coding Standards Fixer](https://cs.sensiolabs.org/) (`php-cs-fixer`) has been added, specifically for the New Twitch API code. A configuration file for it can be found in `.php_cs.dist`. The ruleset is left at default (PSR-2 at this time). The configuration file mostly just limits it's scope to only the New Twitch API code.
149170

150-
```bash
151-
vendor/bin/phpunit # or simply "phpunit" if you have it installed globally
152-
```
171+
You can run the fixer with `vendor/bin/php-cs-fixer fix`. However, the easiest way to run the fixer is with the provided git hook.
153172

154-
## Documentation
173+
### Git pre-commit Hook
155174

156-
The Twitch API docs can be found [here](https://dev.twitch.tv/docs).
175+
In `bin/git/hooks`, you'll find a `pre-commit` hook that you can add to git that will automatically run the `php-cs-fixer` everytime you commit. The result is that, after the commit is made, any changes that fixer has made are left as unstaged changes. You can review them, then add and commit them.
157176

158-
As for the documentation of this library, that is still on the to-do list. In the meantime, most modern IDEs by default, or through the use of plugins, will provide class property and method auto-completion. Or you can simple look through the [source](src) code.
177+
To install the hook, go to `.git/hooks` and `ln -s ../../bin/git/hooks/pre-commit`.
159178

160179
## License
161180

0 commit comments

Comments
 (0)