I am using Abraham Williams' oAuth library to update a status. The application does not have a UI (other than the prompt from Twitter for credentials. Instead, the user enters a URL in the browser.
When the URL is called, I get an error: "Could not post Tweet. Error: Reason: 1".
I inserted some test code, and it seems as if the session is getting lost in between transitions: $_SESSION['tweetmsg'] is set on initial call in index.php, but then when the switch to connect.php happens, it seems as if the session is lost. Any ideas?
Following is the source code:
index.php
<?php
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
session_start();
if (empty($_SESSION['access_token'])) {
$_SESSION['tweetmsg'] = create_tweet_text();
print "<script>self.location='./connect.php');</script>";
}
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
if (!isset($_SESSION['tweetmsg'])) {
exit('No tweet value in session or from form');
}
$tweetmsg = $_SESSION['tweetmsg'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
echo 'Tweet Posted: '.$tweetmsg;
}
else {
echo 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
session_destroy();
}
function create_tweet_text () {
return 'this is a test';
}
connect.php
?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK.'callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
print "<script>self.location='$url';</script>";
callback.php
<?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
$_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
print "<script>self.location='index.php';</script>";
}
Recently Twitter deactivated a number of http urls for oAuth and replaced them with https equivalents. If you can see the URL string http://twitter.com/oauth/request_token in the includes then it means you need to follow https://dev.twitter.com/discussions/10803 and change all the calls to https...
Related
How can I get about a Laravel route if the request is a get or post?
I try to test my laravel routes with the following
public function testRoutes()
{
$app = app();
$routes = $app->routes->getRoutes();
/**
* Test if mynamespace routes are redirected to login page if is not the login page
*/
echo PHP_EOL;
foreach ($routes as $route) {
if(strpos($route->getName(),'mynamespace::' ) !== false ) {
$url = $route->uri;
//$appURL = env('APP_URL') .'/';
$response = $this->get($url);
if((int)$response->status() !== 200 ){
echo $url . ' (FAILED) did not return 200. The response is ' . $response->status();
$this->assertTrue(false);
} else {
echo $url . ' (success ?)';
$this->assertTrue(true);
}
echo PHP_EOL;
}
}
}
but I would like exclude post requests for the moment
As we can see the Route class has a property $methods.
Your solution would look something like:
if (in_array('POST', $route->methods)) continue;
It may be interesting for you to look into the testing provided by Laravel itself. A simple way of testing response testing and much more!
Laravel testing.
This is my composer.json:
{
"require": {
"google/apiclient": "1.0.*#beta"
}
}
And this is my code:
<?
$path = get_include_path() . PATH_SEPARATOR . 'C:\wamp\www\gCalendar\vendor\google\apiclient\src';
set_include_path($path);
define("APIKEY","AIxxxxxxxWA");
define("CLIENTID","xxxkqt.apps.googleusercontent.com");
define("CLIENTSECRET","xxxx");
define("DEVELOPERKEY","xxx.apps.googleusercontent.com");
require_once("config.php");
require_once("vendor/autoload.php");
session_start();
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('CalendarTest');
$client->setClientId(CLIENTID);
$client->setClientSecret(CLIENTSECRET);
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(APIKEY); // API key
// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
echo 'Hello, world.';
?>
I have returned this error:
( ! ) Fatal error: Class 'Google_AnalyticsService' not found in C:\wamp\www\gCalendar\index.php on line 21
What I am doing wrong including the library with Composer?
Thank you so much
The class Google_AnalyticsService does not exist in that library. Try Google_Service instead.
$service = new Google_Service($client);
I know this is old, but I see no answer, and there is not enough about this out there... Does setting the scope to 'https://www.googleapis.com/auth/analytics' help?
All scopes found here:
https://developers.google.com/identity/protocols/googlescopes
<?php
session_start();
$_SESSION = [];
require_once 'vendor/autoload.php';//Composer generated autoload.php(not Google/autoload.php)
$google_api_key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
$clientID = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.apps.googleusercontent.com";
$clientSecret = "AAAAAAAAAAAAAAAAAAAAAAAA";
$scriptUri = "https://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('MYAPPNAME');
$client->setClientId($clientID );
$client->setClientSecret($clientSecret);
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey($google_api_key);
$client->addScope('https://www.googleapis.com/auth/analytics');
$service = new Google_Service($client);
if (isset($_GET['logout']))
{
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token']))
{
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken())
{
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
echo 'Hello, world.';
?>
The class used to exists and still get copy pasted along.
Use Google_Service_Analytics now.
In version ^2.0 use like this
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
...
I'm trying to modify the
'Token Interceptor' system plugin
by joomunited.com
The original plugin redirects on encountering an invalid token error using register_shutdown_function.
I'm trying to get it to:
Log the user out if they are logged in
Redirect to the login page with the invalid token message
Code:
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect('/index.php', JText::_('JINVALID_TOKEN'), 'warning');
I can successfully log the user out and redirect to the login page but the error message is not being displayed.
How can I retain the message after logging the user out?
i've also tried:
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
but that didn't work either...
The solution I came up with was a variation of Alonzo Turner's 2nd post here.
The plugin redirects to the login page with a parameter passed in the url. The onAfterInitialise event then looks for this parameter and displays a message if it's found.
class PlgSystemTokeninterceptor extends JPlugin
{
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$app = JFactory::getApplication();
if (($app->isSite() && $this->params->get('use_frontend')) || ($app->isAdmin() && $this->params->get('use_backend')))
{
register_shutdown_function(array($this,'redirectToLogin'));
}
}
public function redirectToLogin()
{
$content = ob_get_contents();
if($content == JText::_('JINVALID_TOKEN') || $content == 'Invalid Token')
{
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect(JURI::base().'index.php?invalid_token=true');
return false;
}
}
function onAfterInitialise()
{
$app = JFactory::getApplication();
$invalid_token = $app->input->get('invalid_token', 'false');
if ($invalid_token == 'true')
{
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
}
return true;
}
}
When you logout you destroy the session so you are not going to have the message any more.
This will get you a message on redirect.
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
//$app->logout();
$app->redirect($this->redirect);
}
This will not because the session is destroyed
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
$app->logout();
$app->redirect($this->redirect);
}
Not tested but
$app->logout()
echo '<div class="">'. JText::_('whatever you want') . '</div>';
$module = JModuleHelper::getModule('login');
$output = JModuleHelper::renderModule($module);
Something like that
I am trying to make a call to get data from Google Analytics.
<?php
require_once 'lib/apiClient.php';
require_once 'lib/contrib/apiAnalyticsService.php';
session_start();
$client = new apiClient();
$service = new apiAnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
try {
$data = $service->data_ga->get('ga:29214712', '2012-01-01', '2012-01-15',
'ga:visits', array('dimensions' => 'ga:source,ga:keyword', 'sort' =>
'-ga:visits,ga:source', 'filters' => 'ga:medium==organic', 'max-results' => '25'));
}
catch (apiServiceException $e) {
echo $e->getCode();
print_r($data);
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
After Wrapping the code in the TRY Catch Block i am getting the following error
403
Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A29214712&start-date=2012-01-01&end-date=2012-01-15&metrics=ga%3Avisits: (403) Forbidden
( ! ) Notice: Undefined variable: data in
C:\wamp\www\gitgrow\index.php on line 43
Note: I have granted the permission and have forced the Profile ID to test it.
The 403 error you're getting means the authorized user doesn't have access to the ga:29214712 reporting profile that is defined in your query.
Take a look at the HelloAnalyticsAPI.php sample in the examples/analytics/demo directory, and make sure you can connect to the API:
http://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fanalytics%2Fdemo
Also, take a look at the Google Analytics developer guide. It will describe how you can obtain the correct profile IDs:
https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports
I have a default CodeIgniter 2.1 install with Magento 10.4.4 installed in a subdir called store.
The following code works when run from web root (with .htaccess disabled). It will give the firstname, lastname of the logged in Magento user.
<?php
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
?>
But, if I run this in a CodeIgniter model, then isLoggedIn returns false.
Here is the CodeIgniter page:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
}
}
CodeIgniter is doing something that I have not been able to track yet. The websiteId is returned correctly, but isLoggedIn returns false.
Anyone have any ideas? THANKS!!
I use both but ive never tried to mash them like that. I foresee quite a few problems.
How are you patching into magento?
You might need two db connections running :
$db['magento']
$db['default'] // codeigniter default
Sessions could become a real problem here also aswell as config data.
Consider sticking with magento for now, then maybe patch into your blog/website via a RESTFul service.
Both code examples above work fine. The problem I had was calling session_start() near the top of the CodeIgniter index.php file. Once that was removed, it all started working.
For posterity, here is a Magento 10 Library for CodeIgniter 2.1:
application/libraries/magento.php
<?php if ( ! defined('BASEPATH')) exit("No direct script access allowed");
Class Magento {
function __construct($params)
{
global $site_root;
$name = $params['name'];
// Include Magento application
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
// Uncomment next line if you have moved app/etc
// $options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options=null);
return Mage::getSingleton("core/session", array("name" => $name));
}
}
// end of magento.php
Usage example app/model/test_mage.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
$params = array('name' => 'frontend'); // frontend or adminhtml
$this->load->library('magento', $params);
}
public function index()
{
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if ($session->isLoggedIn())
{
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}
else
$magento_message .= 'Guest!';
echo $magento_message . '<br>';
}
}
// end of test_mage.php