Update Twitter Status Error - php

I am updating twitter status using my application and facing a problem.
stdClass Object ( [request] => /1/statuses/update.json [error] => Could not authenticate you. )
But i have authenticate just 2 minutes ago and again its showing same error using code given bellow.
if(strlen($status)>=140)
{
$status = substr($status,0,139);
}
if($E_oauth_token != "" && $E_oauth_token_secret != "")
{
try
{
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $E_oauth_token, $E_oauth_token_secret);
$access_token = $twitteroauth->getAccessToken($tweet_verifier);
$params = array('status' => $status);
print_r($twitteroauth->post('statuses/update', $params));
}
catch(exception $e)
{
echo $e;
}

I have found solution for this and explain on this site you can easily check.
There is two types of oauth tokens one is temporary and with that temporary we have to get permanent token explained here Twitter OAuth in PHP.

Related

Microsoft Graph API (Calendar) Intermittent 503 Errors

This code sometimes works, but frequently runs for ~20s then fails with the "503 Service Unavailable" message when I call getPage(). The authentication/token request seems to be working fine.
I can't seem to identify any pattern of when it fails/succeeds. I don't believe it's a throttling error, as there is no "Retry-After" header returned, and the script only runs once per day at night with <200 records returned. I've also tried removing the $filter and changing parameter order as described here, with no clear benefit.
Can someone please help find the cause here? Happy to share any additional info. Any help is much appreciated, thanks!
<?php
define('DEBUG', true);
session_start();
// set config vars
$ms_url_base = "https://login.microsoftonline.com/d3523db7-f84a-4a24-a815-cd4ba4691c9c";
$ms_client_id = '<client id>';
$ms_redirect_uri = "https://example.com/path";
$ms_scope = "calendars.readwrite user.read";
$ms_client_secret = '<secret>';
$ms_auth_endpoint = '/oauth2/v2.0/authorize';
$ms_token_endpoint = '/oauth2/v2.0/token';
$query_numdays = 100;
if (DEBUG) error_reporting(E_ALL);
date_default_timezone_set("America/Detroit");
require_once __DIR__.'/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
class EventMod extends \Microsoft\Graph\Model\Event {
// custom functions here
public function getNextLink() {
parent::getNextLink();
}
}
class ResponseMod extends \Microsoft\Graph\Http\GraphResponse {}
// authorization
$provider = new Stevenmaguire\OAuth2\Client\Provider\Microsoft([
'clientId' => $ms_client_id,
'clientSecret' => $ms_client_secret,
'redirectUri' => $ms_redirect_uri,
'urlAuthorize' => $ms_url_base.$ms_auth_endpoint,
'urlAccessToken' => $ms_url_base.$ms_token_endpoint,
'urlResourceOwnerDetails' => 'https://graph.microsoft.com/v2.0/me',
]);
if (!isset($_GET['code'])) {
$options = ['scope' => $ms_scope, 'aud' => 'Graph'];
$authUrl = $provider->getAuthorizationUrl($options);
$_SESSION['oauth2state'] = $provider->getState();
header('Location: '.$authUrl);
exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
$token = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
} catch (League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
exit ("Get access token exception: ".$e->getMessage());
}
if (DEBUG) {
echo 'Access Token: ' . $token->getToken() . "<p>";
echo 'Refresh Token: ' . $token->getRefreshToken() . "<p>";
echo 'Expired in: ' . $token->getExpires() . "<p>";
echo 'Already expired? ' . ($token->hasExpired() ? 'expired' : 'not expired') . "<p>";
}
// start calendar query
$start=new DateTimeImmutable("yesterday 0:0:1");
$end = $start->add(new DateInterval("P".$query_numdays."D"));
$url='/me/calendarview'
.'?startdatetime='.$start->format('c')
.'&enddatetime='.$end->format('c')
.'&$filter=isOrganizer+eq+false'
.'&$select=subject,responseStatus,start,categories'
.'&$orderby=start/dateTime';
$graph = new Graph;
$graph->setAccessToken($token->getToken());
$data = array();
try {
$iterator = $graph->createCollectionRequest("GET", $url)
->setReturnType(EventMod::class)
->addHeaders(["Prefer" => 'outlook.timezone="America/Detroit"'])
->setPageSize(25);
do {
$page = $iterator->getPage(); /*************** THIS IS WHERE THE EXCEPTION HAPPENS ************/
if (DEBUG) echo "<pre>".print_r($page, true)."</pre>";
$data = array_merge($data, $page);
} while (!$iterator->isEnd());
}
catch (\Microsoft\Graph\Exception\GraphException $e) {
if (DEBUG) echo "GraphException Message: ".$e->getMessage();
exit;
}
catch (Exception $e) {
if (DEBUG) echo "Unk Exception getting data: ".$e->getMessage();
exit;
}
if (DEBUG) print_r($data);
}
?>
composer.json
{
"require": {
"microsoft/microsoft-graph": "^1.29",
"stevenmaguire/oauth2-microsoft": "^2.2"
}
}
I played with your above API call and i ended up noticing the issue - in the case of having bigger larger dates and lot of data at my end (not with smaller time window or less records). It tells me that the failure is due to the client timeout. We need to understand that Calendar view is an expensive operation that too when you deal with calendars and filters added to it. So i went ahead in this scenario, reduce/minimize time window for calendar view by client so smaller segments of time are scanned for matching calendar events. It helped me to get the records as i expected and make use of effective usage of Calendarview API call too.
Apparently the issue was not in the code at all. I discovered that the 503 error was thrown only when a specific date's events were being read by the API. One of the events was rather large and I deleted it; after this the script works well.
This particular event has 16536 attendees listed, which I believe was the source of the error. Still unexplained is why the error was intermittent. I was eventually able to get graph explorer to successfully read the event, so perhaps the bug is in the Microsoft Graph SDK for PHP. I will post there to see if the devs want to capture this error condition.

