Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is PHP program to get OAuth token for WordPress REST API.
<!DOCTYPE html>
<html lang="ja">
<meta charset="UTF-8"/>
<title>Get WordPress OAuth Token</title>
# 自分の環境に応じて書き換える。
# 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);
$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->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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.