GithubHelp home page GithubHelp logo

laravel-magento-client's Introduction

Banner

Laravel Magento Client

Tests Coverage Analysis Total downloads

A client to communicate with Magento from your Laravel application.

<?php

class Example
{
    public function __construct(
        protected \JustBetter\MagentoClient\Client\Magento $magento,
    ) {
    }

    public function retrieveProduct()
    {
        $response = $this->magento->get('products/1');
    }

    public function retrieveOrdersLazily()
    {
        $retrievedOrders = [];

        $searchCriteria = \JustBetter\MagentoClient\Query\SearchCriteria::make()
            ->where('state', 'processing');

        foreach ($this->magento->lazy('orders', $searchCriteria->get()) as $order) {
            $retrievedOrders[] = $order['increment_id'];
        }
    }

    public function multipleConnections()
    {
        $this->magento->connection('connection_one')->get('products/1');
        $this->magento->connection('connection_two')->get('products/1');
    }
}

Looking to synchronize prices or stock to Magento?

Installation

Are you coming from grayloon/laravel-magento-api? We have written a migration guide!

Require this package:

composer require justbetter/laravel-magento-client

Configuration

Add the following to your .env:

MAGENTO_BASE_URL=
MAGENTO_ACCESS_TOKEN=

Optionally, publish the configuration file of this package.

php artisan vendor:publish --provider="JustBetter\MagentoClient\ServiceProvider" --tag=config

Multiple connections

This package supports connecting to multiple Magento instances. In the configuration file you will find an array with the connections where you can configure each connection.

    'connection' => 'default',
    'connections' => [
        'default' => [
            /* Base URL of Magento, for example: https://magento.test */
            'base_url' => env('MAGENTO_BASE_URL'),

           // Other settings
        ],
        'another_connection' => [
            'base_url' => env('ANOTHER_MAGENTO_BASE_URL'),

            // Other settings
        ],
    ],

The connection setting sets which connection is used by default. You can switch connections by using the connection method on the client.

/** @var \JustBetter\MagentoClient\Client\Magento $client */
$client = app(\JustBetter\MagentoClient\Client\Magento::class);

$client->connection('connection_one')->get('products');

Authentication

By default, this packages uses Bearer tokens to authenticate to Magento. Since Magento 2.4.4, this method of authentication requires additional configuration in Magento as described here.

It is recommended to authenticate to Magento using OAuth 1.0 which will also prevent the additional configuration requirements, besides setting up the integration itself.

Setting up OAuth 1.0

Start by adding the following variable to your .env-file.

MAGENTO_AUTH_METHOD=oauth

Note that you can also remove MAGENTO_ACCESS_TOKEN at this point, as it will be saved in a file instead.

Next, open Magento and create a new integration. When configuring, supply a Callback URL and Identity link URL. If you have not made any changes to your configuration, these are the URLs:

Callback URL:      https://example.com/magento/oauth/callback/{connection}
Identity link URL: https://example.com/magento/oauth/identity/{connection}

connection is the key in your connections array in the configuration file.

When creating the integration, Magento will send multiple tokens and secrets to your application via the callback-endpoint. This information will be saved in the database, as configured in magento.php. You may adjust this to save the key in a JSON file or create your own implementation Magento will redirect you to the identity-endpoint in order to activate the integration.

For more information about OAuth 1.0 in Magento, please consult the documentation.

Identity endpoint

Caution

Be sure to add your authentication middleware

Note that the identity-endpoint does not have any authentication or authorization middleware by default - you should add this in the configuration yourself. If you do not have any form of protection, anyone could change the tokens in your secret file.

It is recommended that only administrators of your application are allowed to access the identity endpoint.

Usage

You can get an instance of the client by injecting it or by resolving it:

<?php

public function __construct(
    protected \JustBetter\MagentoClient\Client\Magento $magento
) {

}

// OR

