Receiving HTTP 401 Unauthorized when making a Google plus API call - php

I'm trying to get the list of all my friends from the Google plus via API. The user on whose behalf I'm doing this operation previously authorized my request and I got the auth token. I've tried the following code in php:
function CallAPI() {
$opts = array(
"http" => array(
"method" => "GET"
)
);
$url = 'https://www.googleapis.com/plus/v1/people/me/people/visible?key=XXXX';
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
var_dump($response);
}
but I keep receiving HTTP request failed! HTTP/1.0 401 Unauthorized. How can I prove that the user authorized my operations or what am I doing wrong?
Any help is much appreciated.

You need to authenticate the user to use the special keyword "me" so using your simple API key will not work (assuming the key passed is your simple key). Instead, you need to get an access token and pass that.
For a great example of how to do this in PHP using the PHP client library, try the quickstart:
https://developers.google.com/+/quickstart/php
If you are already getting an access token, you can call tokeninfo passing access token to get more information about who the user is associated with it:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.xxxxxxxx...
At this point, you could call:
'https://www.googleapis.com/plus/v1/people/[useridfromaccesstoken]/people/visible?key=XXXX';
To verify that your API key is correct but I would recommend using the client library as demonstrated in the quickstart sample.

Related

ebay sdk - retrieving orders and sync with external DB

I am struggling, literally, trying to figure out how to use th Ebay API in order to retrieve the orders received on a specific merchant account and then store some datas in an external DB.
I have registered to developer.ebay.it, I have built a key pair, both for production and sandbox, then I have tried the api (Browse/getItem)...and then...LOST.
I cannot use the Fullfillment, because I always get a response of Insufficient authorization, even if I create a token, even if I put a real order number... I don't get how to question the API.
Lastly, I am using PHP and I have downloaded the davidtsadler SDK from github. How do I configure an example of getOrder with that SDK? Do you have any link, suggestions, anything?
What I find on internet is not enough clear for my level of knowledge and almost nobody deals with the getOrder call.
Thank you for your help.
The ebay API documentation is fairly clear on how to perform a query:
If you wanted to get a specific Fullfillment policy, then you would need to perform a GET request to ebays Fullfillment API using the /order/{orderId} path - where {orderId} is a real order ID.
In PHP, that might go a little something like this:
/* Returns a JSON object containing an ebay order */
function getOrder($order_id, $auth_key){
$options = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Bearer ".$auth_key."\r\n" .
"Content-Type: application/json"
)
);
$context = stream_context_create($options);
$result = file_get_contents("https://api.ebay.com/sell/fulfillment/v1/order/".$order_id, false, $context);
return json_decode($result);
}
Then you could call the method above and retrieve an order using:
$order = getOrder("A REAL ORDER ID", "YOUR AUTH KEY");
The $order variable now holds a JSON object. You can print info from the object using: (This example prints the username associated with the order)
echo $order->buyer->username;
Finally, please note the direct quote from ebays documentation:
"eBay creates and displays an Application token. This token is valid for a limited time span. If you get an invalid token error when you make a call using this token, simply create a new token and use the new token in your call."

Can only get access token for QuickBooks API once

