Using Twitter OAuth for automatic status update - php

I want my website to automatically post status updates to a particular twitter account using OAuth in PHP.
I test this using a URL
www.mysite.com/update_status
but it asks me for "user name" and "password", which is fine when I am testing it. But my website will not be able to insert this user name and password before posting the status update.
So the question is how can a website which is in the server, automatically post a status update to an account without user filling out the user name and password.
Is there any way to bypass this? I tried saving oAuth tokens, but it's not working.
Thank you for your answer in advance!

My recommendation:
1) Use a PHP library like http://github.com/abraham/twitteroauth.
2) Select your app on http://dev.twitter.com/apps and click on "My Access Token".
3) Us that access token as described on http://dev.twitter.com/pages/oauth_single_token.

Just tried this and it WORKS! And its SO SIMPLE to use!!
http://ditio.net/2010/06/07/twitter-php-oauth-update-status/
Got it working in under 5mins.

xAuth is able to do that, but Twitter only allows it for desktop and mobile apps.
In case you wanna try it, read this article and the API docs.

Try it with zend framework. As of version 1.10.8 minimal code required to post on Twitter is:
$token = new Zend_Oauth_Token_Access;
$token->setParams(array(
'oauth_token' => 'REPLACE_WITH_TOKEN',
'oauth_token_secret' => 'REPLACE_WITH_TOKEN_SECRET'
));
$twitter = new Zend_Service_Twitter(array(
'consumerSecret' => 'REPLACE_WITH_CONSUMER_SECRET',
'accessToken' => $token
));
$response = $twitter->status->update('REPLACE WITH MESSAGE');
All tokens and secrets can be accessed after registering your application on http://dev.twitter.com

Related

Bigcommerce customer login api (single sign-on) invalid login issue

