Skip to content

Instantly share code, notes, and snippets.

@nosuz
Created June 2, 2016 08:13
Show Gist options
  • Save nosuz/cc48b8a8d44fd283094e1afd33a7feff to your computer and use it in GitHub Desktop.
Save nosuz/cc48b8a8d44fd283094e1afd33a7feff to your computer and use it in GitHub Desktop.
This is PHP program to get OAuth token for WordPress REST API.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8"/>
<title>Get WordPress OAuth Token</title>
</head>
<body>
<?php
require_once('HTTP/OAuth/Consumer.php');
session_start();
# 自分の環境に応じて書き換える。
# depend on your site
$SITE_URL = 'https://WordPressSite';
$SECRET_FILE = "DIR/wp-oauth-key.json";
/*
{
"client_key": "XXXXXXXXXXXXX",
"client_secret": "XXXXXXXXXXXXXXXX",
}
*/
$request_token_endpoint = $SITE_URL . "/oauth1/request";
$authorize_token_endpoint = $SITE_URL . "/oauth1/authorize";
$access_token_endpoint = $SITE_URL . "/oauth1/access";
$callback = "http://localhost:8080/get-oauth-token.php";
# get client token and secret
$io = fopen($SECRET_FILE, "r");
$secret = json_decode(fread($io, filesize($SECRET_FILE)), TRUE);
fclose($io);
$oauth = new HTTP_OAuth_Consumer($secret["client_key"], $secret["client_secret"]);
try {
if (empty($_GET)) {
# first access
# clear session
$_SESSION = [];
# get request token
$oauth->getRequestToken($request_token_endpoint, $callback);
$_SESSION['request_key'] = $oauth->getToken();
$_SESSION['request_secret'] = $oauth->getTokenSecret();
# redirect to authorize page
$auth_url = $oauth->getAuthorizeUrl($authorize_token_endpoint);
header("Location: $auth_url");
print("<a href=\"" . $auth_url . "\">Click me to get WordPress OAuth token</a></br>\n");
} elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])){
# callbacked from OAuth provider
# get access token
$oauth->setToken($_SESSION['request_key']);
$oauth->setTokenSecret($_SESSION['request_secret']);
$oauth->getAccessToken($access_token_endpoint, $_GET['oauth_verifier']);
$secret["access_key"] = $oauth->getToken();
$secret["access_secret"] = $oauth->getTokenSecret();
print "Save this in secret file<br/>";
print "<pre>";
print json_encode($secret, JSON_PRETTY_PRINT);
print "</pre>";
} else {
print "??? エラー ???\n";
}
} catch (Exception $e) {
print $e->getMessage();
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment