Skip to content

Instantly share code, notes, and snippets.

@modder2
Last active July 9, 2022 19:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save modder2/09caaef602ddf30db5bb417398aa7cae to your computer and use it in GitHub Desktop.
Save modder2/09caaef602ddf30db5bb417398aa7cae to your computer and use it in GitHub Desktop.
Get Yahoo OAuth2 refresh token from console (server-side installed application flow) on PHP

Get Yahoo OAuth2 refresh token

This PHP script helps you to get OAuth2 refresh token from console for your Yahoo API app (server-side installed application flow), e.g. for Yahoo Gemini or Yahoo Social APIs apps.

The access token expires but the refresh token doesn't, and should be stored for later use. Using the refresh token you can get a new access token.

See Explicit Grant Flow in Yahoo OAuth 2.0 Guide.

Step 1. Creating OAuth2 credentials

Follow the first step from the guide to generate a Client ID and Client Secret, then come back to this page.

Step 2. Getting OAuth2 refresh token

  1. Save YahooGetRefreshToken.php to your machine.

  2. In a terminal, navigate to YahooGetRefreshToken.php.

  3. Run this file via the command line.

    This is an interactive example, which will require you to provide input. It will not run properly in a web browser.

    $ php YahooGetRefreshToken.php 
    Please input your client ID and secret. If you do not have a client ID or secret, please create one in your Apps: https://developer.yahoo.com/apps/
    Enter your client ID: ***********
    Enter your client secret: ***********
    Log in to your Yahoo account and open the following URL:
    https://api.login.yahoo.com/oauth2/request_auth?client_id=***********&redirect_uri=oob&language=en-us&response_type=code
    
  4. The file will prompt you to visit a URL where you will need to allow the OAuth2 credentials to access your Yahoo account on your behalf. Navigate to the URL in a private browser session or an incognito window. Log in with the same Yahoo account you use to access API app. Click Agree on the OAuth2 consent screen.

  5. An authorization code will be shown to you. Copy and paste the verification code into the command line where you're running the YahooGetRefreshToken.php example and press enter. The example should complete and display a refresh token.

    After approving the token enter the authorization code here: ****
    
    Your refresh token is: ***********
    
  6. Store this refresh token and use it to get an access token in your applications.

<?php
/**
* This example will print out an OAuth2 refresh token for Yahoo APIs.
*/
/**
* Example class to access Yahoo OAuth2 protected APIs, based on https://developer.yahoo.com/oauth2/guide/
* Find documentation and support on Yahoo Developer Network: https://developer.yahoo.com/forums
*/
class YahooOAuth2
{
const AUTHORIZATION_ENDPOINT = 'https://api.login.yahoo.com/oauth2/request_auth';
const TOKEN_ENDPOINT = 'https://api.login.yahoo.com/oauth2/get_token';
/**
* Make an API request.
*
* @param string $url Endpoint URL.
* @param array $data Post data.
* @param string $auth Basic authorization, "username:password" string.
* @param array $headers HTTP headers.
* @return string
* @throws Exception
*/
public function fetch($url, array $data = null, $auth = null, array $headers = null)
{
$curl = curl_init($url);
if ($data) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
} else {
curl_setopt($curl, CURLOPT_POST, false);
}
if ($auth) {
curl_setopt($curl, CURLOPT_USERPWD, $auth);
}
if ($headers) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if (empty($response)) {
// some kind of an error happened
$message = curl_error($curl);
curl_close($curl); // close cURL handler
throw new Exception($message);
} else {
$info = curl_getinfo($curl);
curl_close($curl); // close cURL handler
if ($info['http_code'] != 200 && $info['http_code'] != 201) {
$message = 'Received error: ' . $info['http_code'] . PHP_EOL .
'Raw response: ' . $response;
throw new Exception($message);
}
}
return $response;
}
/**
* Get an authorization URL.
*
* @param string $client_id Consumer Key.
* @param string $redirect_uri Yahoo redirects Users to this URL after they authorize access to their private data.
* If the user should not be redirected to your server, you should specify the callback as "oob" (out of band).
* @param string $language Language identifier. Default value is "en-us".
* @return string
*/
public function getAuthorizationUrl($client_id, $redirect_uri, $language = 'en-us')
{
return static::AUTHORIZATION_ENDPOINT . '?' . http_build_query([
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'language' => $language,
'response_type' => 'code',
]);
}
/**
* Get refresh token by authorization code.
*
* @param string $client_id Consumer Key.
* @param string $client_secret Consumer Secret.
* @param string $redirect_uri Yahoo redirects Users to this URL after they authorize access to their private data.
* If your application does not have access to a browser, you must specify the callback as "oob" (out of band).
* @param string $code Authorization code.
* @return string
* @throws Exception
*/
public function getRefreshToken($client_id, $client_secret, $redirect_uri, $code)
{
$url = static::TOKEN_ENDPOINT;
$data = [
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$auth = $client_id . ':' . $client_secret;
$response = $this->fetch($url, $data, $auth);
// Convert the result from JSON format to a PHP object
$token = json_decode($response);
return $token->refresh_token;
}
}
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
return;
}
try {
$stdin = fopen('php://stdin', 'r');
print('Please input your client ID and secret. '
. 'If you do not have a client ID or secret, please create one in '
. 'your YDN Apps: https://developer.yahoo.com/apps/'
. PHP_EOL);
print('Enter your client ID: ');
$client_id = trim(fgets(STDIN));
print('Enter your client secret: ');
$client_secret = trim(fgets(STDIN));
$oauth2client = new YahooOAuth2();
$redirect_uri = 'oob'; // out of band - don't redirect
// Get the authorization URL for the OAuth2 authorization code.
// "oob" redirect URL is being used since this is an installed application.
// A web application would pass in a redirect URL back to the application,
// ensuring it's one that has been configured in the YDN App.
$authorization_url = $oauth2client->getAuthorizationUrl($client_id, $redirect_uri);
// In a web application you would redirect the user to the authorization URL
// and after approving the token they would be redirected back to the
// redirect URL, with the URL parameter "code" added. For desktop
// or server applications, spawn a browser to the URL and then have the user
// enter the authorization code that is displayed.
printf('Log in to your Yahoo account and open the following URL:' .
PHP_EOL . '%s' . PHP_EOL . PHP_EOL, $authorization_url);
print 'After approving the token enter the authorization code here: ';
$stdin = fopen('php://stdin', 'r');
$code = trim(fgets($stdin));
fclose($stdin);
print PHP_EOL;
// Get the refresh token using the authorization code. Ensure you use the same
// redirect URL used when requesting authorization.
$token = $oauth2client->getRefreshToken($client_id, $client_secret, $redirect_uri, $code);
printf('Your refresh token is: %s' . PHP_EOL . PHP_EOL, $token);
} catch (Exception $e) {
printf('An error has occurred: %s' . PHP_EOL, $e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment