PHP code example of jvandemo / zendservice-oauth2

1. Go to this page and download the library: Download jvandemo/zendservice-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/ */

    

jvandemo / zendservice-oauth2 example snippets


use ZendService\Oauth2\Client\Client;

// Create configuration
$config = array(

    // Oauth2 client options
    'client' => array(
        'client_id' => 'your_client_id',
	    'client_secret' => 'your_client_secret',
	    'authorization_url' => 'https://api.youwishtoconnect.to/authorize',
	    'access_token_url' => 'https://api.youwishtoconnect.to/access_token',
	    'redirect_uri' => 'http://www.yourwebsite.com/where_to_go_after_authorization',
	    'state' => 'somerandomstate',
    ),
    
    // Http client options
    'http' => array(
        'adapter'   => 'Zend\Http\Client\Adapter\Curl',
        'curloptions' => array(
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_SSL_VERIFYPEER => false,
        ),
    ),
);

// Create a new Oauth2.0 client and pass in the config
$client = new Client($config);

// Let the client build the authorization request for you:
$url = $client->getAuthorizationRequestUrl()

// Redirect the user to the authorization request url:
return $this->redirect()->toUrl($url);

// Grab the access token from the authorization response:
$code = $_GET['code'];

// Use the authorization code to get an access token: 
$accessToken = $client->getAccessToken(array(
	'code' => $code
));

// Create a client
$client = new Client($config);

// Get the token from your backend e.g. with unserialize
$accessToken = getAccessTokenFromYourBackend(); // Replace with your custom function

and perform GET requests
$response = $client->get('http://api.youwishtoconnect.to/some_endpoint', array('access_token' => $accessToken->getAccessToken()));

// or POST requests
$response = $client->post('http://api.youwishtoconnect.to/some_endpoint', array('access_token' => $accessToken->getAccessToken()));

// Some third parties e.g. Linkedin 

// Print the response body
echo $response->getBody()