Calling Twitter API results in "Timestamp out of bounds" Error - twitter

I am calling Twitter for fetching user Timeline Details. Here is my code
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: OAuth oauth_consumer_key=\"XXXXXXX\",oauth_token=\"XXXXXXX\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"XXXXXXX\",oauth_nonce=\"XXXXXXXX\",oauth_version=\"1.0\",oauth_signature=\"XXXXXXX\"",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
I am able to fetch details. But after a day I am getting this response
{"errors":[{"code":135,"message":"Timestamp out of bounds."}]}
Is my Token getting expired ? I want to run this code as a background request.

The oauth_timestamp should be the number of whole seconds since 1 Jan 1970 00:00:00 UTC.
{"errors":[{"code":135,"message":"Timestamp out of bounds."}]}
Usually means that your server / machine time is off by more than 30 seconds (actual time not including time-zone differences). Look at the response header to see what Twitter's time is.
oauth_timestamp=1521786006

Related

eBay API error: Authorization is throwing the following error....invalid grant, invalid client

I am trying to authorize eBay user for exchanging token. Unfortunately, it's not working and returning 2type of error for different aspect. The errors are: 'invalid grant' and 'invalid client'
My code response is 200. But, in postman, it's showing the following response for 2 different Authorization criteria
Error for .. Authorization: Basic 'my code'
{
"error": "invalid_grant",
"error_description": "the provided authorization grant code is invalid or was issued to another client"
}
Error for .. Authorization: Bearer'my code'
{
"error": "invalid_client",
"error_description": "client authentication failed"
}
My Code:
<?php
$clientID = 'client_id';
$clientSecret = 'client_secret';
$authCode = 'authorization_code';
$url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token';
$redirectUrlName = 'redirect_uri';
$body = http_build_query([
'grant_type' => 'authorization_code',
'code' => $authCode,
'redirect_uri'=> $redirectUrlName
]);
$headers = [
'Cache-Control: no-cache',
'Accept : application/json',
'Content-Type : application/x-www-form-urlencoded',
'Authorization: Basic '.base64_encode($clientID.':'.$clientSecret)
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
// CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response."\n";
}
?>
Same thing worked for me, when I was trying for client credentials.
The body section seems to be incorrectly being passed:
'grant_type' => 'authorization_code'&,
'code' => $authCode&,
'redirect_uri'=> $redirectUrlName
In a working code for my case, here is how the body is passed:
CURLOPT_POSTFIELDS => 'grant_type=authorization_code&code=<code value>&redirect_uri=<uri for my test>',
The code was okay, except 2things.
Authorization code: This will come from eBay as a Response. We need to fetch the code.
$headers will have to write as following:
$headers = [
'Cache-Control: no-cache',
'Accept: application/json',
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic '.base64_encode($clientID.':'.$clientSecret)
];
There Will have no space between Cache-Control and Colon(:). That mean, there will have no space at key and colon. Applicable for all key-value pair.

Setting request body for Guzzle 6 put()

