WooCommerce Rest API gives syntax error - php

I'm working on a side project and I've been trying to interact with the WooCommerce REST API.
I have everything seemingly correct. I've created the proper keys because they work with cURL. But when I try to utilize the php-wrapper, provided by Automattic, everything stops working.
I have the code set up exactly like they've instructed:
require DIR . '/../vendor/autoload.php';
use Automattic\WooCommerce\Client;
$woocommerce = new Client(
'https://mywebsitenamegoeshere.com',
'##########',
'##########',
[
'wp_api' => true,
'version' => 'wc/v2',
'query_string_auth' => true
]
);
I'm simply trying to do a request to list the endpoints (which also works with cURL) but as soon as I attempt to interact via the php-wrapper I get this error message:
Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Syntax error' in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:346
Stack trace: #0 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(385): Automattic\WooCommerce\HttpClient\HttpClient->processResponse()
#1 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('', 'GET', Array, Array)
#2 /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/ticket-data-test-template.php(15): Automattic\WooCommerce\Client->get('')
#3 /nas/content/live/wwitssltest/wp-includes/template-loader.php(74): include('/nas/content/li...')
#4 /nas/content/live/wwitssltest/wp-blog-header.php(19): require_once('/nas/content/li...')
#5 /nas/content in /nas/content/live/wwitssltest/wp-content/themes/twentyseventeen/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 346
When I look in the files, specifically HttpClient.php the most specific information I can come across is that the JSON might not be formatted properly?
The documentation seems pretty cut and dry but nothing I do makes any difference.
With the exception of <php print_r( $woocommerce ); ?> which returns the Client object.

You're missing a comma after query_string_auth' => true.
It should be: query_string_auth' => true.
Cheers!

Related

Shopify - Custom PHP app gives Missing Authorization key error

I am trying to build a custom Shopify app in my Shopify admin.
I am using Shopify's official PHP library.
I have successfully initialized the library.
Now when I try to connect to the API I am getting the following error:
Fatal error: Uncaught Shopify\Exception\MissingArgumentException: Missing Authorization key in headers array in /www/doc/www.sozialstar.de/www/script/vendor/shopify/shopify-api/src/Auth/OAuth.php:226 Stack trace: #0 /www/doc/www.sozialstar.de/www/script/vendor/shopify/shopify-api/src/Utils.php(160): Shopify\Auth\OAuth::getCurrentSessionId(Array, Array, true) #1 /www/doc/www.sozialstar.de/www/script/shopifytest.php(29): Shopify\Utils::loadCurrentSession(Array, Array, true) #2 {main} thrown in /www/doc/www.sozialstar.de/www/script/vendor/shopify/shopify-api/src/Auth/OAuth.php on line 226
Here is my PHP code:
$requestHeaders = array('api_version'=>'2022-10', 'X-Shopify-Access-Token'=>'mytoken');
$requestCookies = array();
$isOnline = true;
$this->test_session = Utils::loadCurrentSession(
$requestHeaders,
$requestCookies,
$isOnline
);
I am doing this based on Shopify API docs.
Why is it not working?
It seems like the Shopify API for PHP expects you to set the Authorization header field/ doesn't support X-Shopify-Access-Token. Try this instead:
$requestHeaders = array(
'api_version'=>'2022-10',
'Authorization'=>'Bearer YOUR_ACCESS_TOKEN'
);

how to get dutchie graphQL api working with php

I am working to get response from dutchie GrapghQL api using PHP, These are working fine with POSTMAN , but when I am trying to get them work with below Library , its not working at all, and there is very less documentation available for dutchie(php graghql)
https://github.com/webonyx/graphql-php/
Before I have worked on rest apis with php MySQL, its totally new thing to me so not getting how get it work
Postman working image
<?php
include("library/graphQL/vendor/autoload.php");
use GraphQL\Client;
use GraphQL\Exception\QueryError;
$client = new Client(
'https://plus.dutchie.com/plus/2021-07/graphql',
["Authorization" => "public- eyJhbGciOiJIUzI1NiJ9."]
);
// Create the GraphQL mutation
$gql = (new Mutation('Ping'))
->setSelectionSet(
[
'id',
'time',
]
);
// Run query to get results
try {
$results = $client->runQuery($gql);
}
catch (QueryError $exception) {
// Catch query error and desplay error details
print_r($exception->getErrorDetails());
exit;
}
Display original response from endpoint
var_dump($results->getResponseObject());
Display part of the returned results of the object
var_dump($results->getData()->pokemon);
Reformat the results to an array and get the results of part of the array
$results->reformatResults(true);
print_r($results->getData()['data']);
Error I am getting
Fatal error: Uncaught Error: Class 'Mutation' not found in
C:\xampp\htdocs\dispoapi\index.php:21 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\dispoapi\index.php on line 21
For me, the fix was to include the class, like this:
$gql = (new GraphQL\Mutation('Ping'))
Notice the "GraphQL\" in front of "Mutation"? If you don't setup an alias for "Mutation", then that has to be added in front of it.
Otherwise, this has to come after the "GraphQL" library include:
use GraphQL\Mutation;

Get Monolog JSON Stack Trace as Array