I'm using PHPoAuthLib in order to connect to the QuickBooks API per their example
When I follow their example, the first request that I make to the API works perfectly:
$result = json_decode($quickbooksService->request($url));
echo 'result: <pre>' . print_r($result, true) . '</pre>';
However in their example they use $_GET['oauth_token'] and $_GET['oauth_verifier'] to request an access token, and these values are only available on the $_GET server variable during the single callback from QuickBooks Online immediately after my app has been authorized.
For future requests there are no such examples on PHPoAuthLib's docs, so I tried a quick homebrew solution:
Save the response from QBO somewhere
if (!empty($_GET['oauth_token']) {
file_put_contents("token.txt", json_encode([
'oauth_token' => $_GET['oauth_token'],
'oauth_verifier' => $_GET['oauth_verifier'],
'realm_id' => $_GET['realmId']
]));
}
Use that response again later
$token = json_decode(file_get_contents("token.txt"));
$quickbooksService->requestAccessToken(
$token->oauth_token,
$token->oauth_verifier
// $token->getRequestTokenSecret() is not necessary - it will be automatically populated
);
// At this point my app crashes and return a 500 error
// Further code does not run
The error I receive is:
TokenResponseException in StreamClient.php line 68:
Failed to request resource. HTTP Code: HTTP/1.1 401 Unauthorized
Remember that the token and verifier work perfectly if I use them immediately after the app is authorized. If I save them to a file and attempt to re-use them 30 seconds later, this happens.
I think it might be a fundamental misconception about OAuth 1.0
I don't think what you have is a correct OAuth implementation. Have you read the OAuth spec and implemented as it's defined there?
Once you have a request token and a verifier, you use those to get an access token.
That access token is then good for 6 months.
It looks like you're trying to use a short-lived request token to continually fetch access tokens instead. That won't work.
i.e. If you're doing this everytime you want to make another request:
$quickbooksService->requestAccessToken(
Then you're doing something wrong. You should be doing that ONCE every 6 months, and that's it.
Working code here:
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/IntuitAnywhere.php
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/IPP/OAuth.php
https://github.com/consolibyte/quickbooks-php
Spec is here:
http://oauth.net/core/1.0a/#auth_step3

OAuth 1.0a Implementation with PHP Pecl - Custom Signature (Fitbit)

I had an implementation of OAuth working with Fitbit to pull data from fitbit's service. However they recently updated their service and now the request is failing whenever I try to get an access token.
They have made the following statement about the new requirement:
The solution is to OAuth sign the requests to <https://api.fitbit.com/oauth/request_token> and <https://api.fitbit.com/oauth/access_token> in a similar manner that all other calls to the Fitbit API are signed.
Requests to <https://api.fitbit.com/oauth/request_token> need to be signed with your application's consumer key and secret.
Requests to <https://api.fitbit.com/oauth/access_token> need to be signed with your application's consumer key and secret and the oauth_token and oauth_verifier received from the authorization callback.
I am using the PHP PECL OAuth library for OAuth requests. However I can't find a way to add additional parameters to the signature. I am trying the following but I'm not sure that this is the correct way to update the OAuth Signature:
$params['consumer_key'] = $this->consumer_key;
$params['consumer_secret'] = $this->consumer_secret;
$params['oauth_token'] = $this->oauth_token;
$params['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$this->signature = $this->oauth->generateSignature('GET', $this->access_url, $params);
$this->access_token = $this->oauth->getAccessToken($this->access_url, $this->signature, $_REQUEST['oauth_verifier']);
The OAuth error I get is:
401
Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
oauthoauth_signatureInvalid signature: FfvYDv5MSOfwcOwLZBJa0TlKS4Q=false
The signature which is stored from the code above shows that the proper signature should be:
[signature] => wlfzqPs4aEkTkHfqyaO65D/RW6o=
This is the "Headers Sent" piece of the debug information:
[headers_sent] => Authorization: OAuth oauth_session_handle="Frdnxw8oHe3BgNVi0Fy4jBXrZko%3D",
oauth_verifier="ss6nmke8elf3so66jg3auued49",
oauth_consumer_key="(my key)",
oauth_signature_method="HMAC-SHA1",
oauth_nonce="30463910852ea5cc2d04e60.71895372",
oauth_timestamp="1391090882",
oauth_version="1.0",
oauth_token="2cabd6beab341e332bdf8e522b6019ef",
oauth_signature="hULwWcQOl%2F8aYjh0YjR843iVXtA%3D"
I can't find anything in the documentation which explains how I can set the signature for OAuth to use with it's request. Any Help would be greatly appreciated!!!
Please let me know if you need more information!
I have found the issue.
It turns out I was not saving the oauth_token_secret being handed back and I was instead using the consumer secret.
Once I updated this, the process ran as expected.

Sending Money with Dwolla's API and using PHP to do it?

Hello everyone I'm back again, In my last post I was attempting to use the SOAP api (Integrating Dwolla with PHP with their API) but I found out the SOAP API is deprecated and apparently Dwolla has more efficient way such as the REST/oAuth2.0 which is why I'm here today asking how to use the rest API as its been almost 2 weeks and I'd really like to learn this.
First off I'll say that I've successfully been able to get an access_token I have no problem doing that. The issue is that when I try to use an a Send Endpoint(https://www.dwolla.com/developers/endpoints/accountapi/send) basically trying to send money to and account. My exact issue is that I can never get a successful response; only false or error message responses.
So on the index page I have "Add funds to your account" link. Users will click that link and it will take them to the Dwolla Page that will accept them to Sign in to their Dwolla account an then accept the permissions the website is asking for. After the user presses "Accept" it will redirect to the selected URL that I chose and send back an access_token to use for authorization purposes. Here is my code (This is the page that Dwolla redirects too and sends the access_token too)
<?php
//Define variables
$key = 'redacted';
$secret = 'redacted';
$dwolla_client_id = urlencode($key);
$dwolla_secret_key = urlencode($secret);
$code = urlencode($_GET["code"]);
//get token
$retireve_token = file_get_contents("https://www.dwolla.com/oauth/v2/token?client_id=".$dwolla_client_id."&client_secret=".$dwolla_secret_key."&grant_type=authorization_code&redirect_uri=http://localhost/purchase_order.php&code=".$code);
$decoded_json = json_decode($retireve_token, true);
var_dump($decoded_json);
if($decoded_json["access_token"]){
$arr = '{
"oauth_token": "'.$decoded_json["access_token"].'",
"fundsSource": "balance",
"pin": "1111",
"notes": "Payment for services rendered",
"amount": 1.01,
"destinationId": "812-111-1111",
"assumeCosts": false,
"facilitatorAmount": 0,
"destinationType": "dwolla"
}';
$opts = array('http'=>array('method'=>"POST",'content'=> $arr, 'header' => 'Content-Type: application/json'));
$ctx = stream_context_create($opts);
$send_request = file_get_contents('https://www.dwolla.com/oauth/rest/accountapi/send', false, $ctx);
var_dump(json_decode($send_request));
}
?>
I receive messages like this for example
array(1) { ["access_token"]=> string(50)
"redacted" } Warning:
file_get_contents(https://www.dwolla.com/oauth/rest/accountapi/send):
failed to open stream: HTTP request failed! HTTP/1.1 503 Service
Unavailable in /home/swiftbitcoins/purchase_order.php on line 47 NULL
what you are trying to make is a get request whereas Dwolla documentation refers to this as post request.
better you can do is user their php Library with built in methods to make calls. this is a standard library for making restful calls and much better than writing the way you have written in the code snippet above.
https://github.com/Dwolla/dwolla-php

Requesting user email from Google Api returns unauthorized 401 error

I try to connect to google API and it returns:
failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
I requested for access token and it returned me xxx, after that I connect to Google API by following PHP code:
$opts = array('http' =>
array(
'method' => 'GET',
'header' => "Authorization: OAuth $access_token\r\nContent-Type: application/json\r\n",
)
);
$context = stream_context_create($opts);
$result = file_get_contents('https://www.googleapis.com/userinfo/email?alt=json',false,$context);
Where is mistake did I write wrongly headers, or something else?
Update: $access_token is a value which I got in json by requesting it.
You don't need the content type header for a GET request.
You need to query this URL to get the User Info: https://www.googleapis.com/oauth2/v2/userinfo
Make sure that the $access_token value contains an correctly authorized access token, for that you need your user to go through an OAUth 2.0 flow.
All of this is all documented there: https://developers.google.com/accounts/docs/OAuth2Login
Check how to do it in php, but when logging your client to Google you must set the RequestPermission parameter so you can get info from user's profile
requestPermissions: 'https://www.googleapis.com/auth/userinfo.profile'

Categories