Undefined index: oauth_token using Consolibyte QuickBooks PHP DevKit - php

I am using the Quickbooks PHP DevKit from github.com/consolibyte/quickbooks-php
Am getting the following error page after clicking on Connect to Quickbooks icon:
Notice: Undefined index: oauth_token in
/srv/disk14/2290833/www/qbstream.scienceontheweb.net/QuickBooks/IPP/IntuitAnywhere.php
on line 468
Notice: Undefined index: oauth_token_secret in
/srv/disk14/2290833/www/qbstream.scienceontheweb.net/QuickBooks/IPP/IntuitAnywhere.php
on line 468
Notice: Undefined index: oauth_token in
/srv/disk14/2290833/www/qbstream.scienceontheweb.net/QuickBooks/IPP/IntuitAnywhere.php
on line 485
Warning: Cannot modify header information - headers already sent by
(output started at
/srv/disk14/2290833/www/qbstream.scienceontheweb.net/QuickBooks/IPP/IntuitAnywhere.php:468)
in
/srv/disk14/2290833/www/qbstream.scienceontheweb.net/QuickBooks/IPP/IntuitAnywhere.php
on line 443
I added some print statements to index.php to show that the SQL database is connecting and storing variables from my edited config.php:
http://qbstream.scienceontheweb.net/docs/partner_platform/example_app_ipp_v3/index.php
mcrypt php extension is installed, you can run phpinfo.php at the above url
Attached are my development keys and development settings at developer.intuit.com (pic of settings appended to keys as I am allowed only 2 links in this post):
dev keys & settings
Here is my config.php
<?php
/**
* Intuit Partner Platform configuration variables
*
* See the scripts that use these variables for more details.
*
* #package QuickBooks
* #subpackage Documentation
*/
// Turn on some error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Require the library code
require_once dirname(__FILE__) . '/../../../QuickBooks.php';
//require_once('/home/www/qbstream.scienceontheweb.net/QuickBooks.php');
// Your application token (Intuit will give you this when you register an Intuit Anywhere app)
$token = '99cbe16bba521b4f25b99cbb4ad297910a33';
// Your OAuth consumer key and secret (Intuit will give you both of these when you register an Intuit app)
//
// IMPORTANT:
// To pass your tech review with Intuit, you'll have to AES encrypt these and
// store them somewhere safe.
//
// The OAuth request/access tokens will be encrypted and stored for you by the
// PHP DevKit IntuitAnywhere classes automatically.
$oauth_consumer_key = 'qyprdq1tdxuG9uvFFY4dQnNWtrA8a3';
$oauth_consumer_secret = 'qKK95MELeifFxcxuy7zeApvtncRcQfYtmYS9TCHi';
// If you're using DEVELOPMENT TOKENS, you MUST USE SANDBOX MODE!!! If you're in PRODUCTION, then DO NOT use sandbox.
$sandbox = true; // When you're using development tokens
//$sandbox = false; // When you're using production tokens
// This is the URL of your OAuth auth handler page
//$quickbooks_oauth_url = 'http://quickbooks.v3.com:8888/quickbooks-php/docs/partner_platform/example_app_ipp_v3/oauth.php';
$quickbooks_oauth_url = 'http://qbstream.scienceontheweb.net/docs/partner_platform/example_app_ipp_v3/oauth.php';
// This is the URL to forward the user to after they have connected to IPP/IDS via OAuth
//$quickbooks_success_url = 'http://quickbooks.v3.com:8888/quickbooks-php/docs/partner_platform/example_app_ipp_v3/success.php';
$quickbooks_success_url = 'http://qbstream.scienceontheweb.net/docs/partner_platform/example_app_ipp_v3/success.php';
// This is the menu URL script
//$quickbooks_menu_url = 'http://quickbooks.v3.com:8888/quickbooks-php/docs/partner_platform/example_app_ipp_v3/menu.php';
$quickbooks_menu_url = 'http://qbstream.scienceontheweb.net/docs/partner_platform/example_app_ipp_v3/menu.php';
// This is a database connection string that will be used to store the OAuth credentials
// $dsn = 'pgsql://username:password#hostname/database';
// $dsn = 'mysql://username:password#hostname/database';
$dsn = mysqli_connect("etc,etc,etc,etc");
// You should set this to an encryption key specific to your app
$encryption_key = 'bcde1234';
// Do not change this unless you really know what you're doing!!! 99% of apps will not require a change to this.
$the_username = 'DO_NOT_CHANGE_ME';
// The tenant that user is accessing within your own app
$the_tenant = 12345;
// Initialize the database tables for storing OAuth information
if (!QuickBooks_Utilities::initialized($dsn))
{
// Initialize creates the neccessary database schema for queueing up requests and logging
QuickBooks_Utilities::initialize($dsn);
}
// Instantiate our Intuit Anywhere auth handler
//
// The parameters passed to the constructor are:
// $dsn
// $oauth_consumer_key Intuit will give this to you when you create a new Intuit Anywhere application at AppCenter.Intuit.com
// $oauth_consumer_secret Intuit will give this to you too
// $this_url This is the full URL (e.g. http://path/to/this/file.php) of THIS SCRIPT
// $that_url After the user authenticates, they will be forwarded to this URL
//
$IntuitAnywhere = new QuickBooks_IPP_IntuitAnywhere($dsn, $encryption_key, $oauth_consumer_key, $oauth_consumer_secret, $quickbooks_oauth_url, $quickbooks_success_url);
// Are they connected to QuickBooks right now?
if ($IntuitAnywhere->check($the_username, $the_tenant) and
$IntuitAnywhere->test($the_username, $the_tenant))
{
// Yes, they are
$quickbooks_is_connected = true;
// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);
// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
QuickBooks_IPP::AUTHMODE_OAUTH,
$the_username,
$creds);
if ($sandbox)
{
// Turn on sandbox mode/URLs
$IPP->sandbox(true);
}
// Print the credentials we're using
//print_r($creds);
// This is our current realm
$realm = $creds['qb_realm'];
// Load the OAuth information from the database
$Context = $IPP->context();
// Get some company info
$CompanyInfoService = new QuickBooks_IPP_Service_CompanyInfo();
$quickbooks_CompanyInfo = $CompanyInfoService->get($Context, $realm);
}
else
{
// No, they are not
$quickbooks_is_connected = false;
}
Please help me connect to intuit. Thank you.

