smolblog/oauth2-twitter

PHP League OAuth2-Client 的 Twitter OAuth 2.0 客户端提供者

1.1.0 2023-04-15 15:21 UTC

This package is auto-updated.

Last update: 2024-09-15 18:16:45 UTC


README

此软件包为 PHP League 的 OAuth 2.0 客户端提供 Twitter OAuth 2.0 支持。

安装

要安装,请使用 composer

composer require smolblog/oauth2-twitter

用法

用法与 The League 的 OAuth 客户端相同,使用 \Smolblog\OAuth2\Client\Provider\Twitter 作为提供者。

授权码流

<?php
session_start();

require_once 'vendor/autoload.php';

$provider = new Smolblog\OAuth2\Client\Provider\Twitter([
	'clientId'          => 'MjVXMnRGVUN5Ym5lcVllcTVKZkk6MTpjaQ',
	'clientSecret'      => 'YDPiM-JsC5xU44P2VijGJRB7zdKB1PckCGjOynXGx9HZM7N6As',
	'redirectUri'       => 'http://oddevan.test/twitter-test/',
]);

if (!isset($_GET['code'])) {
	unset($_SESSION['oauth2state']);
	unset($_SESSION['oauth2verifier']);
	
	// Optional: The default scopes are ‘tweet.read’, ‘users.read’,
	// and ‘offline.access’. You can change them like this:
	$options = [
		‘scope’ => [
			‘tweet.read’,
			‘tweet.write’,
			‘tweet.moderate.write’,
			‘users.read’,
			‘follows.read’,
			‘follows.write’,
			‘offline.access’,
			‘space.read’,
			‘mute.read’,
			‘mute.write’,
			‘like.read’,
			‘like.write’,
			‘list.read’,
			‘list.write’,
			‘block.read’,
			‘block.write’,
			‘bookmark.read’,
			‘bookmark.write’,
		],
	]; 
		

	// If we don't have an authorization code then get one
	$authUrl = $provider->getAuthorizationUrl($options);
	$_SESSION['oauth2state'] = $provider->getState();

	// We also need to store the PKCE Verification code so we can send it with
	// the authorization code request.
	$_SESSION['oauth2verifier'] = $provider->getPkceVerifier();

	header('Location: '.$authUrl);
	exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

	unset($_SESSION['oauth2state']);
	exit('Invalid state');

} else {

	try {

		// Try to get an access token (using the authorization code grant)
		$token = $provider->getAccessToken('authorization_code', [
			'code' => $_GET['code'],
			'code_verifier' => $_SESSION['oauth2verifier'],
		]);

		// Optional: Now you have a token you can look up a users profile data
		// We got an access token, let's now get the user's details
		$user = $provider->getResourceOwner($token);

		// Use these details to create a new profile
		printf('Hello %s!', $user->getName());

	} catch (Exception $e) {
		echo '<pre>';
		print_r($e);
		echo '</pre>';

		// Failed to get user details
		exit('Oh dear...');
	}

	// Use this to interact with an API on the users behalf
	echo $token->getToken();
}

变更日志

CHANGELOG.md

致谢

作为Smolblog项目的一部分维护。

由于Twitter的新付费API,Smolblog项目已无法可靠地维护此插件。我们将修复我们能解决的问题,但我们无法对新功能做出反应。如果您想接管主动维护,请联系我们。

许可证

修改后的3条款BSD许可证(BSD)。有关更多信息,请参阅许可证文件