woocommerce api v2 returns uncaught exception - php

Using wc-api (https://github.com/woocommerce/wc-api-php)
My client function: (literally the same as in docs)
$woocommerce = new Client(
$store_url, // Your store URL
$consumer_key, // Your consumer key
$consumer_secret, // Your consumer secret
[
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v2', // WooCommerce WP REST API version
'query_string_auth' => true // Force Basic Authentication as query string true and using under HTTPS
]
);
and when I try with
$results = $woocommerce->get('');
or
$results = $woocommerce->get('products');
or any other endpoint it gives me:
An uncaught Exception was encountered
Type: Automattic\WooCommerce\HttpClient\HttpClientException
Message: Error: No route was found matching the URL and request method
[rest_no_route]
If I change the version to 'wc/v1' it is working ok.
Do I need to add some other plugins or additional code to make v2 work?

Try send your request like this, with your creds in param :
$res = ($woocommerce->get('orders?status=processing&consumer_key=ck_XXXXXXXXXXXXXXXXXXXXXXXXX&consumer_secret=cs_XXXXXXXXXXXXXXXXXXXXXXXXX'));

Related

TheNetworg oAuth2 to Microsoft Graph reports token expired while it's not

I am trying to build a simple MS Graph API call to get familiar with Graph.
However, I can't get it to work. MS Graph keeps giving the error that my token has expired, while it's not.
Code:
<?php
require_once('C:\inetpub\site6\vendor\autoload.php');
// Using newest version of TheNetworg Oauth2
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
'clientId' => '***************',
'clientSecret' => '**********',
'redirectUri' => 'https://app2.***/test.php'
]);
// Set to use v2 API, skip the line or set the value to Azure::ENDPOINT_VERSION_1_0 if willing to use v1 API
$provider->defaultEndPointVersion = TheNetworg\OAuth2\Client\Provider\Azure::ENDPOINT_VERSION_2_0;
$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);
//echo $baseGraphUri;
$provider->tenant = '*********.onmicrosoft.com'; //Azure AD ID
$provider->authWithResource;
$provider->scope = $baseGraphUri . '/.default';
$token = $provider->getAccessToken('client_credentials', ['scope' => $provider->scope]);
// echo $token;
// Set up our request to the API
$ref= 'users/someuser#mytenant.com';
$response = $provider->get($ref, $token, $headers = []);
// Store the result as an object
$result = json_decode( $response->getBody() );
?>
But I keep getting ended up with error:
PHP Fatal error: Uncaught
League\OAuth2\Client\Provider\Exception\IdentityProviderException:
Your access token has expired. Please renew it before submitting the
request. in
C:\inetpub\site6\vendor\thenetworg\oauth2-azure\src\Provider\Azure.php:394
What am I doing wrong? When I google the error, I get a lot of results telling that I am trying to access MS Graph with an Azure AD Graph token, but when I do echo $baseGraphUri; I really tells me graph.microsoft.com.
I found out what the error is. Although I use "$baseGraphUri = $provider->getRootMicrosoftGraphUri(null);", the library still connects to the Azure AD API instead of the Microsoft Graph API. So it authenticates with the wrong kind (aud) of token.
Adding this line fixed the problem:
$provider->urlAPI = 'https://graph.microsoft.com/';

PHP: How to make an api call with api key authorization using Guzzle?

I'm trying to create a client to connect an IBM-Watson bot service using Guzzle for an application constructed in Laravel, but it fails when attempting to create a new session of the service, I got the error 401: Unauthorized. I'm not using basic authorization, instead I'm trying to connect by api-key authorization.
function start_bot_session() {
//Api Key de Watson.
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//ID bot (Watson).
$assistant_id = '9c1c426d-cd33-49ec-a3bc-f0835c3264b5';
//URL service.
$url = 'https://gateway.watsonplatform.net/assistant/api/v2/assistants/';
//Method for start a new session.
$method = $assistant_id.'/sessions?version=2019-02-28';
$client = new \GuzzleHttp\Client(["base_uri" => $url]);
$response = $client->request('POST', $method, [
'headers' => [
'Authorization:' => $api_key
]
]);
return response;
}
Is there any way I can fix this?
Can you tell me some alternatives to make api call instead of using Guzzle?

Woocommerce Rest API: Error: An error occurred in the request and at the time were unable to send the consumer data

I am integrating Woo-commerce API's in my Laravel 5.6 site using Woo-commerce official rest sdk. I made a link using authentication endpoint URL.Which is mention at here .
When user clicks the link it takes the user to Woo-commerce authentication page, where user login and Approve the request.
After approving the request it should take me to return url which i mention in the link. Instead it shows me the following error.
Error: An error occurred in the request and at the time were unable to send the consumer data.
Here is my code.
`$store_url = 'YourStoreUrl';
$endpoint = '/wc-auth/v1/authorize';
$params = [
'app_name' => 'YourApplicationName',
'scope' => 'read_write',
'user_id' => 'yourUserId',
'return_url' => 'YourStoreUrl/callbackurl',
'callback_url' => 'YourStoreUrl/returncallback'
];
$query_string = http_build_query( $params );
$url = $store_url . $endpoint . '?' . $query_string;`
For future users who may have this same problem, ensure that your callback_url is correct. The error is mostly due to the callback_url.
In my case, I initially had this piece of python code:
store_url = 'http://localhost/wordpress'
endpoint = '/wc-auth/v1/authorize'
params = {
"app_name": "My app",
"scope": "read_write",
"user_id": 123,
"return_url": "http://localhost/wordpress/",
"callback_url": "https://f46c7c857579.ngrok.io",
}
query_string = urlencode(params)
return "%s%s?%s" % (store_url, endpoint, query_string)
But my callback_url was wrong. When I put in the correct callback_url, the error vanished. callback_url": "https://f46c7c857579.ngrok.io/return"
Also, make sure your callback_url has the POST HTTP METHOD