/** @var \JustBetter\MagentoClient\Client\Magento $client */
$client = app(\JustBetter\MagentoClient\Client\Magento::class);

After you got an instance you can use the graphql, get, post, put and patch methods to use the Magento API.

SearchCriteria / Filtering

To easily create search criteria you can use the \JustBetter\MagentoClient\Query\SearchCriteria class. For example:

<?php

$search = \JustBetter\MagentoClient\Query\SearchCriteria::make()
        ->select('items[sku,name]')
        ->where('sku', '!=', '123')
        ->orWhere('price', '>', 10),
        ->whereIn('sku', ['123', '456'])
        ->orWhereNull('name')
        ->orderBy('sku')
        ->paginate(1, 50)
        ->get();

You can view more examples in Magento's documentation.

Connections

You can connect to other connections using the connection method on the client.

/** @var \JustBetter\MagentoClient\Client\Magento $client */
$client = app(\JustBetter\MagentoClient\Client\Magento::class);

$client->connection('connection_one')->get('products');
$client->connection('connection_two')->get('products');

GraphQL

You can run authenticated GraphQL queries using the graphql method on the client.

/** @var \JustBetter\MagentoClient\Client\Magento $client */
$client = app(\JustBetter\MagentoClient\Client\Magento::class);

$client->graphql(
    'query searchProducts($search: String) {
        products(
            search: $search
        ) {
            items {
            sku
            }
        }
    }',
    [
        'search' => 'test'
    ]
);

More Examples

You can view the tests for more examples.

Testing

This package uses Laravel's HTTP client so that you can fake the requests.

<?php

Http::fake([
    '*/rest/all/V1/products*' => Http::response([
        'items' => [['sku' => '::some_sku::']],
        'total_count' => 1,
    ]),
]);

Quality

To ensure the quality of this package, run the following command:

composer quality

This will execute three tasks:

  1. Makes sure all tests are passed
  2. Checks for any issues using static code analysis
  3. Checks if the code is correctly formatted

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

JustBetter logo

laravel-magento-client's People

Contributors

indykoning avatar lucassmacedo avatar mennotempelaar avatar ramonrietdijk avatar vincentbean avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-magento-client's Issues

Dependency Injection - newbie question

Hello!

Thank you for contributing your time and talents for this!
I am currently using the greyloon api package and it works well - but I am unfamiliar with how to use your software as a client rather than as a facade. Can you give me a brief example of what it is you are passing to the "Example" class (the $magento object comes from where?)

Thanks and sorry for the newbie question!

Select items - searchCriteria

Hi,

this select return 0 orders

$searchCriteria = \JustBetter\MagentoClient\Query\SearchCriteria::make()
->select(['entity_id','increment_id'])
->where('entity_id', '=', '399824')
->get();

but this return order

$searchCriteria = \JustBetter\MagentoClient\Query\SearchCriteria::make()
->where('entity_id', '=', '399824')
->get();

where is a problem?

Lazy method

It would be nice to implement a lazy method for all requests. Just like the current pre-defined requests

Sort results when retrieving orders

Is there a possibility to sort the results (ASC/DESC) when retrieving orders?
In the Magento docs, you need the searchCriteria[sortOrders] parameter, but I cannot find how to apply this.

Bulk Support

Hello! This package doest have support to bulk requests?

Problem after switching to 2.4 from 1

Hello,

I am having trouble after switching from 1.x to 2.4.

Code parts:

use \JustBetter\MagentoClient\Client\Magento as Magento;
use \JustBetter\MagentoClient\Query\SearchCriteria as MagentoSearchCriteria;
public function __construct(
        protected Magento $magento,
    )
    {
        $this->middleware(['auth']);
    }

$response = $this->magento->get('products/1');

Error thrown on last code above:

JustBetter\MagentoClient\OAuth\KeyStore\KeyStore::instance(): Return value must be of type JustBetter\MagentoClient\OAuth\KeyStore\KeyStore, Illuminate\Foundation\Application returned