I'm using Laravel 4.2 and want to get logs out as JSON. Laravel uses Monolog, so I've configured the JSON formatter like so:
$logHandler = new Monolog\Handler\StreamHandler(Config::get('app.logFile'), Monolog\Logger::DEBUG);
$logHandler->setFormatter(new Monolog\Formatter\JsonFormatter);
Log::getMonolog()->pushHandler($logHandler);
The problem is that stack traces are included as part of the message string, like so:
{
"message": "exception 'Exception' with message 'Socket operation failed: Host name lookup failure' in /var/www/vendor/clue/socket-raw/Socket/Raw/Socket.php:388\nStack trace:\n#0 /var/www/vendor/clue/socket-raw/So..."
}
Can someone point me in the right direction to make the stack trace its own separate array in the json?
Long overdue update:
The primary problem is that Laravel, and lots of code following its example, tries to log the exception by itself, e.g., Log::error($e). This is the wrong way to log an exception with Monolog. That first parameter is supposed to be a simple message string. In processing it, Monolog\Logger::addRecord() explicitly casts the message to a string:
$record = array(
'message' => (string) $message,
//...
);
If $message is actually an exception, you get the whole stack trace as a string. Unfortunately, this is what Laravel's default exception handler does.
The correct way to get a stack trace as an array is to pass the exception in as context so that it's available non-stringified to the formatter. For instance:
Log::error($e->getMessage(), ['exception' => $e]);
Something equivalent is what you need to put in your custom exception handler for Laravel, and then you can use a proper JSON formatter and get what you except.

How do I dump variables in Yii for debugging?

How do I dump and print variables in Yii for debugging? I would like to use var_dump() or print_r(). I tried to use Yii::trace() but it crashes with this error in runtime/logs/app.log. It doesn't even tell me the line in my code that it fails.
2015-03-18 20:54:11 [::1][-][-][warning][yii\log\Dispatcher::dispatch] Unable to send log via yii\debug\LogTarget: Exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
in /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php:58
Stack trace:
#0 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php(58): serialize(Array)
#1 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2-debug/LogTarget.php(112): yii\debug\LogTarget->export(Array)
#2 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2/log/Dispatcher.php(183): yii\debug\LogTarget->collect(Array, true)
#3 /cygdrive/c/Users/Chloe/workspace/AffiliateArbitrage/vendor/yiisoft/yii2/log/Logger.php(170): yii\log\Dispatcher->dispatch(Array, true)
#4 [internal function]: yii\log\Logger->flush(true)
#5 {main}
Reference
http://www.yiiframework.com/doc-2.0/guide-runtime-logging.html
Because you are asking about something like var_dump and print_r, I can advise built-in helper for this. It's called yii\helpers\VarDumper. Yii::trace() is for logging trace messages.
VarDumper is intended to replace the buggy PHP function var_dump and print_r.
It can correctly identify the recursively referenced objects in a
complex object structure. It also has a recursive depth control to
avoid indefinite recursive display of some peculiar variables.
VarDumper can be used as follows,
VarDumper::dump($var);
Personally I don't use it, just tried only couple of times for testing.
I think is better to use Xdebug for that purposes.
See also PsySH.
Use this:
<?php echo '<pre>'; print_r($model); exit; ?>
I used this, but I'm sure there's a better way.
Yii::warning('**********************', var_export($category,true));
config/web.php
'log' => [
...
'flushInterval' => 1, // for debug
'targets' => [
[
...
'exportInterval' => 1, // for debug - slow
],
],
],
Use this, to see your variable or object array.
use yii\helpers\VarDumper;
VarDumper::dump($variableArray , $dept = 10, $highlight = true);
To detail you can read the doc
http://www.yiiframework.com/doc-2.0/yii-helpers-basevardumper.html#dump()-detail
You can do it yourself:
In your main index page (back/index.php or front/index.php) add this code to the top ob_start();. Then define 2 functions for better debugging
function dd($v){
ob_clean();
var_dump($v);
exit;
}
function dj($v){
ob_clean();
echo CJSON::encode($v);
exit;
}
and add ob_end_flush(); at the very end of your main index page . Now you can call dd($model) or dj($model). There you had your dumper working. Congratulations!
I had written an article about this problem with debug variables in Yii 2:
Since for the sake of Simplicity and Quick Development, I’ve created a helper for those who use Yii. You can just call dd($var1, $var2, ….); for dump & die or d($var1, $var2, ….); for dump data.
Details and installation instructions are on: https://dangnhsite.wordpress.com/2016/04/06/variable-debug-in-yii-2/

Yii2 app\controllers\response not found using yii2-widget-depdrop extension

I am new to yii2 and php web app development. I am using dep-drop for selecting input
depending on parent selection. Now I get an error message in yii2 debugger,
exception 'yii\base\ErrorException' with message 'Class 'app\controllers\Response' not found' in G:\xampp\htdocs\project\controllers\SalesOrderController.php:129 Stack trace: #0 [internal function]: yii\base\ErrorHandler->handleFatalError() #1 {main}
Just adding an update because at least in one hand the answer from above can be misleading.
I think that beside issue you mentioned above you had additional issue which is resolved by adding "use yii\helpers\Json;" or something similar because Response is not within namespace you mentioned.
If you want to have a Json Output from your controller and if you want to use Response class for managing action output you will need to use
use yii\web\Response;
Additionally, example of usage:
public function actionApi() {
Yii::$app->response->format = Response::FORMAT_JSON;
return array(
"test" => "test",
"test2" => "test2"
);
}
Sorry It was my mistake.
I just included this :
use yii\helpers\Json;
Problem Solved. And dep dropdown is now working as expected
please use this code.
use yii\web\Response;

Categories