I am setting the request body incorrectly for these Guzzle put() calls. I am making get() calls to same API using same token without issue.
The API has a test environment and here is what a successful put call looks like in cURL:
curl -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Basic tokenishere=' -d '{ \
"OrganizationCode": "10", \
"EventID": 5524, \
"FunctionID": 321, \
"Description": "Test" \
}' 'https://example.com/api/v1/Functions/10/5524/321'
My Guzzle code is
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
$client = new \GuzzleHttp\Client(array("base_uri" => "https://example.com"));
$response = $client->put("/api/v1/Functions/10/".$_SESSION['eventID'].'/'.$functionID,
array(
'headers' => array(
'token' => $token,
'debug' => true,
),
'body' => $data
)
I have also tried
$request = $client->put("/api/v1/Functions/10/$_SESSION[eventID]/$functionID", array('headers' => array('token' => $token)));
$request->setBody($data);
$response = $request->send();
And I have tried using param name json instead of body.
I have verified the JSON string in $data.
https://guzzle3.readthedocs.io/http-client/request.html shows an example where the body is 3rd arg:
$request = $client->put('http://httpbin.org/put', array(), 'this is the body');
So I also tried this below but same issue...
$request = $client->put("/api/v1/Functions/10/".$_SESSION['eventID'].'/'.$functionID, array(
'headers' => array(
'token' => $token,
'debug' => true,
)), $data);
Debug output is
PUT /api/v1/Functions/10/5524/321 HTTP/1.1
User-Agent: GuzzleHttp/6.3.3 curl/7.52.1 PHP/7.3.6-1+0~20190531112735.39+stretch~1.gbp6131b7
Host: example.com
token: tokenisreallyhere==
debug: 1
{"OrganizationCode":10,"EventID":"5524","FunctionID":"321","Description":"Test"}PUT /api/v1/Functions/10/5524/321 HTTP/1.1
User-Agent: GuzzleHttp/6.3.3 curl/7.52.1 PHP/7.3.6-1+0~20190531112735.39+stretch~1.gbp6131b7
Host: example.com
token: tokenisreallyhere==
debug: 1
{"OrganizationCode":10,"EventID":"5524","FunctionID":"321","Description":"Test"}HTTP/1.1 400 Missing model object in request body. Check body And header content type.
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
ETag: ""
X-Frame-Options: SAMEORIGIN
Date: Thu, 05 Sep 2019 21:57:06 GMT
Content-Length: 0
Where do I set the body?
Use form_params body is deprecated
$response = $client->put("/api/v1/Functions/10/".$_SESSION['eventID'].'/'.$functionID,
array(
'headers' => array(
'token' => $token,
'debug' => true,
),
'form_params' => $data
)
Of course the part I think is irrelevant is the answer: I did not show that I was using json_encode() on $data before passing it. The array, not a json object string, was expected so with $data as an array this works correctly.
$response = $client->put("/api/v1/Functions/10/".$_SESSION['eventID'].'/'.$functionID,
array(
'headers' => array(
'token' => $token,
'debug' => true
),
'json' => $data
)
);

Creating Group via Microsoft Graph returns Error "An unexpected PrimitiveValue node was found when reading from the JSON reader"

Am trying to create group using my admin account via Microsoft Graph. I have implemented all the required parameters/variables but when I tried making calls to the API, it displays error below:
{
"error": {
"code": "Request_BadRequest",
"message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartArray' node was expected.",
"innerError": {
"request-id": "02bfcc43-5982-4c49-8484-da9d6cc61bab",
"date": "2017-12-05T17:53:57"
}
}
}
My code:
<?php
session_start();
echo $acc= $_SESSION['access_token'];
$data_string = array("description" => "An Awesome New Group", "displayName" => "Awesome Group", "groupTypes" => "Unified", "mailEnabled" => "true", "mailNickname" => "awesomeGroup", "securityEnabled" => "fasle");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/groups",
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
print_r($response);
if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
Note that my real tenant id was replaced with admin#secx34fake.onmicrosoft.com so that its not displayed to public.
The error is telling you that the URL you're using is invalid.
This is accurate as /v1.0/admin#secx34fake.onmicrosoft.com/groups isn't a valid endpoint. Specifically it rejecting the userPrincipalName of admin#secx34fake.onmicrosoft.com. I'm not exactly sure where you were going with this but a Group is not a child of a User object. A User can be a member of a Group but they are both top-level elements within your Active Directory.
As an aside, a "segment" in the context of a URL is the elements separated by a /. You can think of a URL as a / delimited string with each column being a "segment". For example, /v1.0/me/events contains 3 segments: v1.0, me and events. The error you got is telling you one of these "segments" is either invalid or not in the proper order (i.e. /v1.0/events/me has the right segments in the wrong order).
For creating a Group, the proper URI looks like this:
POST https://graph.microsoft.com/v1.0/groups
Within the body of your POST you define the properties of the group. For example:
{
"description": "An Awesome New Group",
"displayName": "Awesome Group",
"groupTypes": ["Unified"],
"mailEnabled": true,
"mailNickname": "awesomeGroup",
"securityEnabled": false
}

Correct Way to use returned ApiGility Implicit Token

My app receives an access token by virtue of an implicit grant. Now I am attempting to use this token to access the content servers RPC service. I am not 100% sure if this is the correct way to do it as I am unable to get it to work.
$code = (string) $this->params()->fromQuery('code', null);
$client = new HttpClient(
'http://www.example.com/api/books',
array(
'maxredirects' => 0,
'timeout' => 30
)
);
$client->setMethod('GET');
$client->setHeaders(
[
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$code
]
);
try {
$response = $client->send();
} catch (\Exception $e) {
throw new \Exception($e);
}
Here is the example in postman which is failing:
In this question the authorization_code was used and not the access_token and that's why it failed.

post data with curl and change page url

I have a shopping site and I have to send username and password and some other data to the bank, so I have used curl for posting data .because it should be safe.
but my problem is when I post data with curl to the bank, page url dont change! I see banks result in my server page !!!
I need this posting data same as posting data in html page redirect too the url which has been determined !!
$data = array(
"MID" => "0113-19",
"RedirectURL" => $SERVER . "/shop/profile.php",
"Amount" => $sum,
"ResNum" => $ResNum,
"username" => "xxxx",
"password" => "1234");
//traverse array and prepare data for posting (key1=value1)
foreach ( $data as $key => $value) {
$data[] = $key . '=' . urlencode($value);
}
$post_string = implode ('&', $data);
$res = array();
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_POST => true, // return web page
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_AUTOREFERER => false, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_POSTFIELDS => $post_string, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false , // stop after 10 redirects
CURLOPT_COOKIEJAR => "cookie.txt" , // stop after 10 redirects
CURLOPT_COOKIEFILE => "cookie.txt" , // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false , // stop after 10 redirects
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U;
Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" // stop after 10 redirects
);
//////////////////////
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );

Resources