Please advise what is going wrong.

Laravel 10
PHP 8.1

Thank you,
Nir

Unable to Activate Integration

Hello.

I am trying to install this package.

Environment:

MacOS 13.4.1
PHP 8.1
Laravel 10.14.1
Magento 2.4.6

Both Laravel & Mage domains are local with .test tld.

.env set with MAGENTO_BASE_URL pointing to local domain
and MAGENTO_AUTH_METHOD=oauth

No issues during installation, but when I am trying to activate the integration at Magento, I get:
The attempt to post data to consumer failed due to an unexpected error. Please try again later.

Debug log:

[2023-07-16T17:03:00.516376+00:00] main.CRITICAL: Laminas\Http\Exception\RuntimeException: Unable to read response, or response is empty in /Users/nir/htdocs/projects/artee/m2/vendor/laminas/laminas-http/src/Client.php:973
Stack trace:
#0 /Users/nir/htdocs/projects/artee/m2/vendor/magento/module-integration/Model/OauthService.php(245): Laminas\Http\Client->send()
#1 /Users/nir/htdocs/projects/artee/m2/vendor/magento/module-integration/Controller/Adminhtml/Integration/TokensExchange.php(59): Magento\Integration\Model\OauthService->postToConsumer('2', 'https://intrane...')
#2 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange->execute()
#3 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->___callParent('execute', Array)
#4 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->Magento\Framework\Interception\{closure}()
#5 /Users/nir/htdocs/projects/artee/m2/generated/code/Magento/Integration/Controller/Adminhtml/Integration/TokensExchange/Interceptor.php(23): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->___callPlugins('execute', Array, Array)
#6 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/Action/Action.php(111): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->execute()
#7 /Users/nir/htdocs/projects/artee/m2/vendor/magento/module-backend/App/AbstractAction.php(151): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http))
#8 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Backend\App\AbstractAction->dispatch(Object(Magento\Framework\App\Request\Http))
#9 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->___callParent('dispatch', Array)
#10 /Users/nir/htdocs/projects/artee/m2/vendor/magento/module-backend/App/Action/Plugin/Authentication.php(145): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#11 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(135): Magento\Backend\App\Action\Plugin\Authentication->aroundDispatch(Object(Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#12 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#13 /Users/nir/htdocs/projects/artee/m2/generated/code/Magento/Integration/Controller/Adminhtml/Integration/TokensExchange/Interceptor.php(32): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->___callPlugins('dispatch', Array, Array)
#14 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/FrontController.php(245): Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#15 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/FrontController.php(212): Magento\Framework\App\FrontController->getActionResponse(Object(Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor), Object(Magento\Framework\App\Request\Http))
#16 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/FrontController.php(147): Magento\Framework\App\FrontController->processRequest(Object(Magento\Framework\App\Request\Http), Object(Magento\Integration\Controller\Adminhtml\Integration\TokensExchange\Interceptor))
#17 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))
#18 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch', Array)
#19 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#20 /Users/nir/htdocs/projects/artee/m2/generated/code/Magento/Framework/App/FrontController/Interceptor.php(23): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array)
#21 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/Http.php(116): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#22 /Users/nir/htdocs/projects/artee/m2/generated/code/Magento/Framework/App/Http/Interceptor.php(23): Magento\Framework\App\Http->launch()
#23 /Users/nir/htdocs/projects/artee/m2/vendor/magento/framework/App/Bootstrap.php(264): Magento\Framework\App\Http\Interceptor->launch()
#24 /Users/nir/htdocs/projects/artee/m2/pub/index.php(30): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http\Interceptor))
#25 {main} {"exception":"[object] (Laminas\\Http\\Exception\\RuntimeException(code: 0): Unable to read response, or response is empty at /Users/nir/htdocs/projects/artee/m2/vendor/laminas/laminas-http/src/Client.php:973)"} []
[2023-07-16T17:03:00.622119+00:00] main.INFO: Broken reference: the 'notification.messages' tries to reorder itself towards 'user', but their parents are different: 'header.inner.right' and 'header' respectively. [] []