Ebay: Auth token is invalid. Validation of the authentication token in API request failed

I'm trying to use Ebay PHP SDK to connect to Ebay and fetch sellers selling item. For this I used following steps:
Step 1: Get authorize token and code for logged-in user. I used following code to implement.
use \DTS\eBaySDK\OAuth\Services as OauthService;
use \DTS\eBaySDK\OAuth\Types as OauthType;
use \DTS\eBaySDK\Constants;
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;
use \DTS\eBaySDK\Trading\Enums;
$service = new OauthService\OAuthService([
'credentials' => $config['sandbox']['credentials'],
'ruName' => $config['sandbox']['ruName'],
'sandbox' => true
]);
$oauthParam = [
'client_id' => $config['sandbox']['credentials']['appId'],
'redirect_uri' => $config['sandbox']['redirect_uri'],
'response_type' => 'code',
'scope' => 'https://api.ebay.com/oauth/api_scope'
];
$urlParam = '';
$query = [];
foreach($oauthParam as $key => $param) {
$query[] = "$key=$param";
}
$urlParam = '?' . implode('&', $query);
$url = 'https://signin.sandbox.ebay.com/authorize' . $urlParam;
#session_start();
if(isset($_SESSION['ebay_oauth_token'])) {
$token = $_SESSION['ebay_oauth_token']['code'];
}
else {
if(isset($_GET['code'])) {
$token = $_GET['code'];
$_SESSION['ebay_oauth_token']['code'] = $token;
$request = new OauthType\GetUserTokenRestRequest();
$request->code = $token;
$response = $service->getUserToken($request);
if ($response->getStatusCode() !== 200) {
//Error
} else {
$_SESSION['ebay_oauth_token']['access_token'] = $response->access_token;
}
} else {
#header('location: ' . $url);
}
}
$userOauthToken = $_SESSION['ebay_oauth_token']['access_token'];
The above code is working as expected. That is the user is redirected to Sign In Page to authorize himself and get the set of Code and Access Token.
Step 2: Fetch Selling Items using code obtained from Step #1. I've used following code to implement the functionality.
$request->RequesterCredentials = new Types\CustomSecurityHeaderType();
$request->RequesterCredentials->eBayAuthToken = $token; //Obtained from Step 1
$request->ActiveList = new Types\ItemListCustomizationType();
$request->ActiveList->Include = true;
$request->ActiveList->Pagination = new Types\PaginationType();
$request->ActiveList->Pagination->EntriesPerPage = 10;
$request->ActiveList->Sort = Enums\ItemSortTypeCodeType::C_CURRENT_PRICE_DESCENDING;
$pageNum = 1;
do {
$request->ActiveList->Pagination->PageNumber = $pageNum;
$response = $service->getMyeBaySelling($request);
if (isset($response->Errors)) {
//Error Output
}
if ($response->Ack !== 'Failure' && isset($response->ActiveList)) {
foreach ($response->ActiveList->ItemArray->Item as $item) {
//Output response
}
}
$pageNum += 1;
} while ({condition});
I'm having problem in Step #2. It is generating Invalid Token while running the code.
I would highly appreciate if anyone help me.
You are mixing the requests. In the second part of your code, the request belongs to the Trading API that uses the Auth'n'Auth token, and you are trying to make the call using the OAuth token. These 2 tokens are different and work for different APIs.
You have 2 options.
Either keep the second part of your code, which appears to be correct, actually, but use the Auth'n'Auth token (that you can generate from the developer account). In this case, the first part is useless.
Keep the first part of your code, and delete the second part. In this case, you need to rewrite your second part of code using the OAuth API instead of the Trading API.