Related

QuickBooks PHP API - Can't get through the oAuth process again

First off: I'm using https://github.com/consolibyte/quickbooks-php
I accidentally disconnected the APP from the "Apps" page in an attempt to reconnect (get new auth creds), but it appears that was a mistake.
So now I'm trying to go through the authorization process again but I'm getting an error when I click the "Connect to QuickBooks" button on the "docs/example_app_ipp_v3/" page as described in the Quick-Start guide.
Is there something I'm missing here? I can still query through the API explorer, but I can't seem to get any data back when I use $InvoiceService->query in the code (just returns false).
//get invoice info
require_once '../includes/quickbooks-php/config.php';
// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);
// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
//error_reporting(0);
//ini_set('display_errors', 1);
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
QuickBooks_IPP::AUTHMODE_OAUTH,
$the_username,
$creds);
// This is our current realm
$realm = $creds['qb_realm'];
// Load the OAuth information from the database
if ($Context = $IPP->context())
{
// Set the IPP version to v3
$IPP->version(QuickBooks_IPP_IDS::VERSION_3);
$CustomerService = new QuickBooks_IPP_Service_Customer();
$InvoiceService = new QuickBooks_IPP_Service_Invoice();
$ItemService = new QuickBooks_IPP_Service_Item();
$PaymentService = new QuickBooks_IPP_Service_Payment();
$invoice_query = $InvoiceService->query($Context, $realm, "SELECT *, Line.* FROM Invoice WHERE Id = '" .QuickBooks_IPP_IDS::usableIDType($main_invoice['qb_invoice_id']). "'");
$this_invoice = array();
var_dump($invoice_query);
if (count($invoice_query)){
foreach ($invoice_query as $Invoice){
//do stuff with invoice here
}
}
}
I'm getting bool(false) from the var_dump($invoice_query) even though it gets through the if($Context = $IPP->context())
Then when I visit the "docs/example_app_ipp_v3/" page with nothing but the config updated to my current auth credentials the "Connect to Quickbooks" button (html below) takes me to the 404 page.
<ipp:connecttointuit>Connect with QuickBooks</ipp:connecttointuit>
Are you POSITIVE that your App Token and other credentials are correct in the config.php file? If they are sandbox/dev tokens, please post the config file.
Are you POSITIVE that the URLs in your configuration file are correct? If they are sandbox/dev, please post them.
Is $sandbox set to TRUE or FALSE? Does that correspond to the tokens you're using?