I'm new to bigcommerce and jwt tokens. I'm trying to get the customer login api to work on a trail store. But have not been able to successfully login a customer automatically.
I got it to work once or twice, but now it doesn't work anymore, and an unable to figure out the odd behavior since nothing changed with the code. I've tried googling if anyone else has had issues with the customer login api but have found nothing.
I've gone thru the tutorial on https://developer.bigcommerce.com/api/v2/#customer-login-api and copied the example provided.
Is there something I'm missing with the code below?
I've gone to developer.bigcommerce.com and created a draft app.
I got the Client ID and Client Secret from the draft app.
I've gone into my trial store and successfully installed the draft app.
I've tested this page on SSL as well.
Could it be because it's a trail store and it will only work if it's a real store?
Thanks.
Here is the php code below:
include "vendor/autoload.php";
use Bigcommerce\Api\Client as Bigcommerce;
use Firebase\JWT\JWT;
function getCustomerLoginToken($id, $redirectUrl = '', $requestIp = '') {
/*
if (empty(self::$client_secret)) {
throw new Exception('Cannot sign customer login tokens without a client secret');
}
*/
$payload = array(
'iss' => '#MyApp1's Client ID#',
'iat' => time(),
'jti' => bin2hex(random_bytes(32)),
'operation' => 'customer_login',
'store_hash' => '#Store Hash#',
'customer_id' => $id
);
if (!empty($redirectUrl)) {
$payload['redirect_to'] = $redirectUrl;
}
if (!empty($requestIp)) {
$payload['request_ip'] = $requestIp;
}
return JWT::encode($payload, "#MyApp1's Client Secret#", "HS256");
}
$jwt = getCustomerLoginToken(1);
header("Location: " . 'https://store-#Store Hash#.mybigcommerce.com/login/token/' . $jwt);
exit();
There are a couple of constraints that can cause errors:
The app must be installed on the store (seems like you're all good here - you can also test with an API token created locally in the store - https://support.bigcommerce.com/articles/Public/Store-API-Accounts/)
The app must have the Login OAuth scope
The JWT URL must be visited within about 30 seconds, or it won't work.
The computer/server that's generating the JWT needs to have a clock that's synchronized, otherwise your IAT value will appear to have been created more than 30 seconds ago or even in the future which will fail.
The URL can only be visited exactly once - if anything runs a GET request against it other than the intended end user's browser, it won't work. For example, if you send the URL in a Slack message, slack will try to preview the link by visiting it and therefore invalidate it.
It's good to double-check that your JWT is valid at https://jwt.io/
BigCommerce support has access to logs which can shed more light on the situation if you've ruled out the above.
Hope this helps!
do not need app client_id and Secret code , you need to api's client_id and secret code

Firebase PHP CURL Authentication

I currently building a small chat using Firebase and PHP. This, I thought, would be a good learning project for Firebase, and so far I am very happy with it!
However, I have hit a wall. I am not sure how I can implement an authentication system to Firebase via PHP. It's quite specific what I need the authentication system to do:
To be able to use the chat, the user must login using my custom php login system. Then once they are logged in, they will also authenticate to be able to read/write in the chat.
I couldn't really understand how this (if even) is possible with PHP, using CURL.
In my __construct function in have the following:
require('/libs/FirebaseLib.php');
$this->firebase = new fireBase('https://<url>.firebaseio.com');
require('/libs/JWT.php');
require('/libs/FirebaseToken.php');
$tokenGen = new Services_FirebaseTokenGenerator('<firebase-secret>');
$this->authtoken = $tokenGen->createToken(
array(
'id' => $this->userid
)
);
How would I authenticate with Firebase to let the user be able to read/write in my chat and not allow non authenticated user to read/write?
Note: I have not done anything to the Firebase security rules - this is part of my question.
I've looked at the documentation, I might just be very thick, but I couldn't really find what I was looking for.
Hope anyone to point me in the right direction.
Thanks!
EDIT: I have intentionally not been using javascript for my chat, apart from ajax calls to my php script which then relays it to Firebase after I have done what I want to do with the user's messages.
EDIT 2: Added links to the used libraries: "Firebase Token Generator" and "Firebase PHP Client"
EDIT 3: My current code looks like this: (reference)
__construct:
$this->authtoken = JWT::encode(
array(
'admin' => true,
'debug' => true,
'v' => 0,
'iat' => time(),
'd' => array('user' => 'admin')
),
'<secret>',
'HS256'
);
New Message Function:
$response = $this->firebase->set('/chat.json?auth=' . $this->authtoken, array(
'message' => array(
'username' => 'Test',
'time' => time(),
'string' => 'Hello World!'
)
));
However it returns: { "error" : "invalid_token: Could not parse auth token." }. I basically want to get permission as the administrator. I have tried just using the Firebase secret as the auth, but its returns the same error.
Rules:
{
"rules": {
".read": "auth.username == 'admin'",
".write": "auth.username == 'admin'"
}
}
The general workflow would be:
After user has authenticated with your custom login system, generate a Firebase auth token in your server-side PHP code. (it looks like you got this far with the code snippet you pasted).
Pass that token back to the client.
Have the client call firebase.auth(<token>); to authenticate to Firebase using your server-generated token.
Use security rules to restrict what the client can read/write, depending on the contents of their auth token.
For a simple scenario where you just want to allow all Firebase access if they're authenticated, you could just have security rules like:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
This would give authenticated users read/write access to your whole Firebase. You probably want to lock it down more than that though (i.e. only give them read/write access to certain parts of the Firebase). Check out our Security Quickstart for a walkthrough on how auth and security rules work.
If this doesn't help, perhaps you can elaborate on which part you're getting stumped at.

Getting 403 error when trying to update profile description with Soundcloud PHP API

When I try to update the profile description of a soundcloud account via their php sdk, I get a 403 error every time. The app is authenticated and I am able to do things like place comments, but I'm not able to update anything on the profile (particularly the description field).
I'm using the standard code, found in their official documentation:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->post('me', array(
'description' => 'I am using the SoundCloud API!'
)));
print $user->description;
Please help me find out where the error comes from, because I'm all out of ideas.
Our bad, the user documentation that you point to there had two problems:
Updates to the user resource should use the PUT method, not POST.
Arguments need to be namespaced properly.
I've modified the documentation to fix these two problems. New code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->put('me', array(
'user[description]' => 'I am using the SoundCloud API!'
)));
print $user->description;
Hope that helps and sorry again for the confusion. Let me know if you run into any more problems.
To update user related information you need to login to Sound Cloud as user and then authenticate your application to use your personal data, else you will get 403 for all user related information while updating / delete. For posting any comments you don't need this authentication
http://developers.soundcloud.com/docs#authentication
Refer
Getting Information about the Authenticated User
Once the user has signed into SoundCloud and approved your app's authorization request, you will be able to access their profile and act on their behalf. We have provided a convenient endpoint for accessing information about the authenticated user.

Twitter OAuth (PHP): Need good, basic example to get started

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"
}
}
*/
}

Facebook GRAPH API, php SDK problem

it's weird this morning all my facebook applications don't work anymore. And when I use the graph API using request like : "graph.facebook.com/me"
I got :
{
"error": {
"type": "OAuthException",
"message": "An active access token must be used to query information about the current user."
}
}
Any idea?
Facebook did a developer update the past couple days..
http://developers.facebook.com/blog/post/518/
We had problems with the API key on older versions of the sdk, check that.
same thing here. I followed Ben Biddington's blog to get the access token. Same error when trying to use it. Facebook's OAuth implementation doesn't follow the spec completely, i am fine with it as long as the doc is clear, which obviously is not the case here. Aslo, it would be nice if the userid and username are returned with the access token.
You need to create an app so that you can get an appId and secret. Then you can create a facebook object like so:
$fb = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => $cookie
));
and get the access token with $fb->getAccessToken(); this can then be appended to your graph api call url, and it should work.
when you click on facebook button, after login one cookie is generated with fbs_(token_access). by which it understands that you are logged in. may be because you are going directly you dont have sufficient access to get json encoded data..
this can be the problem for you.. make sure when you are loggedd in,cookie is generated ..
As the message states, you need to provide a valid access token. If you aren't providing one, then it obviously is the problem, as you need to have one, even when accessing your own information. If you are providing one, and it gives that error, then the token is not valid, which may be because it has expired or been revoked.

Categories