PHP MusicBrainz get the first release date

i am trying to get the first release date of a song using Musicbrainz. To get this i am using the mikealmond musicBrainz library.
The problem i have is that when i try to execute exactly the same code as in this example (https://github.com/mikealmond/MusicBrainz/blob/master/examples/first-recording-search.php) i always get an authentication error.
Client error response [status code] 401 [reason phrase] Unauthorized [url] http://musicbrainz.org/ws/2/artist/0383dadf-2a4e-4d10-a46a-e9e041da8eb3?inc=releases+recordings+release-groups+user-ratings&fmt=json
Therefore i tried to add my username and password to the request:
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()),'myusername','mypassword');
$brainz->setUserAgent('myapplicationname', '0.2', 'http://localhost:443/');
If i call the url in the error message manually and enter my username and password i get the array i expect.
I just had a discovery: If I removed -"+ user - ratings"- it does not require authentication.
Therefore i commented the lines with "user - ratings" in my project
Now i think it works, but the performance of the query is very bad and often i get Error 503 // The MusicBrainz web server is currently busy. Please try again later. //
It takes a few seconds just for one song. Does someone know if this is normal or if i still have some kind of mistake?
My code....
//Create new MusicBrainz object
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
$brainz->setUserAgent('applicationname', '0.2', 'http://localhost:443/');
// set defaults
$artistId = null;
$songId = null;
$lastScore = null;
$firstRecording = array(
'releaseDate' => new DateTime()
);
// Set the search arguments to pass into the RecordingFilter
$args = array(
"recording" => 'we will rock you',
"artist" => 'Queen',
);
try {
// Find all the recordings that match the search and loop through them
$recordings = $brainz->search(new RecordingFilter($args));
$recorings i can print and in the loop i can print each $recording, but the error comes when i extract the informations
/** #var $recording \MusicBrainz\Recording */
foreach ($recordings as $recording) {
// if the recording has a lower score than the previous recording, stop the loop.
// This is because scores less than 100 usually don't match the search well
if (null != $lastScore && $recording->getScore() < $lastScore) {
break;
}
$lastScore = $recording->getScore();
$releaseDates = $recording->getReleaseDates();
$oldestReleaseKey = key($releaseDates);
if (strtoupper($recording->getArtist()->getName()) == strtoupper($args['artist'])
&& $releaseDates[$oldestReleaseKey] < $firstRecording['releaseDate']
) {
$firstRecording = array(
'releaseDate' => $recording->releases[$oldestReleaseKey]->getReleaseDate()
);
}
}
pr($firstRecording);
} catch (Exception $e) {
pr($e->getMessage());
}
$brainz = new MusicBrainz(new GuzzleHttpAdapter(new Client()), 'username', 'password');
You must set your MusicBrainz account credentials. Replace 'username' with your account username, and 'password' with the password used to login to MusicBrainz.org

DoExpresscheckout not woking. it gives ACK failure

