update with photo in twitter - twitter

Afer tried a lot of times with abraham's code and other, I will read about tmhOauth, but I couldn't update the statuses with a picture. I modified with the 1.1 url this one and it doesn't works. Please somebody could help me? Thanks.
<?php
/**
* Tweets a Twitter photo along with a message from the user whose oauth_token
* and oauth_secret you use.
*
* Although this example uses your user token/secret, you can use
* the oauth_token/secret of any user who has authorised your application.
*
* This example is intended to be run from the command line.
*
* Instructions:
* 1) If you don't have one already, create a Twitter application on
* https://dev.twitter.com/apps
* 2) From the application details page copy the consumer key and consumer
* secret into the place in this code marked with (YOUR_CONSUMER_KEY
* and YOUR_CONSUMER_SECRET)
* 3) From the application details page copy the access token and access token
* secret into the place in this code marked with (A_USER_TOKEN
* and A_USER_SECRET)
* 4) Update $image to point to a real image file on your computer.
* 5) In a terminal or server type:
* php /path/to/here/photo_tweet.php
*
* #author themattharris
*/
require 'tmhOAuth.php';
require 'tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => '*',
'consumer_secret' => '*',
'user_token' => '*',
'user_secret' => '*',
));
// we're using a hardcoded image path here. You can easily replace this with
// an uploaded image - see images.php in the examples folder for how to do this
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
// this is the jpeg file to upload. It should be in the same directory as this file.
$image = '1594816618.jpg';
$code = $tmhOAuth->request(
'POST',
'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image};type=image/jpeg;filename={$image}",
'status' => 'Picture time',
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
?>

I had the same problem. I found that on my server, I had to specify the full file system path (NOT the URL) to the image.
For example, '/home/mydomain/public_html/image.jpg'
As soon as I did that it worked fine.

Related

How can I get JWT with Ruby?

I am currently working on the project that I am going to integrate the application of my company and salesforce.
In my case, it seemed that using the JWT for authentication is better.
So, I wanted to try it.
but I don't know how to generate JWT on Ruby though I researched a lot.
So if anyone knows how to make jwt, I would love you to tell me how to do it.
What I wanted to do is that
1, create application on salesforce (done)
2, create X509 certification and set it on the application on salesforce. (done)
3, create JWT by using the secret key of X509 certification. (don't know how)
I have been looking for the way to solve this but I couldn't.
I guess I should be doing something like this.
require 'jwt'
payload = { data: 'test' }
# The secret must be a string. A JWT::DecodeError will be raised if it isn't provided.
hmac_secret = 'my$ecretK3y'
token = JWT.encode payload, hmac_secret, 'HS256'
# eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y
puts token
decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }
# Array
# [
# {"data"=>"test"}, # payload
# {"alg"=>"HS256"} # header
# ]
puts decoded_token
but this doesn't work on my local.
When I run this file, it says
`require': cannot load such file -- jwt
I think PHP version of what I want to do is this.
<?php
require_once './vendor/autoload.php';
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
// ログインURL
// 本番: https://login.salesforce.com
// Sandbox: https://test.login.salesforce.com
// スクラッチ組織: https://test.saleforce.com
define('LOGIN_URL', 'https://test.salesforce.com');
// コンシューマ鍵
define('CLIENT_ID', <<接続アプリケーションのコンシューマ鍵>>);
// ユーザID
define('USER_ID', 'xxxxx#example.com');
function createjwt() {
$signer = new Sha256();
$privateKey = new Key('file://cert/server.key');
$time = time();
$token = (new Builder())->issuedBy(CLIENT_ID) // iss: コンシューマ鍵
->permittedFor(LOGIN_URL) // aud: SalesforceログインURL
->relatedTo(USER_ID) // sub: SalesforceユーザID
->expiresAt($time + 3 * 60) // exp: 3分以内
->getToken($signer, $privateKey);
return $token;
}
$jwt = createjwt();
echo $jwt;
If you have any clue please help me.
references are here:
https://help.salesforce.com/articleView?id=sf.remoteaccess_oauth_jwt_flow.htm&type=5
https://github.com/jwt/ruby-jwt
It was not the error of JWT but that I couldn't install get properly.
I tried once because of shortage of memory.
and this solved this problem.
gem install jwt
thank you.

eBay OAuth cannot fetch token

I am trying to integrate an eBay SDK developed by David Sadler which is in GitHub. But I got stuck on connection part itself. I am getting app token with http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php with my production credentials.
But when I hit, http://localhost/ebay-sdk-examples/oauth-tokens/02-get-user-token.php it gives me this error:
[error] => invalid_grant
[error_description] => the provided authorization grant code is invalid or was issued to another client
all The codes are available in the SDK link. Incase you need here is the code snippet
<?php
/**
* Copyright 2017 David T. Sadler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Include the SDK by using the autoloader from Composer.
*/
require __DIR__ . '/../vendor/autoload.php';
/**
* Include the configuration values.
*
* Ensure that you have edited the configuration.php file
* to include your application keys.
*/
$config = require __DIR__ . '/../configuration.php';
/**
* The namespaces provided by the SDK.
*/
use \DTS\eBaySDK\OAuth\Services;
use \DTS\eBaySDK\OAuth\Types;
/**
* Create the service object.
*/
$service = new Services\OAuthService([
'credentials' => $config['production']['credentials'],
'ruName' => $config['production']['ruName'],
'sandbox' => false,
]);
$token = $config['production']['testToken']; ** This is the app token I get with http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php **
/**
* Create the request object.
*/
$request = new Types\GetUserTokenRestRequest();
$request->code = $token;
// $request->code = 'v^1.1#i^1#I^3#r^1#p^3#f^0#t^Ul41XzA6MkIzRjJFRjA1MENDMzZCQjlGMjVERkYyMkMxMTRBM0VfMV8xI0VeMjYw';
/**
* Send the request.
*/
$response = $service->getUserToken($request);
echo '<pre>';
print_r($response);
echo '<pre>';
exit;
/**
* Output the result of calling the service operation.
*/
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if ($response->getStatusCode() !== 200) {
printf(
"%s: %s\n\n",
$response->error,
$response->error_description
);
} else {
printf(
"%s\n%s\n%s\n%s\n\n",
$response->access_token,
$response->token_type,
$response->expires_in,
$response->refresh_token
);
}
If there are simple codes to without using any SDK to connect to eBay with OAuth, its what I am searching for.
I am also currently working with this SDK.
My understanding is you should place the url:
http://localhost/ebay-sdk-examples/oauth-tokens/02-get-user-token.php
As your Your auth accepted URL1 in the developer.ebay.com, under Get a Token from eBay via Your Application.
Where you are setting $token this should be set to $_GET['code'] as when testing the sign-in and accepting you should be redirected to the above URL with a ?code=xxxx parsed back to it.
The value your currently setting to $token should be set as the value of your authToken within your credentials.
Hope that helps.
eBay Token generation can be achieved using our custom PHP/.NET scripts. eBay API documentation having many references
https://viewdotnet.wordpress.com/2011/12/20/ebay-token-generation/
The above link includes all the required details to generate eBay Auth. token

Hiding YouTube API for client using server

My inexperience has left me short of understanding how to hide an API Key. Sorry, but I've been away from web development for 15 years as I specialized in relational databases, and a lot has changed.
I've read a ton of articles, but don't understand how to take advantage of them. I want to put my YouTube API key(s) on the server, but have the client able to use them w/o exposure. I don't understand how setting an API Key on my server (ISP provided) enables the client to access the YouTube channel associated with the project. Can someone explain this to me?
I am not sure what you want to do but for a project I worked on I needed to get a specific playlist from YouTube and make the contents public to the visitors of the website.
What I did is a sort of proxy. I set up a php file contains the api key, and then have the end user get the YT content through this php file.
The php file gets the content form YT using curl.
I hope it helps.
EDIT 1
The way to hide the key is to put it in a PHP file on the server.
This PHP file will the one connecting to youtube and retrieving the data you want on your client page.
This example of code, with the correct api key and correct playlist id will get a json file with the 10 first tracks of the play list.
The $resp will have the json data. To extract it, it has to be decoded for example into an associative array. Once in the array it can be easily mixed in to the html that will be rendered on the client browser.
<?php
$apiKey = "AIza...";
$results = "10";
$playList = "PL0WeB6UKDIHRyXXXXXXXXXX...";
$request = "https://www.googleapis.com/youtube/v3/playlistItems?part=id,contentDetails,snippet&maxResults=" . $results .
"&fields=items(contentDetails%2FvideoId%2Cid%2Csnippet(position%2CpublishedAt%2Cthumbnails%2Fdefault%2Ctitle))" .
"&playlistId=" . $playList .
"&key=" . $apiKey;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $request,
CURLOPT_SSL_VERIFYPEER => false
));
$resp = curl_exec($curl);
if (curl_errno($curl)) {
$status = "CURL_ERROR";
}else{
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
$status = "OK";
//Do something with the $resp which is in JSON format.
//Like decoding it into an associative array
} else {
$status = "YT_ERROR";
}
}
curl_close($curl);
?>
<html>
<!-- your html here -->
</html>
Note: CURLOPT_SSL_VERIFYPEER is set to false. This is in development. For prod it should be true.
Also note that using the api this way, you can restrict the calls to your api key bounding them to your domain. You do that in the googla api console. (Tip for production)

Expire-date in refresh-token (oauth2, exact)

So I'm using the exact-online XML-api to retrieve some user-related data.
This works fine so far, but since it is using oauth 2.0, I am being redirected after 600 sec and the login-prompt appears again.
This function refreshes the access-token:
/**
* #param string $refreshToken
* #return array {access_token, expires_in, refresh_token}
*/
public function refreshAccessToken($refreshToken)
{
$params = array(
'refresh_token' => $refreshToken,
'grant_type' => self::GRANT_REFRESH_TOKEN,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
);
$url = sprintf(self::URL_TOKEN, $this->countryCode);
return $this->getResponse($url, $params);
}
I debuged into it and the expires_in is set to 600. I guess this is the cause I'm being logged after after a short amount. My question: how can I disable this 600 sec timeout?
Also I found this function:
/**
* #param int $expiresInTime
*/
protected function setExpiresIn($expiresInTime)
{
$this->expiresIn = time() + $expiresInTime;
}
I modified the function and added a *1000 so it doesn't run out, but that didn't affect the outcome.
Is this an oauth-specific thing? Is it somehow managable to don't be kicked off after 10 mins?
There is no such thing in the backend of exact-online, which could change this value. Also, since this is a request I recieve, I don't think I can manipulate it, right?
Update 1
Due to the good feedback, I think I got a start with that problem, but no solution yet. I'll provide the code I'm currently using. I also asked the support of exact, but didn't got too much help there unfortunatly.
Please see this code:
<?php
require_once($sShopHomeDir . "modules/" . $sModulePath . "/library//exact/ExactApi.php");
$this->_exactApi = new ExactApi('de', $this->_sClientId, $this->_sClientSecret, $this->_sDivision);
$this->_exactApi->getOAuthClient()->setRedirectUri($this->_sRedirectUri.$param);
if (!isset($_GET['code']))
{
// Redirect to Auth-endpoint
$authUrl = $this->_exactApi->getOAuthClient()->getAuthenticationUrl();
header('Location: ' . $authUrl, true, 302);
die('Redirect');
}
else
{
$tokenResult = $this->_exactApi->getOAuthClient()->getAccessToken($_GET['code']);
$this->_exactApi->setRefreshToken($tokenResult['refresh_token']);
}
From the comments and answer, I'm convinced that this is the way to go. I'm retrieving a code and store/set the refresh-token - which, from my understanding, is correct that way.
For a better readabilty, I'll provide links to the two files which Exact online provides in their examples:
ExactApi.php
ExactOAuth.php
You have two OAuth flows supported by Exact Online. From the information and the timeout you give I am pretty sure you are using the implicit grant flow, which is not documented by Exact, but it does work.
The only other option you have is to use the token based authentication flow, which requires an extra step, namely exchanging your response code for an access token. That token is valid for a year and can be refreshed afterwards to extend the period for another year. The token based authentication flow is only useful in environments you can control, like web applications.
That token based authentication flow doesn't work with two phase authentication, so you can't refresh a token after that one year period.

Google Docs: Cannot export/download user's document using administrative access/impersonation (forbidden 403) in python

I have read this thoroughly: https://developers.google.com/google-apps/documents-list/#using_google_apps_administrative_access_to_impersonate_other_domain_users
I have googled this to death.
So far I have been able to:
Authorise with:
clientLogin
OAuth tokens (using my domain key)
retrieve document feeds for all users in the domain (authorised either way in #1)
I am using the "entry" from the feed to Export/Download documents and always get forbidden for other users for documents not shared with admin. The feed query I am using is like:
https://docs.google.com/feeds/userid#mydomain.com/private/full/?v=3
(I have tried with and without the ?v=3)
I have also tried adding the xoauth_requestor_id (which I have also seen in posts as xoauth_requestor), both on the uri, and as a client property: client.xoauth_requestor_id = ...
Code fragments:
Client Login (using administrator credentials):
client.http_client.debug = cfg.get('HTTPDEBUG')
client.ClientLogin( cfg.get('ADMINUSER'), cfg.get('ADMINPASS'), 'HOSTED' )
OAuth:
client.http_client.debug = cfg.get('HTTPDEBUG')
client.SetOAuthInputParameters( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, cfg.get('DOMAIN'), cfg.get('APPS.SECRET') )
oatip = gdata.auth.OAuthInputParams( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, cfg.get('DOMAIN'), cfg.get('APPS.SECRET') )
oat = gdata.auth.OAuthToken( scopes = cfg.get('APPS.%s.SCOPES' % section), oauth_input_params = oatip )
oat.set_token_string( cfg.get('APPS.%s.TOKEN' % section) )
client.current_token = oat
Once the feed is retrieved:
# pathname eg whatever.doc
client.Export(entry, pathname)
# have also tried
client.Export(entry, pathname, extra_params = { 'v': 3 } )
# and tried
client.Export(entry, pathname, extra_params = { 'v': 3, 'xoauth_requestor_id': 'admin#mydomain.com' } )
Any suggestions, or pointers as to what I am missing here?
Thanks
You were very close to having a correct implementation. In your example above, you had:
client.Export(entry, pathname, extra_params = { 'v': 3, 'xoauth_requestor_id': 'admin#mydomain.com' } )
xoauth_requestor_id must be set to the user you're impersonating. Also what you need is to use 2-Legged OAuth 1.0a with the xoauth_requestor_id set either in the token or in the client.
import gdata.docs.client
import gdata.gauth
import tempfile
# Replace with values from your Google Apps domain admin console
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
# Set this to the user you're impersonating, NOT the admin user
username = 'userid#mydomain.com'
destination = tempfile.mkstemp()
token = gdata.gauth.TwoLeggedOAuthHmacToken(
consumer_key, consumer_secret, username)
# Setting xoauth_requestor_id in the DocsClient constructor is not required
# because we set it in the token above, but I'm showing it here in case your
# token is constructed via some other mechanism and you need another way to
# set xoauth_requestor_id.
client = gdata.docs.client.DocsClient(
auth_token=token, xoauth_requestor_id=username)
# Replace this with the resource your application needs
resource = client.GetAllResources()[0]
client.DownloadResource(resource, path)
print 'Downloaded %s to %s' % (resource.title.text, destination)
Here is the reference in the source code to the TwoLeggedOAuthHmacToken class:
http://code.google.com/p/gdata-python-client/source/browse/src/gdata/gauth.py#1062
And here are the references in the source code that provide the xoauth_requestor_id constructor parameter (read these in order):
http://code.google.com/p/gdata-python-client/source/browse/src/atom/client.py#42
http://code.google.com/p/gdata-python-client/source/browse/src/atom/client.py#179
http://code.google.com/p/gdata-python-client/source/browse/src/gdata/client.py#136

Resources