Google Admin SDK PHP cannot create user. Not Authorized

I'm having a problem implementing Google Admin SDK in PHP. It always give error
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST
https://www.googleapis.com/admin/directory/v1/users: (403) Not Authorized to access this
resource/api' in ..\google-api-php-client\src\Google\Http\REST.php on line 79
Here is my code :
<?php
session_start();
/* * **********************************************
Make an API request authenticated with a service
account.
* ********************************************** */
set_include_path("google-api-php-client/src" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Directory.php';
/* * **********************************************
ATTENTION: Fill in these values! You can get
them by creating a new Service Account in the
API console. Be sure to store the key file
somewhere you can get to it - though in real
operations you'd want to make sure it wasn't
accessible from the webserver!
The name is the email address value provided
as part of the service account (not your
address!)
Make sure the Books API is enabled on this
account as well, or the call will fail.
* ********************************************** */
$client_id = 'my_client_id'; //Client ID
$service_account_name = 'email'; //Email Address
$key_file_location = 'key.p12'; //key.p12
if ($client_id == '<YOUR_CLIENT_ID>' || !strlen($service_account_name) || !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("appname");
$service = new Google_Service_Directory($client);
/* * **********************************************
If we have an access token, we can carry on.
Otherwise, we'll get one with the help of an
assertion credential. In other examples the list
of scopes was managed by the Client, but here
we have to list them manually. We also supply
the service account
* ********************************************** */
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array('https://www.googleapis.com/auth/admin.directory.user'), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/* * **********************************************
We're just going to make the same call as in the
simple query as an example.
* ********************************************** */
$familyName = filter_input(INPUT_GET, 'familyname');
$givenName = filter_input(INPUT_GET, 'givenname');
$password = filter_input(INPUT_GET, 'password');
$primaryEmail = filter_input(INPUT_GET, 'email');
$user = new Google_Service_Directory_User();
$name = new Google_Service_Directory_UserName();
$name->setFamilyName($familyName);
$name->setGivenName($givenName);
$user->setName($name);
$user->setHashFunction("MD5");
$user->setPrimaryEmail($primaryEmail);
$user->setPassword(hash("md5", $password));
$result = $service->users->insert($user);
There is no documentation and I'm very confused with this error.
I had a similar problem until I set the "sub" account on the credentials object which is the email address for the administrative user that you want to perform the API action as.
So in Google Apps Admin for your domain I assume you've created a user and added them to and admin role that has API access to users right? In your code above you just need to add (with correct email address of course):
$cred->sub = "adminuser#domain.com";
Add that right before:
$client->setAssertionCredentials($cred);
I did a full example for someone else that you might be able to reference too: https://gist.github.com/fillup/9fbf5ff35b337b27762a
I had a similar problem but found a solution to this by going through this blog
http://michaelseiler.net/2014/12/16/google-admin-sdk-api-with-php/
Assuming you have done all the necessary setting up on the Admin Console (i.e. delegating domain authority), then pay particular attention to the line
`$cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/admin.directory.user'), $key);`
this should be:
`$user_to_impersonate = 'adminaccount#example.com';$scopes =array('https://www.googleapis.com/auth/admin.directory.user');$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
$scopes,
$key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate);`
I changed that and boom....
I think i was receiving this error when i tried to query a user.
During the creation of the JWT_CLAIM portion of the assertion, you must specify a domain admin account that your service account can impersonate... this part was poorly documented, i thought.
i dont know exactly how the google php library does it, but i didnt see anywhere in your code where you specify that account email address. if you have looked at the oauth2 documentation, in the jwt_claim secion, there is an "additional claims" subsection that says:
To obtain an access token that grants an application delegated access to a resource, include the email address of the user in the JWT claim set as the value of the sub field.
I had to include that admin email account in the creation of my assertion before i could even query the directory.users API.
i apologize if this isnt helpful, but im not using the library for php, im building my own (with php).

twitter API unable to retrieve token

Hi I'm making an app which post tweets to users time lines after they have authenticated. I'm using the library and tutorial found here : twitteroauth
Everything works fine until I get to the callback url and attempt to retrieve the access token and a var dump of the request returns Invalid request token .
here's the code :
function authenicateApp() {
//Set app keys
// Connect to twitter and recive token
$connection = new TwitterOAuth('**', '**');
$temporary_credentials = $connection->getRequestToken('http://abc.def.com');
// Redirect to twitter authentation page
header('location:'.$connection->getAuthorizeURL($temporary_credentials));
}
function appPost() {
$connection1 = new TwitterOAuth('**' ,'**', $_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']);
var_dump($connection1->getAccessToken($_REQUEST['oauth_verifier']));
}
You have to actually have $temporary_credentials to the session before you try and use the session when you create $connection1.

google service account authentication with google-api-php-client using calendar api

i am using php 5.3.3, and codeigniter 2.1.0.
what i want to do is set up a service account, so a user can add an appointment in a text entry field on my website, then have that appointment added to a shared shared google calendar.
i have a google account, and using : https://code.google.com/apis/console I created a new project called 'pqp'
on services: enabled the calendar api
on api access: i created an oath 2.0 client id… product name = pqp, application type = service account.
downloaded the key 46… -privatekey.p12. there is a screenshot of the settings:
I got an svn checkout of the google-api-php-client (28/6/2012)
In the google-api-php-client/src/config.php I changed lines:
25: 'application_name' => 'pqp',
28: 'oauth2_client_id' => '373xxx730.apps.googleusercontent.com',
57: 'ioFileCache_directory' => 'tmp/apiClient', // my apache user does not have access to the system /tmp folder. + tmp/apiClient has permissions of 777 on the server.
using this link:
http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php?spec=svn445&r=395
I modified it to:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller{
function __construct()
{
parent::__construct();
}
function index()
{
set_include_path(get_include_path() . PATH_SEPARATOR .dirname(__FILE__).'/../libraries/google-api-php-client/src');
ini_set('error_reporting',E_ALL);
ini_set('display_errors','1');
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
define('CLIENT_ID','3731xxx44730.apps.googleusercontent.com');
define('SERVICE_ACCOUNT_NAME','373xxx244730#developer.gserviceaccount.com');
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
define('KEY_FILE',dirname(__FILE__).'/../../461290xxx796c0b7db9582c-privatekey.p12');
require_once "apiClient.php";
require_once "contrib/apiCalendarService.php";
$client = new apiClient();
$client->setApplicationName("pqp");
// Set your cached access token. Remember to replace $_SESSION with a
// real database or memcached.
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
echo 'client access token is set.<br/>';
}
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$key = file_get_contents(KEY_FILE);
$creds = new apiAssertionCredentials(SERVICE_ACCOUNT_NAME,array('https://www.googleapis.com/auth/calendar'),$key);
$client->setAssertionCredentials($creds);
$client->setClientId(CLIENT_ID);
$service = new apiCalendarService($client);
echo 'client:<br/>';
var_dump($client);
echo 'service:<br/>';
var_dump($service);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
echo 'token is good!, so creating an event....';
echo $this->insert_event($service,'testing summary','my location','2012-06-29T10:00:00.000+10:00','2012-06-29T10:00:00.000+10:00');
}
}
function insert_event($service,$summary,$location,$from,$to){
$event = new Event();
$event->setSummary($summary);
$event->setLocation($location);
$start = new EventDateTime();
$start->setDateTime($from);
$event->setStart($start);
$end = new EventDateTime();
$end->setDateTime($to);
$event->setEnd($end);
$attendee1 = new EventAttendee();
$attendee1->setEmail('test#example.com');
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
return $createdEvent->getId();
}
}
a pastie of the output is here:
the $client object is not authenticated, the getAccessToken is not set, and the event is not inserted.
i have found it difficult to work out which settings in the $config file to change because there is different nomenclature. i guess this is an artifact of how the code has progressed.
are the settings in src/config.php correct? do i need to alter any more settings?
it is my understanding that if i create the service account, download the key file, and the contents of this file with my developer id, it should return a token, and there is no need to set up a redirection uri.. is that correct? this is the functionality i want. i don't want the user to have to authorise access because the website will only ever interact with one google account.
So, the question is, how do i get this calendar api to authenticate using a google service account?
You can try this one if you not already...
EDIT: this one intresting but if you still feel like to write one yourself then try this THE mother of the oauth2. helpful
About Service Account at google-api-php-client that you use(always take the trunk's one with SVN) I can't found in that code manipulations any reference apiAssertionCredentials::generateAssertion()
definitely there is no call to auth in there
public function __construct(
$serviceAccountName,
$scopes,
$privateKey,
$privateKeyPassword = 'notasecret',
$assertionType = 'http://oauth.net/grant_type/jwt/1.0/bearer',
$prn = false) {
$this->serviceAccountName = $serviceAccountName;
$this->scopes = is_string($scopes) ? $scopes : implode(' ', $scopes);
$this->privateKey = $privateKey;
$this->privateKeyPassword = $privateKeyPassword;
$this->assertionType = $assertionType;
$this->prn = $prn;
}
and this method should be called I guess...
public function generateAssertion() {
$now = time();
$jwtParams = array(
'aud' => apiOAuth2::OAUTH2_TOKEN_URI,
'scope' => $this->scopes,
'iat' => $now,
'exp' => $now + self::MAX_TOKEN_LIFETIME_SECS,
'iss' => $this->serviceAccountName,
);
if ($this->prn !== false) {
$jwtParams['prn'] = $this->prn;
}
return $this->makeSignedJwt($jwtParams);
}
EDIT:
Pardon. In fresh ver. look's like it's Google_OAuth2::refreshTokenWithAssertion() actualy who should start the real proces

PHP/Twitter oAuth - Automated Tweets

Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back from them.
What the script below attempts to do is 'cache' the request_token and request_secret. So in theory I should be able to reuse those details (all 4 of them to automatically tweet when required).
<?php
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
$consumer_key = CONSUMER_KEY;
$consumer_secret = CONSUMER_SECRET;
if (isset($_GET["register"]))
{
// If the "register" parameter is set we create a new TwitterOAuth object
// and request a token
/* Build TwitterOAuth object with client credentials. */
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request = $oauth->getRequestToken();
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
// At this I store the two request tokens somewhere.
file_put_contents("request_token", $request_token);
file_put_contents("request_token_secret", $request_token_secret);
// Generate a request link and output it
$request_link = $oauth->getAuthorizeURL($request);
echo "Request here: " . $request_link . "";
die();
}
elseif (isset($_GET["validate"]))
{
// This is the validation part. I read the stored request
// tokens.
$request_token = file_get_contents("request_token");
$request_token_secret = file_get_contents("request_token_secret");
// Initiate a new TwitterOAuth object. This time we provide them with more details:
// The request token and the request token secret
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$request_token, $request_token_secret);
// Ask Twitter for an access token (and an access token secret)
$request = $oauth->getAccessToken();
// There we go
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
// Now store the two tokens into another file (or database or whatever):
file_put_contents("access_token", $access_token);
file_put_contents("access_token_secret", $access_token_secret);
// Great! Now we've got the access tokens stored.
// Let's verify credentials and output the username.
// Note that this time we're passing TwitterOAuth the access tokens.
$oauth = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token, $access_token_secret);
// Send an API request to verify credentials
$credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());
// Parse the result (assuming you've got simplexml installed)
$credentials = simplexml_load_string($credentials);
var_dump($credentials);
// And finaly output some text
echo "Access token saved! Authorized as #" . $credentials->screen_name;
die();
}
?>
When i run /?verify&oauth_token=0000000000000000 - It works however trying to resuse the generated tokens etc... I get a 401
Here is the last bit of code where I attempt to reuse the details from Twitter combined with my consumer_key and consumer_secret and get the 401:
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
$access_token, $access_token_secret);
// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
array('status' => "Hey! I'm posting via #OAuth!"), 'POST');
Not sure whats going wrong, are you able to cache the details or do i need to try something else?
You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.
That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.
twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts)
The image below describes the flow of the OAuth authentication.
Hope it helps.
A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.
require_once 'Zend/Service/Twitter.php';
class Twitter {
protected $_username = '<your_twitter_username>';
protected $_token = '<your_twitter_access_token>';
protected $_secret = '<your_twitter_access_token_secret>';
protected $_twitter = NULL;
//class constructor
public function __construct() {
$this->getTwitter();
}
//singleton twitter object
protected function getTwitter() {
if (null === $this->_twitter) {
$accessToken = new Zend_Oauth_Token_Access;
$accessToken->setToken($this->_token)
->setTokenSecret($this->_secret);
$this->_twitter = new Zend_Service_Twitter(array(
'username' => $this->_username,
'accessToken' => $accessToken,
));
$response = $this->_twitter->account->verifyCredentials();
if ($response->isError()) {
throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
}
}
return $this->_twitter;
}
//send a status message to twitter
public function update( $tweet ) {
$this->getTwitter()->status->update($tweet);
}
}
In your second script, it looks like you aren't setting the Consumer Key and Consumer Secret when you create your TwitterOAuth instance.
// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);

Categories