我正在尝试通过Wordpress中的twitter api对用户进行身份验证。
基于此示例,php重定向可以按我的意愿进行工作: https://github.com/tutsplus/tuts-twitter-oauth
现在,我正在尝试在Wordpress中实现此功能,并且在执行重定向时遇到了一些问题。我需要的是: 1.一个用于处理登录并重定向到callback.php页面的文件(login.php 2. callback.php收集用户信息 这些登录信息使用$ _SESSION传递,对于登录和回调,我都有两个php函数。由于这两个函数都使用重定向,并且wp_redirect必须位于add_action挂钩中,所以我想知道如何实现此目标。
我有完成所有这些操作的基本代码,但是我使用的是短代码,这不是一个好主意,因为重定向无法以这种方式工作。 无论如何,我都会发布此代码,因此您可能会更好地了解我在做什么:
<?php
require_once 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
ini_set('display_errors', 1);
$GLOBALS['config'] = require_once 'config.php';
function login_user() {
session_start();
$config = $GLOBALS['config'];
// create TwitterOAuth object
$twitteroauth = new TwitterOAuth($config['consumer_key'], $config['consumer_secret']);
// request token of application
$request_token = $twitteroauth->oauth(
'oauth/request_token', [
'oauth_callback' => $config['url_callback']
]
);
// throw exception if something gone wrong
if($twitteroauth->getLastHttpCode() != 200) {
throw new \Exception('There was a problem performing this request');
}
// save token of application to session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// generate the URL to make request to authorize our application
$url = $twitteroauth->url(
'oauth/authorize', [
'oauth_token' => $request_token['oauth_token']
]
);
// and redirect
header('Location:'. $url);
# wp_redirect( $url );
# exit;
}
function callback_user($config) {
session_start();
$config = $GLOBALS['config'];
print('---------------');
print_r($_SESSION);
print('---------------');
// get and filter oauth verifier
$oauth_verifier = filter_input(INPUT_GET, 'oauth_verifier');
// check tokens
if (empty($oauth_verifier) ||
empty($_SESSION['oauth_token']) ||
empty($_SESSION['oauth_token_secret'])
) {
// something's missing, go and login again
header('Location: ' . $config['url_login']);
}
// print_r($_SESSION);
// connect with application token
$connection = new TwitterOAuth(
$config['consumer_key'],
$config['consumer_secret'],
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
// request user token
$token = $connection->oauth(
'oauth/access_token', [
'oauth_verifier' => $oauth_verifier
]
);
// connect with user token
$twitter = new TwitterOAuth(
$config['consumer_key'],
$config['consumer_secret'],
$token['oauth_token'],
$token['oauth_token_secret']
);
$user = $twitter->get('account/verify_credentials');
// if something's wrong, go and log in again
if(isset($user->error)) {
header('Location: ' . $config['url_login']);
}
print_r( $user);
}
function ta_login_shortcode() {
ob_start();
login_user();
return ob_get_clean();
}
function ta_callback_shortcode() {
ob_start();
callback_user();
return ob_get_clean();
}
add_shortcode( 'user_callback_ta', 'ta_callback_shortcode' );
add_shortcode( 'user_login_ta', 'ta_login_shortcode' );
?>