AWS Cognito Developer Authentication in PHP

Am trying to implement developer authentication using the PHP SDK but keep getting this error:
Fatal error: Uncaught
Aws\CognitoIdentity\Exception\CognitoIdentityException: AWS Error
Code: AccessDeniedException, Status Code: 400, AWS Request ID:
da162f98-fb50-11e4-937e-0bf2642a4752, AWS Error Type: client, AWS
Error Message: User: arn:aws:iam::256661818246:user/tester is not
authorized to perform:
cognito-identity:GetOpenIdTokenForDeveloperIdentity on resource:
arn:aws:cognito-identity:us-east-1:256661818246:identitypool/us-east-1:69767873-2de2-4cc7-a78f-3d18b5e9bf71,
User-Agent: aws-sdk-php2/2.8.3 Guzzle/3.9.3 curl/7.20.0 PHP/5.3.6
thrown in
/var/www/html/aws/Aws/Common/Exception/NamespaceExceptionFactory.php
on line 91
This is my sample code:
<?php
session_start();
//Include AWS client libs
require (dirname(__DIR__).'/aws/aws-autoloader.php');
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
/* Global Vars */
$aws_region = 'us-east-1';
$aws_key = '<AWS_KEY>';
$aws_secret = '<AWS_SECRET>';
$aws_account_id = '<AWS_ACCOUNT_ID>';
$identity_pool_id = 'us-east-1:xxxx-xxxx-xxxx-xxxx';
//Initialize a Cognito Identity Client using the Factory
$client = CognitoIdentityClient::factory(array('region' => $aws_region, 'key' => $aws_key, 'secret' => $aws_secret));
/* Acquire new Identity */
$identity = $client->getOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $identity_pool_id, 'Logins' => array('login.custom.traffic' => 'jkljkasdjk')));
//Obtain Identity from response data structure
$id = $identity->get('IdentityId');
echo "IdentityId: ".$id;
?>
I suspect the error occurs while trying to get the developer Identity. What am I missing?
Reason behind this error is there might be no policy attached to the IAM user 'tester'.
You can attach an already existing policy 'AmazonCognitoDeveloperAuthenticatedIdentities' from IAM console which gives this user access to Cognito APIs including 'getOpenIdTokenForDeveloperIdentity' as well.

Bad Request when submitting Guzzle POST to Bit Bucket Access Token Endpoint

I have been trying to implement a simple authentication flow using OAuthv1.a and bit bucket. My issue occurs when I make a request for access tokens using the previously supplied verifier and oauth_token. I am always given a 400 error with no real indication as to why.
Client error response
[status code] 400
[reason phrase] BAD REQUEST
[url] https://bitbucket.org/api/1.0/oauth/access_token?oauth_consumer_key=<snip>&oauth_nonce=fba24cfb3147ca7d32b3924fad43fd509bbb9bc1&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1381034857&oauth_token=fFz369NUmCHNyn7PGj&oauth_verifier=6724267371&oauth_version=1.0&oauth_signature=1H7%2Bvx0fVh2Sj%2FcDAE2QzkTx8us%3D
I am using the OauthPlugin class within guzzle to build signed parameters and submitting post requests as described in the documentation. Has anyone had an issue like this with any other OAuthv1 provider or Bit Bucket specifically?
$client = new Client('https://bitbucket.org/api/1.0/');
$oauth = new OauthPlugin( array(
'request_method' => OauthPlugin::REQUEST_METHOD_QUERY,
'consumer_key' => Config::get('oauthv1.key'),
'token' => Input::get('oauth_token'),
'verifier' => Input::get('oauth_verifier')
)
);
$client->addSubscriber($oauth);
$client->post('oauth/access_token')->send();
Even though the Bitbucket API documentation doesn't mention it, the call to the oauth/access_token endpoint also requires the consumer_secret and oauth_token_secret. The consumer secret is generated by Bitbucket when you create your app and should be stored in your config. You can get the oauth_token_secret from the response of the call to oauth/request_token. Just save it in the session so you can use it when getting the access token.
Request a request token:
$client = new Client('https://bitbucket.org/api/1.0');
$oauth = new OauthPlugin(array(
'consumer_key' => $app['bitbucket.key'],
'consumer_secret' => $app['bitbucket.secret'],
'callback' => 'http://mysite.local/callback',
));
$client->addSubscriber($oauth);
$response = $client->post('oauth/request_token')->send();
// Parse the response
parse_str($response->getBody(), $result);
// Save the token secret in the session
$app['session']->set('oauth_token_secret', $result['oauth_token_secret']);
// Redirect to Bitbucket to authorize the application
return $app->redirect(sprintf('https://bitbucket.org/api/1.0/oauth/authenticate?oauth_token=%s', $result['oauth_token']));
Request an access Token:
$token = $app['request']->get('oauth_token');
$verifier = $app['request']->get('oauth_verifier');
$tokenSecret = $app['session']->get('oauth_token_secret');
$client = new Client('https://bitbucket.org/api/1.0');
$oauth = new OauthPlugin(array(
'consumer_key' => $app['bitbucket.key'],
'consumer_secret' => $app['bitbucket.secret'],
'token' => $token,
'token_secret' => $tokenSecret,
'verifier' => $verifier,
));
$client->addSubscriber($oauth);
$client->post('oauth/access_token')->send();
// Parse the response
$response = parse_str($response->getBody(), $result);
// Get the access token
$accessToken = $result['oauth_token'];

Categories