Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Basic Shopify Api Laravel Package

gnikyt/basic-shopify-api

Tested Shopify API wrapper for PHP using Guzzle. Supports REST and GraphQL (sync/async), OAuth and private apps, rate limiting, retries, pagination, and helpers for install/authorize URLs, HMAC validation, call limits, middleware, and storage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require gnikyt/basic-shopify-api
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Gnikyt\ShopifyApi\ShopifyServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Gnikyt\ShopifyApi\ShopifyServiceProvider" --tag="config"
    

    Update .env with your Shopify API credentials:

    SHOPIFY_API_KEY=your_api_key
    SHOPIFY_API_SECRET=your_api_secret
    SHOPIFY_STORE_DOMAIN=your-store.myshopify.com
    SHOPIFY_ACCESS_TOKEN=your_access_token
    
  3. First Use Case: Fetching Products (PHP 8.1 Iterables)

    use Gnikyt\ShopifyApi\Facades\Shopify;
    
    // Works with PHP 8.1 iterable signature
    foreach (Shopify::products()->get() as $product) {
        // $product is now properly typed as an iterable item
        echo $product->title;
    }
    

Implementation Patterns

Core Workflows

  1. REST API Usage Use the fluent facade methods for common operations:

    // Create a product
    $product = Shopify::products()->create([
        'title' => 'New Product',
        'body_html' => '<strong>Description</strong>',
        'vendor' => 'Acme Corp',
    ]);
    
    // Update a product
    Shopify::products()->update($product->id, ['title' => 'Updated Title']);
    
    // Delete a product
    Shopify::products()->delete($product->id);
    
  2. GraphQL Queries (Private App Support) Execute custom GraphQL queries, including properly documented private app queries:

    $query = '
        query {
            products(first: 10) {
                edges {
                    node {
                        title
                        id
                    }
                }
            }
        }
    ';
    $result = Shopify::graphql()->query($query);
    
    // Private app queries (now fully documented)
    $privateQuery = '
        query {
            privateMetafields {
                edges {
                    node {
                        key
                    }
                }
            }
        }
    ';
    $privateResult = Shopify::graphql()->query($privateQuery, ['isPrivate' => true]);
    
  3. Pagination Handle paginated responses with iterable support:

    $products = Shopify::products()->get(['limit' => 50]);
    foreach ($products as $product) {
        // Process each product
    }
    
    // Or use nextPage() for full pagination
    while ($products->hasMorePages()) {
        $products = $products->nextPage();
        foreach ($products as $product) {
            // Process next batch
        }
    }
    
  4. Webhooks Register and manage webhooks with signature verification:

    // Register a webhook
    Shopify::webhooks()->register(
        'orders/create',
        'https://your-app.com/webhooks/shopify',
        ['topic' => 'orders']
    );
    
    // Verify webhook signatures
    $isValid = Shopify::webhooks()->verify($request);
    

Integration Tips

  • Laravel Ecosystem: Leverage Laravel’s Http client or Queue for async operations.
  • Caching: Cache frequent API calls with Laravel’s cache system:
    $products = Cache::remember('shopify_products', now()->addHours(1), function () {
        return Shopify::products()->get();
    });
    
  • Error Handling: Wrap API calls in try-catch blocks:
    try {
        $product = Shopify::products()->get($id);
    } catch (\Gnikyt\ShopifyApi\Exceptions\ShopifyException $e) {
        Log::error($e->getMessage());
        abort(500, 'Failed to fetch product');
    }
    
  • PHP 8.1 Iterables: The package now fully supports PHP 8.1 iterable signatures. Use foreach loops directly on responses:
    foreach (Shopify::products()->get() as $product) {
        // $product is now properly typed
    }
    

Gotchas and Tips

Common Pitfalls

  1. Authentication Issues

    • Ensure SHOPIFY_ACCESS_TOKEN is correct and has the required permissions.
    • For private apps, use SHOPIFY_API_KEY and SHOPIFY_API_SECRET with OAuth flow.
    • Debug with:
      Shopify::setDebug(true); // Logs raw API responses
      
  2. Rate Limiting

    • Shopify enforces rate limits (e.g., 2 calls/second for public apps).
    • Implement exponential backoff for retries:
      use Gnikyt\ShopifyApi\Exceptions\RateLimitExceededException;
      
      try {
          $response = Shopify::products()->get();
      } catch (RateLimitExceededException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  3. GraphQL Schema Changes

    • Shopify’s GraphQL schema evolves. Validate queries against the latest schema.
    • Use the Shopify::graphql()->introspect() method to inspect the schema dynamically.
    • Note: Private GraphQL queries are now fully documented in the package. Always use the isPrivate flag when needed.
  4. Webhook Delays

    • Shopify may retry failed webhook deliveries. Implement idempotency in your handlers:
      if (Shopify::webhooks()->verify($request) && $request->hasValidSignature()) {
          $order = $request->json()->get('order');
          // Process only if not already handled
          if (!Order::where('shopify_id', $order['id'])->exists()) {
              // Handle order
          }
      }
      

Debugging Tips

  • Enable Debug Mode:

    Shopify::setDebug(true);
    

    Check Laravel logs for raw API responses.

  • Log API Calls: Use Laravel’s tap to log inputs/outputs:

    Shopify::products()->get()->tap(function ($products) {
        Log::debug('Fetched products:', $products->toArray());
    });
    
  • PHP 8.1 Iterables Debugging: Ensure your loops are compatible with the new iterable signature:

    // Works with PHP 8.1
    foreach (Shopify::products()->get() as $product) {
        Log::debug('Product:', $product->title);
    }
    

Extension Points

  1. Custom Endpoints Extend the API client for unsupported endpoints:

    use Gnikyt\ShopifyApi\ShopifyClient;
    
    $client = new ShopifyClient();
    $response = $client->request('GET', '/admin/api/2023-07/custom_endpoint', []);
    
  2. Middleware Add custom middleware to the Guzzle client:

    Shopify::extend(function ($client) {
        $client->getEmitter()->attach(
            new \GuzzleHttp\Middleware::tap(function ($request) {
                // Modify request
            })
        );
    });
    
  3. Model Bindings Create Eloquent models with accessors for Shopify data:

    class ShopifyProduct extends Model
    {
        public function getTitleAttribute($value)
        {
            return ucfirst($value);
        }
    
        public static function fromShopify($data)
        {
            return static::create($data);
        }
    }
    
  4. PHP 8.1 Iterables in Collections

    • The package now fully supports PHP 8.1 iterable signatures. When working with collections, ensure compatibility:
    $products = Shopify::products()->get();
    foreach ($products as $product) {
        // $product is now properly typed
    }
    
    • For older PHP versions, use ->all() or ->toArray() if needed:
    $productsArray = Shopify::products()->get()->toArray();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor