PHP - Twitpic And Oauth. Please Help.
Hello guys, I am trying my best to upload images to Twitpic by using PHP and OAuth (PECL extension) and I keep getting "Could not authenticate you (header rejected by twitter)".
Can someone tell me what am I doing wrong? This is my code so far: $arguments[] = "oauth_consumer_key=" . $this->consumer_key; $arguments[] = "oauth_nonce=" . md5(time()); $arguments[] = "oauth_signature_method=HMAC-SHA1"; $arguments[] = "oauth_timestamp=" . time(); $arguments[] = "oauth_token=" . $this->oauth_token; $arguments[] = "oauth_version=1.0"; $sbs = oauth_get_sbs("POST", "http://api.twitpic.com/2/upload.xml", $arguments); $signature = urlencode(base64_encode(hash_hmac("sha1", $sbs, $this->consumer_secret . "&", true))); $arguments[] = "oauth_signature=" . $signature; sort($arguments); $headers[] = "X-Auth-Service-Provider: http://api.twitter.com/1/account/verify_credentials.json"; $headers[] = "X-Verify-Credentials-Authorization: OAuth\n" . implode(",\n", $arguments); $postfields["key"] = $this->api_key; $postfields["media"] = "@$image"; $postfields["message"] = $message; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://api.twitpic.com/2/upload.xml"); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_VERBOSE, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); echo curl_exec($curl); Kind regards and thanks in advance. Similar TutorialsHi all, I've got a bit of a problem with the Twitpic Api v2 upload. I'll post my code below. The picture with the message uploads to Twitpic, but it's not being posted to Twitter. Anyone have any ideas or experience with this? Thanks. Code: [Select] <?php include 'EpiCurl.php'; include 'EpiOAuth.php'; include 'EpiTwitter.php'; include 'secret.php'; require 'class-xhttp-php/class.xhttp.php'; xhttp::load('profile,oauth'); $arvin = new xhttp_profile(); $arvin->oauth($consumer_key, $consumer_secret, $_COOKIE['oauth_token'], $_COOKIE['oauth_token_secret']); // Generate OAuth Header $authorization = $arvin->get_oauth_header('https://api.twitter.com/1/account/verify_credentials.json'); $data = array(); $data['headers'] = array( 'X-Auth-Service-Provider' => 'https://api.twitter.com/1/account/verify_credentials.json', 'X-Verify-Credentials-Authorization' => $authorization, ); $data['post'] = array( 'key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx', # Twitpic App API key 'message'=> $message, # Twitter status ); $data['files'] = array( 'media' => $image_url, ); $response = xhttp::fetch('http://api.twitpic.com/2/upload.xml', $data); if($response['successful']) { echo $response['body']; } else { print_r($response); } ?> Hi, I found a very nice script for saving my TwitPic images in full size. I have tested this script for a couple of times yesterday and it seems that this way of saving images is now blocked by amazon or TwitPic. Using the API it's not possible to download the images as fas I can see, does anyone has an idea ? http://forrst.com/posts/TwitPic_Hack_Get_Full_TwitPic_Image_using_PHP-mFQ Code: [Select] <?php function imgResize($width, $height, $target) { if ($width > $height) { $percentage = ($target / $width); } else { $percentage = ($target / $height); } $width = round($width * $percentage); $height = round($height * $percentage); return "width=\"$width\" height=\"$height\""; } // full url of the TwitPic photo $url = "http://twitpic.com/1pfhfd"; // make the cURL request to TwitPic URL $curl2 = curl_init(); curl_setopt($curl2, CURLOPT_URL, $url); curl_setopt($curl2, CURLOPT_AUTOREFERER, true); curl_setopt($curl2, CURLOPT_RETURNTRANSFER,true); curl_setopt($curl2, CURLOPT_TIMEOUT, 10); $html = curl_exec($curl2); $HttpCode = curl_getinfo($curl2, CURLINFO_HTTP_CODE); $totalTime = curl_getinfo($curl2, CURLINFO_TOTAL_TIME); // if the HTTPCode is not 200 - you got issues if ($HttpCode != 200) { ?><p>Unable to connect to TwitPic. Please try again later.</p><? } else { // if you are not getting any HTML returned, you got another issue. if ($html == "") { ?><p>Yikes! TwitPic is experiencing heavy load. Please close this window and try again.</p><? } else { $dom = new DOMDocument(); @$dom->loadHTML($html); // grab all the on the page $xpath = new DOMXPath($dom); $hrefs = $xpath->evaluate("/html/body//img"); foreach( $hrefs as $href ) { $url = $href->getAttribute('id'); // for all the images on the page find the one with the ID of photo-display if ($url == "photo-display") { // get the SRC attribute of the element with the ID of photo-display $image = $href->getAttribute('src'); // get the image size $imagesize = getimagesize($image); ?> <a href="<? echo $url; ?>" target="_blank"><img class="twitpic" src="<? echo $image; ?>" "<? echo imgResize($imagesize[0], $imagesize[1], 450); ?>"></a> <? break; } } } } ?> Is anyone able to get this https://github.com/csrui/oauth2-php oAuth PDO example to work? I cannot see where to enter the DB details. Thanks in advance. Good day Campers!
Having spent the better part of my day trawling the internet for an answer I have gotten nowhere so have come to you lovely people for help.
I found a nice little tutorial on PHP gang that would allow me to update my twitter feed from my website using PHP and OAuth.
I set up my twitter app with no issues and generated the API keys. Set the App to 'read/write' permissions and then regenerated the keys
The app is marked to "Allow this application to be used to Sign in with Twitter"
The issue is that when I click the little button to sign in to twitter, the page redirects but displays the generic "Cannot connect to Twitter" error message that has been defined in the code. I do not get asked to "Allow" the script to connect to twitter like it seems to do in the demo.
The PHPGang solution has 4 bits of script so I'm wondering if it has something to do with this as I understand the Abrahams script has slightly more so I do wonder if something is missing. I'm not sure. One of the main problems I am facing is that I have never actually done this before so I don't know where I have gone wrong or what I am even looking for help wise......
I have the following scripts:
callback.php
<?php /** * Take the user when they return from Twitter. Get access tokens. * Verify credentials and redirect to based on response from Twitter. */ session_start(); require_once('oauth/twitteroauth.php'); require_once('config.php'); if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) { $_SESSION['oauth_status'] = 'oldtoken'; header('Location: ./destroysessions.php'); } $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']); //save new access tocken array in session $_SESSION['access_token'] = $access_token; unset($_SESSION['oauth_token']); unset($_SESSION['oauth_token_secret']); if (200 == $connection->http_code) { $_SESSION['status'] = 'verified'; header('Location: ./index.php'); } else { header('Location: ./destroysessions.php'); } ?>config.php <?php /** * @file * A single location to store configuration. */ define('CONSUMER_KEY', 'MY CONSUMER KEY'); define('CONSUMER_SECRET', 'MY SECRECT CONSUMER KEY'); define('OAUTH_CALLBACK', 'URL OF WHERE I AM REDIRECTING TO'); ?>destroysessions.php <?php /** * @file * Clears PHP sessions and redirects to the connect page. */ /* Load and clear sessions */ session_start(); session_destroy(); /* Redirect to page with the connect to Twitter option. */ header('Location: ../index.php'); ?>index.php <?php require_once('oauth/twitteroauth.php'); require_once('config.php'); if(isset($_POST["status"])) { $status = $_POST["status"]; if(strlen($status)>=130) { $status = substr($status,0,130); } $access_token = $_SESSION['access_token']; $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); $connection->post('statuses/update', array('status' => "$status")); $message = "Tweeted Sucessfully!!"; } if(isset($_GET["redirect"])) { $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); $request_token = $connection->getRequestToken(OAUTH_CALLBACK); $_SESSION['oauth_token'] = $token = $request_token['oauth_token']; $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; switch ($connection->http_code) { case 200: $url = $connection->getAuthorizeURL($token); header('Location: ' . $url); break; default: echo '<div class="par">Could not connect to Twitter. Refresh the page or try again later.</div>'; } exit; } if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) { echo '<a href="./index.php?redirect=true"><img src="./images/lighter.png" alt="Sign in with Twitter"/></a>'; } else { echo "<a href='destroysessions.php'>Logout</a><br>"; echo '<div class="par">'.$message.'<div> <form action="index.php" method="post"> <input type="text" name="status" id="status" placeholder="Write a comment...."> <input type="submit" value="Post On My Wall!" style="padding: 5px;"> </form>'; } ?>Now, I am unsure if there is anything wrong with the API keys I have generated or if there is something missing. Is there anyone who can point me in the right direction or offer some advice on where to turn? Thanks! Edited by lauren_etherington, 04 September 2014 - 10:36 AM. I try to modify a twitter application, but I have no idea what I'm doing, this is my code so far: require 'Zend/Oauth/Consumer.php'; $token = unserialize($usersClass->twitterToken()); if(!empty($token)) { $client = $token->getHttpClient($config); $client->setUri('http://twitter.com/users/profile_image/twitter.json'); $client->setParameterGet('screen_name', $screen_name); $client->setMethod(Zend_Http_Client::GET); $response = $client->request(); } I want to get the twitter profile image, but I think it's too difficult for me... Hi guys, I am building my new web-service in a way that makes it use its own API (like Twitter is now). However I have no idea and cannot find a helpful resource on how to turn oAuth 2 (PHP) into an Authentication method and not just for authorizing the display of content. Any and all help is much appreciated. Cheers in advance Been fighting with this for awhile. Finally needed to seek advice. I have a URL setup to go to facebook and get information. It's just a standard link... Code: [Select] a href="https://www.facebook.com/dialog/oauth?client_id=CLIENTIDHERE&redirect_uri=http://www.website.com/facebook_connect.php?response_type=token">Facebook Connect</a></p> That ends up sending them back to my receiver script. I have it laid out as follows: Code: [Select] <?php /* Facebook OAuth Procedures */ $app_id = APPIDHERE; $app_secret = SECRETKEYHERE; $code = $_REQUEST["code"]; $url = 'https://graph.facebook.com/me?access_token=' . $code; $user = json_decode(file_get_contents($url)); echo("Hello " . $user->name); ?> That should be very simple. The link takes them to facebook. This part works. If they are logged in and have approved it, it then takes them to my receiver URL. If they are not logged in, it prompts for login, or if they decline and then it takes them to a failure page at that point. So all of that works. Now this receiver page also receives the code back from the previous URL. That all works fine. However, when I try to get to the graph to get the user data, it returns "File Get Contents" and a bad request message. That doesn't make any sense. According to the Facebook API Documentation this is suppose to be how you get the data back. But in this situation I don't even need there name. The only data I need is the Facebook userid so I can match that up with my database and find a connection, then log them into my system. Any advice on why this is not working? Hi, I'm trying to integrate my web based application with facebook. First of all, I created page login/facebook which redirects user to the URL: Code: [Select] https://www.facebook.com/dialog/oauth?client_id=MY_ID&redirect_uri=https://www.domain.com/connect/facebook&scope=email,user_about_me,user_location So far so good. Have no problems at this stage. If user authorize my application, he gets redirected to the www.domain.com/connect/facebook page. On this page I create user in my database using data returned by FB or just authorize user and create session. On this step I have issues. When I use code from the examples from Facebook Developers Help Page everything works: Code: [Select] $token_url = "https://graph.facebook.com/oauth/access_token?client_id=" . $this->app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $this->secret . "&code=" . $code; $access_token = file_get_contents($token_url); $graph_url = "https://graph.facebook.com/me?" . $access_token; $user_object = json_decode(file_get_contents($graph_url)); When I use following snippet everything works perfectly. However I prefer to use PHP-SDK and having problems. When I use following snippet: Code: [Select] $session = $this->facebook->getSession(); var_dump($session); if( $session ) { try { $uid = $this->facebook->getUser(); $me = $this->facebook->api('/me'); var_dump('me'); } catch (FacebookApiException $e) { error_log($e); } }session is null. After having some fun with PHP-SDK I noticed some funny stuff: When I use SDK getLoginUrl() method to generate redirect URL, it seems to be partially working. Code: [Select] $login_url = $this->facebook->getLoginUrl( array( 'api_key' => $this->api_key, 'req_perms' => 'email,user_work_history,user_about_me,user_location', 'next' => 'https://www.domain.com/connect/facebook' ) ); Now when users authorizes my app, he's being redirected to correct page with some params, URL looks like: Code: [Select] https://www.domain.com/connect/facebook?session={"session_key"%3A"11111111111-111111111"%2C"uid"%3A"11111111"%2C"expires"%3A0%2C"secret"%3A"111111111"%2C"base_domain"%3A"domain.com"%2C"access_token"%3A"1111111|222222.0-33333|sdvsdvsdvsdvsdv"%2C"sig"%3A"gsdbsdbsdbsdbsdbsdbsdb"} Anyone has any idea why it's not hashes or it shouldn't? Or should I leave php-sdk and use the way with file_get_contents()? This is the code im using to try to connect Empire Avenue API but i must be missing somthing here still trying to figure out all this Oauth stuff.
<?php ?> <html> <head>Empire Traider2</head> <body> <form method="post" action="https://www.empireavenue.com/profile/developer/authorize?client_id=app_543abbac2ad99&response_type=code&state=request_access_token"> <input type="submit" value="Login" /> </form> </body> </html>Oauth.php <?php require('client.php'); require('GrantType/IGrantType.php'); require('GrantType/AuthorizationCode.php'); const CLIENT_ID = 'app_543abbac2ad99'; const CLIENT_SECRET = '1ee4b7f5d702d2c7e64523daf4d107b3dd82a0a787f117986d84f'; const REDIRECT_URI = 'https://yousearch.mobi/OAuth2/oauth.php'; const AUTHORIZATION_ENDPOINT = 'http://www.empireavenue.com/profile/developer/authorize'; const TOKEN_ENDPOINT = 'https://api.empireavenue.com/oauth/token'; $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); parse_str($response['result'], $info); $client->setAccessToken($info['access_token']); $response = $client->fetch('https://api.empireavenue.com/profile/info'); echo $response; echo 'test'; } ?>Here are the docs http://www.empireave...elopers/apidocs Can someone please help me in setting up OAuth server and client implementation in PHP? Even after lots of googling I could only find very basic and raw examples which are very difficult to understand. Thanks in advance. |