Using Oauth with GuzzleHttp and Magento API in PHP - php

I'm trying to access Magento's REST API in PHP, using Oauth and GuzzleHttp.
I'm basing my example off of this Twitter example:
https://github.com/guzzle/oauth-subscriber
My code so far is:
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use GuzzleHttp\Client;
$client = new Client(array(
'base_url' => 'http://magento',
'defaults' => array('auth' => 'oauth')
));
$oauth = new Oauth1(array(
'consumer_key' => 'magento_key',
'consumer_secret' => 'magento_secret'
));
$client->getEmitter()->attach($oauth);
$response = $client->post('/oauth/initiate');
print_r($response);die();
My host is http://magento. I'm trying to POST my key and secret to /oauth/initiate like is says in the Magento docs.
http://www.magentocommerce.com/api/rest/authentication/oauth_authentication.html#OAuthAuthentication-AuthenticationEndpoints
Does anyone have any insight on what I might be doing wrong? I'm getting a 500 error using Firefox's RESTClient to make this call.
EDIT:
I'm now getting this exception thrown
{
"response": "Client error response [url] http://magento/oauth/initiate [status code] 400 [reason phrase] Bad Request"
}
It's getting a 400 from http://magento/oauth/initiate but this is only when using GuzzleHttp and Oauth. If I make the POST directly within RESTClient as http://magento/oauth/initiate, I get an error response from Magento itself (so it does not 400), and if I add all the necessary params I get the appropriate token responses.
UPDATE:
After inspecting the exception being thrown I'm seeing my authorization array does not conain my callback url. This is suppose to be http://magento/oauth/authorize which I've adde in the RESTClient and it works with the token response. Iv'e tried adding this in my $oauth array as 'callback' and 'oauth_callback' but neither seem to work. I can see this appears in the exception, under my data array, but not in the [authorize] array which I believe it needs to be. I tihnk that's what's missing, if someone has an idea of where it needs to be placed.

Related

DocuSign API (PHP SDK) - Why do I get this response? "Error while requesting server, received a non successful HTTP code [302] with response Body:"

I'm trying to use the DocuSign PHP SDK to send a signing request based on a template. I am attempting to follow the steps outlined in this example: https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-template-remote
To authenticate, I am using a JWT. I assembled a header and payload signed with RSA256 private key generated by DocuSign, and the access token I received in response is in this format:
eyJ0eXAiOiJ-----.yyyyyy-----.zzzzzz-----
(Example, actual token is much longer).
When I try to run this code here (putting in the above access token and my DocuSign credentials as the arguments):
private function worker($args)
{
$envelope_args = $args["envelope_args"];
# Create the envelope request object
$envelope_definition = $this->make_envelope($envelope_args);
# Call Envelopes::create API method
# Exceptions will be caught by the calling function
$config = new \DocuSign\eSign\Configuration();
$config->setHost($args['base_path']);
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$api_client = new \DocuSign\eSign\client\ApiClient($config);
$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);
try {
$results = $envelope_api->createEnvelope($args['account_id'], $envelope_definition);
$envelope_id = $results->getEnvelopeId();
}
catch(ApiException $apiException) {
echo $apiException->getMessage();
}
return ['envelope_id' => $envelope_id];
}
Then I end up catching an exception:
Error while requesting server, received a non successful HTTP code [302] with response Body:
Digging a little deeper and var_dumping the response, the body is indeed empty and here are the response headers:
array(
0 => string 'HTTP/1.1 302 Found'
'Cache-Control' => string 'no-cache'
'Content-length' => string '0'
'Location' => string 'https://account-d.docusign.com/v2.1/accounts/6d7dc630-xxxx-xxxx-xxxx-xxxxxxxxxxxx/envelopes'
'Connection' => string 'close'
)
I have blocked out the the number in the Location section of the response in case it's anything sensitive. Being new to the DS API, I am unclear what this number is. It's not anything I have defined in my configuration for the project.
Does anyone have any idea what this error message indicates? Am I trying to access an incorrect API endpoint? Does this indicate my JWT access token is invalid? Something else?
Thanks for any help you can provide.
A better technique is to use the php quickstart and then copy the example that creates an envelope from a template
Re your current code: I'd check your base path.
Also check your access token. Your software is being redirected to the account server

PHP - Guzzle Strange trouble

