PHP commandline OAuth authorization for JIRA

I needed to get a user’s OAuth credentials from the commandline, for some commandline tools to work (Drush).

You will need OAuth installed from PECL for this, and have an OAuth link set up in JIRA (or whatever OAuth provider you are using).

// Set up the OAuth client.
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_SIG_METHOD_RSASHA1, OAUTH_AUTH_TYPE_URI);

// cert.pem is the certificate you generated for the OAuth link.
$oauth->setRSACertificate(file_get_contents("cert.pem"));

// Get a request token so we can tell the user to visit a page.
$tokens = $oauth->getRequestToken(OAUTH_REQUEST_URL, 'oob', 'POST');
$oauth_token = $tokens['oauth_token'];
$oauth_token_secret = $tokens['oauth_token_secret'];
$oauth->setToken($oauth_token, $oauth_token_secret);
print "Go to: " . OAUTH_AUTHORIZE_URL . "?oauth_token=$oauth_token\n";

// Get the authorization code from the user.
$code = readline('Enter the authorization code');
$access_token = $oauth->getAccessToken(OAUTH_ACCESS_URL, NULL, $code, 'POST');
$oauth->setToken($access_token['oauth_token'], $oauth_token_secret);
$tokens['access_token'] = $access_token['oauth_token'];

// From now on you would just need the access token, and the token secret.
$oauth->setToken($tokens['access_token'], $tokens['oauth_token_secret']);
$oauth->fetch("https://protected-url.com/resource");
$content = $oauth->getLastResponse();