I watch this video to learn how to post a tweet to Twitter account using PHP. I grab the PHP he give in the video description & add my Application & Access Token details inside the script.
This is my code.
<?php
$the_tweet = 'hello';
// TWITTER API ==================
$consumerKey = 'qu...xF';
$consumerSecret = 'it...hG';
$oAuthToken = '24...ub';
$oAuthSecret = 'oy...d2';
include "OAuth.php";
include "twitteroauth.php";
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
if (isset($the_tweet)) {
$tweetmsg = $the_tweet;
$tweet->post('statuses/update',array('status' => $tweetmsg));
echo "Your message has been sent to Twitter.";
} else {
echo "Your message has not been sent to Twitter.";
}
// END TWITTER API ==================
?>
The github repo for this script is here ('OAuth.php' and 'twitteroauth.php' files inside the 'twitteroauth' folder).
MY PROBLEM
When I run my code with localhost (using MAMP), the tweet successfully sent to my Twitter account.
But, when I put it on my web hosting account and run the code, the tweet not sent to my Twitter account even I still get the success message like below.
How to fix this problem? Why the tweet is not sent and only sent successfully in localhost mode?
This is my Application & Token Access details (it's same like in my code):
Related
I'm creating an AI Assistant using Dialogflow and I need to use Google APIs (google calendar and gmail). The APIs were working perfectly (I used this as reference). However, when I integrated my code with the dialogflow webhook, it returns Webhook Call failed. Error: 500 Internal Server Error.
here is a code snippet:
$client = new Google_Client();
$client->addScope(Google_Service_Gmail::GMAIL_READONLY); //view your emails and settings
$client->addScope(Google_Service_Gmail::GMAIL_COMPOSE); //manage drafts and send emails
$client->addScope(Google_Service_Gmail::GMAIL_MODIFY);
$client->addScope(Google_Service_Gmail::GMAIL_SEND); //send email on your behalf
$client->addScope(Google_Service_Calendar::CALENDAR); //manage calendar
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('auto');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_SESSION['access_token']) && $_SESSION['access_token']){
$client->setAccessToken($_SESSION['access_token']);
$gmail = new Google_Service_Gmail($client);
$user = "emailaddress#gmail.com";
$calendar = new Google_Service_Calendar($client);
$intent = $json->queryResult->intent->displayName;
$location_any = $json->queryResult->parameters->location_any;
$text = $json->queryResult->parameters->text;
$name = $json->queryResult->parameters->name;
$choice = $json->queryResult->parameters->choice;
$subject = $json->queryResult->parameters->subject;
$location = $json->queryResult->parameters->location;
$description = $json->queryResult->parameters->description;
$startDateTime = $json->queryResult->parameters->startDateTime;
$endDateTime = $json->queryResult->parameters->endDateTime;
if($intent== "UnreadMessages"){
$unread = unReadMessages($gmail, $user);
$speech = "You have ".$unread." messages";
}
else if($intent == "GetSchedule"){
$events = get_event($calendar);
if($events){
$reply = "You have the following events coming up:";
foreach($events as $event){
$eventName = $event['eventName'];
$eventTime = $event['time'];
$reply .= $eventName."is at".$eventTime;
}
$speech = $reply;
}
else{
$speech = "You don't have any events coming up.";
}
}
}
I'm suspecting it may be because of the authentication process that's required everytime I try to run the app, since the error only starts popping up whenever I check for session tokens. My problem now is how do I remove this authentication process?
You have several serious issues with your approach here, but most of them result from you treating the interaction with the Google Assistant like it was a browser hitting your web page. Although Actions on Google uses HTTPS and a webhook, it is otherwise not really like a browser at all.
For example, you check $_SESSION to see if an access token has already been set. $_SESSION is typically implemented by setting a session ID in the browser with a session cookie. The Assistant doesn't use cookies at all. Although it has a userStorage object which can be used it similar ways, this is accessed very differently.
It isn't clear if this is what is causing the error, or if the problem is related here somewhere. If you do have error logs, this would be useful to include in the question.
There is a lot that remains unclear. Primarily - where does the auth token come from in the first place in your code.
In a purely web-based OAuth scheme, you'll direct the user to log in using Google Sign In and, as part of that process, request authorization to access their Drive and GMail. Google Sign In for the Assistant doesn't allow you to do that - all it gives you is an Identity Token.
You can use Account Linking to link the Assistant account to your system - but this requires you to have an OAuth server that generates the auth token that the Assistant will give back to you. This is your OAuth token - not one that comes from Google (unless you're proxying it).
If you have a web-based way to get authorization, you can leverage this to provide access through the Assistant as well using Google Sign In for the Assistant.
Recently I have run into a problem with the pinterest api, I am using a library to help me and below is my simple script to authorize my application.
The library I am using is this one
I would ask in there if the problem had anything to do with the library itself which it does not since it was working until i revoked access to test it, since then it never authorizes.
The code redirects me to the login page and shows the right scopes, but when I approve and go to the pinterest page it does not show any authorized apps.
After my main code (below) there is a simple callback page that collects the access token into the database and then shows the user basic info.
Code used to connect:
<?php
session_start();
require "vendor\autoload.php";
use Pinterest\App\Scope;
$client = new Pinterest\Http\BuzzClient();
$auth = new Pinterest\Authentication($client, 'i have my cliend id here', 'i have my client secret here');
$url = $auth->getAuthenticationUrl(
'i have my redirect uri here',
array(
Scope::READ_PUBLIC,
Scope::WRITE_PUBLIC,
Scope::READ_RELATIONSHIPS,
Scope::WRITE_RELATIONSHIPS,
),
'random-string'
);
header('Location: ' . $url);
exit;
?>
<?
// here we want to send the article to twitter
require_once('twitteroauth.php');
// Twitter Connection Data
$tConsumerKey = 'xxxx';
$tConsumerSecret = 'xxxx';
$tAccessToken = 'xxxx';
$tAccessTokenSecret = 'xxxx';
// start connection
$tweet = new TwitterOAuth($tConsumerKey, $tConsumerSecret, $tAccessToken, $tAccessTokenSecret);
// the message
$message = 'Auto Tweet via PHP ...';
// send to twitter
$tweet->post('statuses/update', array('status' => $message));
?>
here is my code .. it does not send post tweet. is it about localhost or something else ?
I'm using xampp on windows7 ..
Which library are you using for OAuth? Is it for an app that you have made or somebody elses?
If you can edit and check the settings on the Twitter developer area, this question about using localhost with your twitter application might be useful for your callback when authenticating your app.
Twitter oAuth callbackUrl - localhost development
I found it useful when wanting to connect apps during development. Using 127.0.0.1.
Im getting started with the php sdk, and struggling to understand a few things (I have a basic example below - but everytime the pic goes to MY wall and not the fan page)
Code:
require_once("facebook.php"); // set the right path
$config = array();
$config['appId'] = 'app id';
$config['secret'] = 'app secret';
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$params = array(
// this is the access token for Fan Page
"access_token" => "I create this via the graph api (select App and click get token), I select publish stream and photo_upload permissions.",
"message" => "test message",
"source" => "#" ."photo.png", // "#" .
);
try {
// **** is Facebook id of Fan page
$ret = $fb->api('/****/photos', 'POST', $params);
echo 'Photo successfully uploaded to Facebook Album';
} catch(Exception $e) {
echo $e->getMessage();
}
the picture keeps going to MY wall (logged in user) and not the fan page, is that because im getting a token for the currently logged in user (me) instead of the fan page? and if so how do i generate a token for the fan page whilst logged in as the developer? (is it by putting the fan page id into the Get bar?)
Apologies for the noob questions but the facebook documentation sucks (until u understand the core functionality of course). Most tutorials work once u know how to use the graph API - none ive looked actually EXPLAIN how to use the graph to generate correct tokens, etc.
\POST /<ID>/photos — this will post on the <ID>'s wall only, so please double-check the <ID> that you are using.
The access token will depict that on behalf of whom the photo would be posted on the <ID>'s wall. If you use the user access token, the photo will be published on behalf of the user and if page access token is used, it will be published on the page's behalf itself.
You can get the page access token of your pages by-
\GET /me/accounts?fields=access_token
(permission required: manage_pages)
Demo
Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.
I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.
I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.
I really appreciate your help.
EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.
this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter
<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
$oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
//necessary to get access token other wise u will not have permision to get user info
$params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
$access_token = $connection->oauth("oauth/access_token", $params);
//now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
$connection = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token['oauth_token'],$access_token['oauth_token_secret']);
$content = $connection->get("account/verify_credentials");
print_r($content);
}
else{
// main startup code
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
//this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
$_SESSION['oauth_token']=$temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
header('Location: ' . $url);
}
?>
I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did
git clone https://github.com/abraham/twitteroauth.git
Upload this into your webhost with domain, say, www.example.com
Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
a) Application Website will be http://www.example.com/twitteroauth
b) Application type will be browser
c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php
Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.
EDIT:
Example will not work but do not worry. Follow the above steps and upload to server.
Make sure you rename the file from github repository i.e. config-sample.php->config.php
if you want to see a working sample, find it here
Here are some OAuth 1.0A PHP libraries with examples:
tmhOAuth
Oauth-php
Twitter async
Twitter async provides documentation on how to simply sign in a user as you asked for.
Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.
http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/
You need to create Twitter App First By going thorugh following URL
https://apps.twitter.com/
Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.
Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.
Abraham's Twitteroauth has a working demo here:
https://github.com/abraham/twitteroauth-demo
Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer
IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.
I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.
Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.
use Abraham\TwitterOAuth\TwitterOAuth;
// Connect
$connection = new TwitterOAuth($twitterConsumerKey, // Your API key
$twitterConsumerSecret, // Your API secret key
$twitterOauthAccessToken, // From your app created at https://developer.twitter.com/
$twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/
// Set API version to 2
$connection->setApiVersion('2');
// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);
if (isset($response['title']) && $response['title'] == 'Unauthorized') {
// Handle error
} else {
var_dump($response);
/*
object(stdClass)#404 (1) {
["data"]=>
object(stdClass)#397 (2) {
["id"]=>
string(19) "0123456789012345678"
["text"]=>
string(13) "Hello Twitter"
}
}
*/
}