i have a problem, when i generate the first oauth response via uber api, i get all the information needed(access_token, refresh_token)
But when i wish to refresh the access_token for a specific user, i get invalid_grant(i know that this means the refresh token has expired, but i generate the codes and at first try it fails even if the codes are still valid)
this is the code i use for refreshing the token, can someone please explain why it is failing to give me a new code?
function refreshToken()
{
$url = 'https://login.uber.com/oauth/v2/token';
$fields = array(
'client_id' => MY_CLIENT_ID,
'client_secret' => MY_CLIENT_SECRET,
'grant_type' => "refresh_token",
'refresh_token' => MY_REFRESH_TOKEN
);
$fields_string = '';
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have the codes stored in the database, grab them and try to use them from there, the auth-code works fine after i oauth, but i need to be able to refresh the access token in order to query the UBER api for the receipt ready post on my webhook, if the token is expired i can't access the call with the current auth token i have(bearer token)
this is the response i get every time:
[error] => invalid_grant
I was storing the refresh token wrong in the database: the length was higher than the one i was storing under. eg: i was storing varchar(100) , i set it to varchar(255) now it works like a wonder.
Related
im trying to upload to my imgur Account's album, however, the upload works, but it looks like its gonna uploaded as anonym/public?
here's my code:
<?php
$client_id = "465xxx8c44294";
$image = file_get_contents("../images/d4487317c3xxx93210b293c2e.jpg");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
//curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image), 'album' => 'nqxxxGE'));
$reply = curl_exec($ch);
curl_close($ch);
$reply = json_decode($reply);
printf('<img height="180" src="%s" >', $reply->data->link);
any advice?
If you want to add image to album, according doc, you need to pass album id. Make sure you've generated token that has access to secret albums.
Here you can find some tips about tokens.
curl_setopt($ch, CURLOPT_POSTFIELDS,
array(
'image' => base64_encode($image),
'album' => '5' // 5 - your album id
)
);
You can check you albums id using this api.
To refresh token:
If a user has authorized their account but you no longer have a valid access_token for them, then a new one can be generated by using the refresh_token.
To obtain a new access token, your application performs a POST to https://api.imgur.com/oauth2/token. The request must include the following parameters to use a refresh token:
refresh_token: The refresh token returned from the authorization code exchange
client_id: The client_id obtained during application registration
client_secret: The client secret obtained during application registration.
grant_type: As defined in the OAuth2 specification, this field must contain a value of: refresh_token.
As long as the user has not revoked the access granted to your application, the response includes a new access token. A response from such a request is shown below:
{
"access_token":"5c3118ebb73fbb275945ab340be60b610a3216d6",
"refresh_token":"d36b474c95bb9ee54b992c7c34fffc2cc343d0a7",
"expires_in":3600,
"token_type":"Bearer",
"account_username":"saponifi3d"
}
Add the refresh part at the start of your script. Something like:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/oauth2/token');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'refresh_token' => $refreshToken, // Your refresh_token
'client_id' => $client_id,
'client_secret' => $clientSecret, //Your client_secret
'grant_type' => 'refresh_token'
]);
//Keep in mind that refreshToken and clientSecret are obtained during registration.
$reply = curl_exec($ch);
curl_close($ch);
$reply = json_decode($reply);
$accessToken = $reply->access_token;
I'm working on Globe Labs API to send an SMS. But before I can send an SMS, the mobile number I want to send message to needs to be subscribed so I can get the access_token which will be used in sending SMS.
There are 2 options to subscribe - via SMS or via Web Form. I was able to use first option without any problem. But I can't make the second option work.
According to the documentation, after the subscriber keyed-in the received confirmation pin on the page and clicked the Confirm button to authorize the subscriber, the page will then be redirected to the redirect_uri of my application, and a Code parameter will be passed(via GET) to it.
Here's the part where I fail to make it work:
To get the access token, you need to do a POST request via https://developer.globelabs.com.ph/oauth/access_token with your ‘app_id’, ‘app_secret’ and ‘code’ as the parameters. The parameters ‘access_token’ and ‘subscriber_number’ will then be returned to your Redirect URI as a response.
Here's my code:
$app_id = '<my_app_id>';
$app_secret = '<my_app_secret>';
$content = array(
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
);
$url = 'http://developer.globelabs.com.ph/oauth/access_token';
$this->post_to_url($url, $content);
function post_to_url($url, $data) {
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, count($data));
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($post);
curl_close($post);
if(!$result){
die('Error: "' . curl_error($post) . '" - Code: ' . curl_errno($post));
} else {
$this->Sms_Api_model->save_subscriber_data();
}
}
This is my redirect URL: http://api.forexcargo.us/sms_api/globelabs_api?code=[code]
And the result I get:
Error: "" - Code:
EDIT:
I tried to use a form and send my data via method POST and it worked. So it really might be my curl setup.
What am I doing wrong?
Any help is highly appreciated. Thank you!
Apologies for being a newbie regarding curl. Apparently, I had to add the following code to see the errors on my code because the URL I'm using has its error checking disabled:
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
And my new code:
function do_post_request($post_data)
{
error_reporting(-1);
ini_set('display_errors', 1);
set_time_limit(0);
$url = 'https://developer.globelabs.com.ph/oauth/access_token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
if($this->json_validator($response) == 1){
$decode_data = json_decode($response, true);
$post_data_arr = array('access_token' => $decode_data['access_token'], 'subscriber_number' => $decode_data['subscriber_number']);
$this->Sms_Api_model->save_subscriber_data($post_data_arr);
//var_dump(http_response_code(200));
}
}
$content = [
'app_id' => $app_id,
'app_secret' => $app_secret,
'code' => $this->input->get('code')
];
$post_request = $this->do_post_request($content);
Now it's working and I was able to save the data I received in my database. Thank you everyone for your help!
I am working on mediawiki api and i want to create user login with api . I referred this link. But i am not able to create session .
here is my code
first step
i have created a session id with this
session_start();
$data = "action=login&lgname=Wiki&lgpassword=gjnlt&lgtoken=5ae555656110dd20a2b0504e4d7e35e0"; // login
$result=call($data); // get the session id
function call($data=null)
{
$ch = curl_init('http://192.168.1.32/Eb_new/mediawiki/api.php?format=json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
return $result=json_decode($result);
}
The response i got is .
{"login":{"result":"Success","lguserid":5,"lgusername":"Wiki","lgtoken":"d85fd0201276632858ce4ad3ac351de4","cookieprefix":"EB_new_wiki_","sessionid":"3b8cdab43d4cda6b4548a3cc27604e20"}}
second step
now I have a session id in $result->login->sessionid .To set the session i made another call to set session like this
setsession($result->login->sessionid); // set the session
function setsession($sessionid)
{
$field_array= array(
'Accept' => 'HTTP_ACCEPT',
'Accept-Charset' => 'HTTP_ACCEPT_CHARSET',
'Accept-Encoding' => 'HTTP_ACCEPT_ENCODING',
'Accept-Language' => 'HTTP_ACCEPT_LANGUAGE',
'Connection' => 'HTTP_CONNECTION',
'Host' => 'HTTP_HOST',
'Referer' => 'HTTP_REFERER',
'User-Agent' => 'HTTP_USER_AGENT',
'Set-Cookie'=>'enwikiSession='.$sessionid.' ;domain=http://192.168.1.32/Eb_new/mediawiki'
);
$curl_request_headers=array();
foreach ($field_array as $key => $value) {
if(isset($_SERVER["$value"])) {
$server_value=$_SERVER["$value"];
$curl_request_headers[]="$key: $server_value";
}
};
$curl_request_headers[]="Expect: ";
session_write_close();
$data = "action=login&lgname=Wiki&lgpassword=gjnlt&lgtoken=5ae555656110dd20a2b0504e4d7e35e0"; // login
$ch = curl_init('http://192.168.1.32/Eb_new/mediawiki/api.php?format=json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $curl_request_headers);
//curl_setopt($curl_handle, CURLOPT_COOKIE, 'enwikiSession='.$sessionid.' ;domain=http://192.168.1.32/Eb_new/mediawiki');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $result = curl_exec($ch);
}
but the user is not logged in . Where i am wrong . any help will be appreciated . thanks
Structure of login request
Send a login request using POST (GET requests will cause an error).
api.php?action=login&lgname=Bob&lgpassword=secret [try in [ApiSandbox]
][1]
Result
{
"login": {
"result": "NeedToken",
"token": "b5780b6e2f27e20b450921d9461010b4",
"cookieprefix": "enwiki",
"sessionid": "17ab96bd8ffbe8ca58a78657a918558e"
}
}
The body of the POST can be empty. This request will also return a session cookie in the HTTP header
(Set-Cookie: enwikiSession=17ab96bd8ffbe8ca58a78657a918558e; path=/; domain=.wikipedia.org; HttpOnly)
that you have to return for the second request if your framework does not do this automatically. The sessionid parameter was added in MediaWiki 1.17 and later.
https://en.wikipedia.org/wiki/Special:ApiSandbox#action=login&lgname=Bob&lgpassword=secret
I found you have not started session anywhere in above code.
You need to add session_start() on every page where you want to retrieve value session or set value to session.
Ref
Here is my php script RefreshToken.php
<?php
$url = 'https://accounts.google.com/o/oauth2/token';
$post_data = array(
'code' => 'xxxxxxxx',
'client_id' => 'xxxxxxxxxxx',
'client_secret' => 'xxxxxxxxxxxxx',
'redirect_uri' => 'http://localhost/googleapi/AuthenticationCode.php',
'grant_type' => 'authorization_code',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$token = json_decode($result);
echo $token->refresh_token . "\n";
?>
Run PHP CLI
php -q RefreshToken.php
PHP Notice: Undefined property: stdClass::$refresh_token in /var/www/googleapi/RefreshToken.php on line 20
The refresh_token is not returned by default in Google OAuth2.
The request for an authorization code requires an extra parameter (access_type): then refresh token will be returned with access_token.
Other unusual behaviour: the refresh_token is returned only one time for a user. If, for some reason, refresh_token is lost for that user, then user will need to open Google Account Security Settings page and drop access for your app. And this is not enough: your app will need to pass more one params (approval_prompt equals true) to indicate we're forcing the request for a new refresh_token.
More info: https://developers.google.com/accounts/docs/OAuth2WebServer#offline)
My question relates to my previous question where I thought I had solved the issue. I've been able to obtain a refresh_token using scripts I found - including the ones in my previous question.
However now armed with this refresh token I am now trying to do some simple things in the first instance list the events in my test calendar
My problem is that trying to list the events using this URL returns an error - trying to get property of non object. This relates to this line of code:
$cAccessToken = $oToken->access_token;
So I assume there's something wrong in getting the access token.
In the part of my script where I obtained the code I needed to add this code:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
This produced the token- so I added this line to the code getting the access token again but it simply produced a blank page.
I must admit to be very confused with the google API. I tried using the google-client-api code but don't quite get this either - I keep running into brick walls.
Here's my code:
<?php
$cPublisherID = '';
$cScope = 'https://www.google.com/calendar/feeds/';
$cClientID = 'XXXXXX.apps.googleusercontent.com';
$cClientSecret = 'XXXXXX';
$cRedirectURI = 'XXXXXX';
$cAuthCode = 'XXXXXX';
$cRefreshToken = 'XXXXXX';
$bRefresh = true;
if (empty($cAuthCode)) {
$rsParams = array(
'response_type' => 'code',
'client_id' => $cClientID,
'redirect_uri' => $cRedirectURI,
'scope' => $cScope
);
$cOauthURL = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($rsParams);
echo("Go to\n$cOauthURL\nand enter the given value into \$cAuthCode\n");
exit();
} // ends if (empty($cAuthCode))
elseif (empty($cRefreshToken)) {
$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
$rsPostData = array(
'code' => $cAuthCode,
'client_id' => $cClientID,
'client_secret' => $cClientSecret,
'redirect_uri' => $cRedirectURI,
'grant_type' => 'authorization_code',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cTokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$cTokenReturn = curl_exec($ch);
$oToken = json_decode($cTokenReturn);
echo("Enter the following values:\n\n");
echo("\$cRefreshToken = '" . $oToken->refresh_token . "';\n");
} // ends
else {
// Get a new Access Token
$cTokenURL = 'https://accounts.google.com/o/oauth2/token';
$rsPostData = array(
'client_secret' => $cClientSecret,
'grant_type' => 'refresh_token',
'refresh_token' => $cRefreshToken,
'client_id' => $cClientID
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cTokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $rsPostData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$cTokenReturn = curl_exec($ch);
$oToken = json_decode($cTokenReturn);
$cAccessToken = $oToken->access_token;
// Get the results
//$cGANURL = 'https://www.googleapis.com/gan/v1beta1/publishers/' . $cPublisherID . '/events';
$rest_url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
$cAuthHeader = "Authorization: OAuth " . $cAccessToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array($cAuthHeader));
curl_setopt($ch, CURLOPT_URL, $rest_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cJsonReturn = curl_exec($ch);
print_r(json_decode($cJsonReturn));
} // ends else from <all authenticated>
?>
I really don't know enough to resolve this - so basically I think I'm getting the tokens I need including the refresh token but not sure how to test and understand what's going on.
I've used the oauth playground and can get results there but not with my own code. I used different codes by the way as I assumed they should be different?