i am creating Expresscheckout API using PAYPAL. Set expresscheckout and get expresscheckout is working properly. i get a tocken and payerid from these two steps. but when i goto DoExpresscheckout it gives me ACK failure.
DoExpressCheckoutPaymentResponseType Object
(
[DoExpressCheckoutPaymentResponseDetails] =>
[FMFDetails] =>
[Timestamp] => 2013-06-10T12:15:02Z
[Ack] => Failure
[CorrelationID] => a88b9b744676a
[Errors] => Array
(
[0] => ErrorType Object
(
[ShortMessage] => This Express Checkout session has expired.
[LongMessage] => This Express Checkout session has expired. Token value is no longer valid.
[ErrorCode] => 10411
[SeverityCode] => Error
[ErrorParameters] =>
)
)
[Version] => 98.0
[Build] => 6341744
)
Does any one have correct code for DoExpresscheckout and what fields are require for make it Sucessful ??
well paypal SDK is extremely simple. first if i were you i would install their example code and make sure it work on your server, from my previous experience there are rare cases where the SDK wont work and have php version issues.
Secondly after you're sure it works on your server, the chart flow is:
step 1.) SetExpressCheckout - with all the required fields like:billing address, products cart total etc...
if that was done correct you'll get a token,
step 2.) GetExpressCheckout - With the previously acquired token you'll do GetExpressCheckout passing the token, if that done correct you'll get:Ack, Token, PayerID, value, currencyID and basically an object that has all the purchase details.
step 3.) DoExpressCheckout - use the acquired fields from 2 to do a DoExpressCheckout as follows:
$path = $pluginfolder.'paypal/lib';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once('services/PayPalAPIInterfaceService/PayPalAPIInterfaceServiceService.php');
require_once('PPLoggingManager.php');
$logger = new PPLoggingManager('DoExpressCheckout');
$token = urlencode( $getToken );
$payerId = urlencode( $getPayerID);
$paymentAction = urlencode( $paymentType);
$orderTotal = new BasicAmountType();
$orderTotal->currencyID = $getCurrencyID;
$orderTotal->value = $getOrderTotal;
$paymentDetails= new PaymentDetailsType();
$paymentDetails->OrderTotal = $orderTotal;
if(isset($notifyURL))
{
$paymentDetails->NotifyURL = $notifyURL;
}
$DoECRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
$DoECRequestDetails->PayerID = $payerId;
$DoECRequestDetails->Token = $token;
$DoECRequestDetails->PaymentAction = $paymentAction;
$DoECRequestDetails->PaymentDetails[0] = $paymentDetails;
$DoECRequest = new DoExpressCheckoutPaymentRequestType();
$DoECRequest->DoExpressCheckoutPaymentRequestDetails = $DoECRequestDetails;
$DoECReq = new DoExpressCheckoutPaymentReq();
$DoECReq->DoExpressCheckoutPaymentRequest = $DoECRequest;
/*
* Trying to go a head with the payment and catching errors that might occure.
*/
try {
/* wrap API method calls on the service object with a try catch */
$DoECResponse = $paypalService->DoExpressCheckoutPayment($DoECReq);
} catch (Exception $ex) {
if(isset($ex)) {
$ex_message = $ex->getMessage();
$ex_type = get_class($ex);
if($ex instanceof PPConnectionException) {
$error[] = "Error connecting to " . $ex->getUrl();
$errorCheck = true;
} else if($ex instanceof PPMissingCredentialException || $ex instanceof PPInvalidCredentialException) {
$error[] = $ex->errorMessage();
$errorCheck = true;
} else if($ex instanceof PPConfigurationException) {
$error[] = "Invalid configuration. Please check your configuration file";
$errorCheck = true;
}
}
}
i hope that helps.

Khan Academy PHP Oauth Code

Im really struggling w/ the OAuth for Khan Academy. This is for my class website (Im a teacher) and I want to pull in user data on particular students. If I could do the OAUTH I would be fine. Im using PHP.
There seems to be many librarys out there, I have been playing w/ Google Oauth (located here http://code.google.com/p/oauth-php/source/browse/trunk/example/client/twolegged.php)
I can formulate the token request fine, although when I call it in the script, it seems like it tries to redirect to another page and gets blocked there.
http://myonlinegrades.com/prealg/khan/oauth-php/example/client/twoleggedtest.php
Im really struggling - Id love any help you might offer.
Code below:
<?php
include_once "../../library/OAuthStore.php";
include_once "../../library/OAuthRequester.php";
// Test of the OAuthStore2Leg
// uses http://term.ie/oauth/example/
$key = '*********';//'<your app's API key>';
$secret = '***********';//'<your app's secret>';
$callBack = "http://myonlinegrades.com/prealg/test2.php5";
$url = 'http://www.khanacademy.org/api/auth/request_token';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "GET";
//$params = null;
$params = array(oauth_consumer_key => $key,oauth_callback=>$callBack);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo 'Error! $response ' . $response;
}
else
{
}
var_dump($response);
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
?>
Not sure this is what you're looking for, but I put together a simple example of doing oAuth with Khan Academy using the Temboo SDK: take a look at https://github.com/matthewflaming/temboo-experiments/tree/master/KhanAcademyOauth
(Full disclosure: I work at Temboo)

Categories