I am using last version of PGP Guzzle HTTP... Very simple test done :
use GuzzleHttp\Client;
$client = new Client();
$res = $client->post('https://MYAPI/cards/XXX/credit',[
'headers' => ['Authorization' => 'Token MYTOKEN'],
'json' => [
"amount" => 10,
"reason" => "Because"
]
]);
var_dump($res);
returned a Exception:
GuzzleHttp\Exception\ClientException : Client error: `POST
https://MYAPI/cards/XXX/credit` resulted in a `405 Method Not Allowed`
response:
{"detail":"Méthode \"GET\" non autorisée."}
Any idea ? the REST API server I am calling is made with Django DRF. But this is nonsense to think it might be incompatible....
Thanxs for any idea.
You get very clear error that the server doesn't accept POST request. I don't know, is it right or not. If have control over the server also, you check the code there, maybe it's just a bug in it.
Basically you cannot talk about compatibility or incompatibility, because it's just simple HTTP and it works. You can have an issue either in communications between you and the server developers or a bug in the server.
Well, it was neither Guzzle nor DRF whiche failed.... only one parameter in DRF urls that does not accept trailing / in rest entry points....
simply adding / after the credit url and everything worked fine....
Strange behaviour somehow for DRF to display this kind of misleading error message .

"Empty Payload. JSON content expected" error calling Microsoft Graph (Guzzle & PHP)

I am trying to call the Microsoft Graph API to reset a passcode on a device registered with Intune. Unfortunately when I go to make the call, I receive an error stating that the JSON Payload is empty. The specific endpoint does not require a JSON payload, in fact it says to not include a body at all.
I attempted to add some JSON to see if that would satisfy the error, and I still receive the same error message.
Here is the call I am making:
$client = new Client();
try{
$client->post('https://graph.microsoft.com/beta/managedDevices/12345resetPasscode', [
'headers' => [
'Authorization' => 'Bearer 12345',
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'json' => json_encode(['hello' => 'world']),
]
]);
} catch (\GuzzleHttp\Exception\ClientException $e) {
dd($e->getResponse()->getBody()->getContents());
}
Here is the error I am receiving:
"Bad Request: Empty Payload. JSON content expected."
https://i.stack.imgur.com/gwwtJ.png
Here is the API Documentation I am working off: https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/intune_devicefe_manageddevice_resetpasscode
Using PHP 7 & Guzzle 6
Any help is appreciated!
I'm an engineer on the Microsoft Intune team, working on the integration between Microsoft Graph and Intune.
It looks like there is an error in the documentation (I will make sure that is fixed). The correct URL You should be using is:
https://graph.microsoft.com/beta/managedDevices/12345/resetPasscode
Where 12345 is a the id of the device.
Hope that resolves your issue
Peter

Create Listing in Etsy using PHP api not working

I'm creating a listing into Etsy using php oAuth.I'm sending following params to api call "quantity,title,description,price,who_made,when_made,is_supply".
I'm following the document as reference here
This is the process flow
Authenticating with etsy using oAuth.
Getting scopes using this api call https://openapi.etsy.com/v2/oauth/scopes
These are working fine.But while creating listing i'm getting following error.
"Invalid auth/bad request (got a 403, expected HTTP/1.1 20X or a redirect)"
3.The process I followed for create listing
$url = "https://openapi.etsy.com/v2/listings/";
$params = array('description' => 'thisisdesc', 'price'=>'1.00', 'quantity'=>'2', 'title'=>'thisistitle', 'who_made'=>'collective', 'is_supply'=>'false','when_made'=>'2010_2015', 'category_id' => '69105467','shipping_template_id' => '110906760173');
$data = $oauth->fetch($url, $params , OAUTH_HTTP_METHOD_POST);
$json = $oauth->getLastResponse();
print_r($json);
It displays error message.Invalid auth/bad request.
Any ideas/suggestions please.
Change
$url = "https://openapi.etsy.com/v2/listings/";
to
$url = "https://openapi.etsy.com/v2/listings";
The extra / at the end may be causing the issue
Can you try removing the '/' and if possible show the response details.

PHP 5.4 Implementation of the Discogs API

In PHP 5.4 Implementation of the Discogs API (https://github.com/ricbra/php-discogs-api) there is example how to get $response = $client->search(['q' => 'Meagashira']); working with oauth1. The example states:
$oauth = new GuzzleHttp\Subscriber\Oauth\Oauth1([
'consumer_key' => $consumerKey, // from Discogs developer page
'consumer_secret' => $consumerSecret, // from Discogs developer page
'token' => $token['oauth_token'], // get this using a OAuth library
'token_secret' => $token['oauth_token_secret'] // get this using a OAuth library
]);
The consumer_key and consumet_secret is given in the discogs app setting. How do I get token and token_secret? I try to make this example code working from command line but I get bunch of exceptions mostly:
PHP Fatal error: Uncaught exception
'GuzzleHttp\Exception\ClientException' with message 'Client error
response [url] http://api.discogs.com/database/search?q=Metallica
[status code] 401 [reason phrase] Unauthorized' in
/var/www/darkplanet/vendors/composer/guzzlehttp/guzzle/src/Exception/RequestException.php:
Disclaimer: I'm the author of the Discogs API PHP client.
Recently I've updated the README.md with a link to an example implementation which can be used as starting point. You can find this example implementation at: https://github.com/ricbra/php-discogs-api-example

Categories