PHP code example of codexshaper / php-oauth2

1. Go to this page and download the library: Download codexshaper/php-oauth2 library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codexshaper / php-oauth2 example snippets


composer 

use CodexShaper\OAuth2\Server\Http\Controllers\RefreshTokenController;
use CodexShaper\OAuth2\Server\Models\User;
use League\OAuth2\Server\Exception\OAuthServerException;

// Step 1
try {
	
	$user = User::find(1);
	$authorize = new AuthorizationController;
	$authRequest = $authorize->authorize($user);
    
} catch (OAuthServerException $exception) {

    return $exception->generateHttpResponse($response);
    
}

// Redirect to callback if skip authorization is true

$client = new Client;

if($client->isSkipsAuthorization()) {

	$headers = $authRequest->getHeaders();
	$locations = $headers['Location'];

	foreach ($locations as $location) {
		header('Location: ' . $location);
	}
	die();
}

// If skip authorization is false then display html button to choose approve or deny. First set authRequest in your session to retrieve later for access token

session_start();

	$_SESSION['authRequest'] = $authRequest;

$html = <<<HTML
	<!DOCTYPE html>
	<html>
		<head>
			<title></title>
		</head>
		<body>
			<form>
				<a href="http://site.com/approve.php?action=approve">Approve</a>
				<a href="http://site.com/approve.php?action=deny">Deny</a>
			</form>
		</body>
	</html>
HTML;

echo $html;

// approve.php
// You need to setup database before call any request

if(isset($_SESSION['authRequest']) && $_REQUEST['action'] === 'approve') {
	try {

		$user = User::find(1);

		$authorize = new AuthorizationController;
		$authRequest = $_SESSION['authRequest'];

		var_dump($authRequest);

		$response = $authorize->approve($authRequest, $user);

		$headers = $response->getHeaders();
		$locations = $headers['Location'];

		foreach ($locations as $location) {
			header('Location: ' . $location);
		}
		die();

		session_destroy();

	} catch(\Exception $ex) {

	}
}

if (isset($_GET['code'])) {
	// call part 2. Here I used guzzle http request

	$code = urldecode($_GET['code']);
	$http = new GuzzleHttp\Client;

	$response = $http->post('http://site.com/oauth/access_token', [
	    'form_params' => [
	        'grant_type' => 'authorization_code',
	        'client_id' => 'CLIENT_ID',
	        'client_secret' => 'CLIENT_SECRET',
	        'code' => $code,
	    ],
	]);

	$data = json_decode((string) $response->getBody(), true);

	var_dump($data);
}