Directly accessing identity endpoint at /magento/oauth/identity throws 403 error.

Please advise what I am missing.

Thank you
Regards,

Nir Banerjee

Cant filter created_at by orders

when i try to filter orders by created_at or filter only orders last 7 days i cant get any response
tried > and like
$searchCriteria = SearchCriteria::make()
->paginate($page, 10)
->where('created_at', 'like', '2023')
->get();

Issue with JustBetter\MagentoClient: "Call to undefined method connection()"

Hello,

I am currently encountering an error with the JustBetter MagentoClient in a Laravel project. I have set up multiple connections in the magento.php configuration file as follows:

php
'connections' => [
'default' => [
'base_url' => env('MAGENTO_BASE_URL'),
'base_path' => env('MAGENTO_BASE_PATH', 'rest'),
'store_code' => env('MAGENTO_STORE_CODE', 'all'),
'version' => env('MAGENTO_API_VERSION', 'V1'),
'access_token' => env('MAGENTO_ACCESS_TOKEN'),
'timeout' => 30,
'connect_timeout' => 10,
'authentication_method' => env('MAGENTO_AUTH_METHOD', 'token'),
],
'xsign' => [
'base_url' => env('MAGENTO_BASE_URL_XSIGN'),
'base_path' => env('MAGENTO_BASE_PATH', 'rest'),
'store_code' => env('MAGENTO_STORE_CODEXSIGN', 'xsign'),
'version' => env('MAGENTO_API_VERSION', 'V1'),
'access_token' => env('MAGENTO_ACCESS_TOKEN_XSIGN'),
'timeout' => 30,
'connect_timeout' => 10,
'authentication_method' => env('MAGENTO_AUTH_METHOD', 'token'),
],
]
When I attempt to use the connection() method to specify which configuration to use ('xsign' in this case), I receive the following error:

Error
Call to undefined method JustBetter\MagentoClient\Client\Magento::connection()
at app/Console/Commands/Xsign/SyncClientesToMagento.php:87
This occurs when trying to execute the command: $response = $this->magento->connection('xsign')->get($url, $queryParams);

I've checked the documentation and tried to ensure that my setup aligns with the provided examples, but I'm stuck on how to resolve this error. Could this be a version issue, or am I missing something in my implementation?

Thank you for any guidance you can provide.

Bulk

Hello,
I am trying to make a post:
$response = $this->magento->post('/rest/default/async/bulk/V1/inventory/source-items',
but it always gives a route error.

"message":"The request does not match any route.

Could you possibly provide some support, please?

Thank you very much.

Searching Customers

Getting the following error when trying to query customers:

$searchCriteria = SearchCriteria::make()
            ->paginate(1, 50)
            ->where('email', 'like', '%@test.com')
            ->get();

return $this->magento->get('customers', $searchCriteria);

Which returns:
{"message":"Request does not match any route."}

Anything I'm missing?

It can't be installed with Laravel 10

composer require justbetter/laravel-magento-client

Info from https://repo.packagist.org: #StandWithUkraine
./composer.json has been updated
Running composer update justbetter/laravel-magento-client
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires justbetter/laravel-magento-client * -> satisfiable by justbetter/laravel-magento-client[1.0.0, ..., 1.0.9].
    - justbetter/laravel-magento-client[1.0.0, ..., 1.0.9] require laravel/framework ^9.0 -> found laravel/framework[v9.0.0, ..., v9.52.4] but it conflicts with your root composer.json require (^10.0).

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require justbetter/laravel-magento-client:*" to figure out if any version is installable, or "composer require justbetter/laravel-magento-client:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

How can I fix this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.