Skip to content

Instantly share code, notes, and snippets.

@taroyabuki
Last active December 14, 2015 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taroyabuki/5100803 to your computer and use it in GitHub Desktop.
Save taroyabuki/5100803 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Twitter OAuth Post</title>
</head>
<body>
<?php
session_start();
$consumerKey = 'Consumer Key';
$consumerSecret = 'Consumer Secret';
$callbackUrl = 'http://localhost/twitter/twitter-1click-post.php';
$oauth = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
if (substr(PHP_OS, 0, 3) == 'WIN') {//XAMPP(いいかげん)
$caPath = 'C:/xampp/perl/vendor/lib/Mozilla/CA/';
$caInfo = "${caPath}cacert.pem";
$oauth->setCAPath($caPath, $caInfo);
}//On Ubuntu, /etc/ssl/certs/ca-certificates.crt is loaded automatically.
if (!isset($_SESSION['access_token'])) {
if (!isset($_GET['oauth_token'], $_GET['oauth_verifier'])) {//OAuth
$request_token = $oauth->getRequestToken('https://api.twitter.com/oauth/request_token', $callbackUrl);
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$authUrl = 'https://api.twitter.com/oauth/authenticate?oauth_token=' . $_SESSION['oauth_token'];
echo("<script>top.location.href='$authUrl';</script>");
} else {//コールバック
$oauth->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $oauth->getAccessToken('https://api.twitter.com/oauth/access_token?oauth_verifier'.$_GET['oauth_verifier']);
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
$_SESSION['access_token'] = $access_token;
header("Location: $callbackUrl"); //トークン隠すための転送(オプショナル)
}
} else {//投稿
$access_token = $_SESSION['access_token'];
$oauth->setToken($access_token['oauth_token'], $access_token['oauth_token_secret']);
$message = 'テスト at ' . time();
$parameters = array('status' => $message);
$oauth->fetch('https://api.twitter.com/1.1/statuses/update.json', $parameters, OAUTH_HTTP_METHOD_POST);
echo htmlspecialchars($oauth->getLastResponse(), ENT_QUOTES, 'UTF-8');
session_destroy();
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment