nicklaw5/twitch-api-php

PHP 的 Twitch API 客户端。

v7.2.0 2023-06-13 04:20 UTC

README

Packagist Version Packagist PHP Version Support Packagist Downloads Packagist License

Twitch API PHP 库允许您通过 HTTP 与多个 Twitch API 端点交互。库不会格式化您请求的响应,因此您在处理从 API 返回的数据方面有完全的灵活性。

文档与链接

入门

要求

  • PHP 7.4 - 该库已在早期版本上显示可以工作,但我们鼓励您使用经过我们库测试的最新 PHP 版本。 - 未来要求将提升到 PHP 8.0,因此您应该针对 PHP 的最新版本进行开发。
  • Composer
  • ext-json: *
  • guzzlehttp/guzzle ~6.0|~7.0

安装

安装 Twitch API PHP 库的推荐方式是通过 Composer

composer require nicklaw5/twitch-api-php

示例用法

对 Twitch API 的所有调用都需要通过 OauthApi 类检索的承载令牌。您可以在 Twitch API 文档中查看 令牌类型。以下示例将客户端 ID、密钥和作用域直接存储在示例中,但您不应这样做。将您的 ID、密钥和作用域存储在安全的地方,例如数据库或环境变量或备用设置存储。此信息的安全性很重要。以下是如何为您应用程序检索令牌的示例

$twitch_client_id = 'TWITCH_CLIENT_ID';
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
$twitch_scopes = '';

$helixGuzzleClient = new \TwitchApi\HelixGuzzleClient($twitch_client_id);
$twitchApi = new \TwitchApi\TwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
$oauth = $twitchApi->getOauthApi();

try {
    $token = $oauth->getAppAccessToken($twitch_scopes ?? '');
    $data = json_decode($token->getBody()->getContents());

    // Your bearer token
    $twitch_access_token = $data->access_token ?? null;
} catch (Exception $e) {
    //TODO: Handle Error
}

以下是如何检索用户令牌的示例

$twitch_client_id = 'TWITCH_CLIENT_ID';
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
$twitch_scopes = '';

$helixGuzzleClient = new \TwitchApi\HelixGuzzleClient($twitch_client_id);
$twitchApi = new \TwitchApi\TwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
$oauth = $twitchApi->getOauthApi();

// Get the code from URI
$code = $_GET['code'];

// Get the current URL, we'll use this to redirect them back to exactly where they came from
$currentUri = explode('?', 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'])[0];

if ($code == '') {
    // Generate the Oauth Uri
    $oauthUri = $oauth->getAuthUrl($currentUri, 'code', $twitch_scopes);
    // Redirect them as there was no auth code
    header("Location: {$oauthUri}");
} else {
    try {
        $token = $oauth->getUserAccessToken($code, $currentUri);
        // It is a good practice to check the status code when they've responded, this really is optional though
        if ($token->getStatusCode() == 200) {
            // Below is the returned token data
            $data = json_decode($token->getBody()->getContents());

            // Your bearer token
            $twitch_access_token = $data->access_token ?? null;
        } else {
            //TODO: Handle Error
        }
    } catch (Exception $e) {
        //TODO: Handle Error
    }
}

当用户令牌过期时,您可以选择刷新它而不是要求他们再次进行身份验证。以下是如何刷新用户令牌的示例

$twitch_client_id = 'TWITCH_CLIENT_ID';
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
$twitch_scopes = '';
$user_refresh_token = 'REFRESH_TOKEN';

$helixGuzzleClient = new \TwitchApi\HelixGuzzleClient($twitch_client_id);
$twitchApi = new \TwitchApi\TwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);
$oauth = $twitchApi->getOauthApi();

try {
    $token = $oauth->getAppAccessToken($twitch_scopes ?? '');
    $data = json_decode($token->getBody()->getContents());

    // Your bearer token
    $twitch_access_token = $data->access_token ?? null;

    // The scopes from the API
    $twitch_scopes = $data->scope;
} catch (Exception $e) {
    //TODO: Handle Error
}

API 类的使用

一切始于 TwitchApi 类。但是,如果您想分别实例化 UsersApiOauthApi 等,您可以自由这样做。

API 调用通常返回实现 ResponseInterface 的对象。由于您获取了完整的 Response 对象,您需要处理其内容,例如使用 json_decode() 解码成对象。该库不假设您想这样做,因此不会自动为您执行此操作。该库只是作为您代码与 Twitch 之间的中间人,为您提供 Twitch API 返回的原始响应。

TwitchApi 可以调用的单个 API 类与 Twitch API 文档 中的对应。其余的 API 类基于此处列出的资源 此处。类中的方法通常对应于每个资源的端点。命名规范被选择以尽可能匹配 Twitch 文档。每个主要端点方法(非便利或辅助方法)都应该有一个 @link 注解,指向该端点的特定文档的 URL。

以下是从其访问令牌检索用户表的示例

$twitch_client_id = 'TWITCH_CLIENT_ID';
$twitch_client_secret = 'TWITCH_CLIENT_SECRET';
// Assuming you already have the access token - see above
$twitch_access_token = 'the token';

// The Guzzle client used can be the included `HelixGuzzleClient` class, for convenience.
// You can also use a mock, fake, or other double for testing, of course.
$helixGuzzleClient = new \TwitchApi\HelixGuzzleClient($twitch_client_id);

// Instantiate TwitchApi. Can be done in a service layer and injected as well.
$twitchApi = new TwitchApi($helixGuzzleClient, $twitch_client_id, $twitch_client_secret);

try {
    // Make the API call. A ResponseInterface object is returned.
    $response = $twitchApi->getUsersApi()->getUserByAccessToken($twitch_access_token);

    // Get and decode the actual content sent by Twitch.
    $responseContent = json_decode($response->getBody()->getContents());

    // Return the first (or only) user.
    return $responseContent->data[0];
} catch (GuzzleException $e) {
    //TODO: Handle Error
}

开发者工具

PHP 编码标准修复器

PHP 编码标准修复工具 (php-cs-fixer) 已添加,专门用于新的 Twitch API 代码。该工具的配置文件位于 .php_cs.dist 中。规则集设置为默认(目前为 PSR-2)。配置文件主要限制了其范围,仅应用于新的 Twitch API 代码。

您可以使用 vendor/bin/php-cs-fixer fix 命令运行修复工具。然而,使用提供的 git 钩子运行修复工具更为简便。

Git 预提交钩子

bin/git/hooks 目录下,您会发现一个 pre-commit 钩子,将其添加到 git 中后,每次提交时都会自动运行 php-cs-fixer。结果是,提交完成后,修复工具所做的更改将保留为未暂存更改。您可以查看它们,然后添加并提交。

要安装钩子,请转到 .git/hooks 目录并执行 ln -s ../../bin/git/hooks/pre-commit

许可协议

MIT 许可协议下分发。